Example analysis of cURL file uploading function compatible with php5 and php7

  • 2021-09-24 21:53:30
  • OfStack

This article illustrates the cURL file upload function compatible with php5 and php7. Share it for your reference, as follows:

Why write this example

Recently modified 1 project, you need to upload files through cURL.

I remember that I had done similar implementation before, so I turned out the previous code and used the "@" prefix.

But the same method doesn't work now! Later, it was discovered that it was a version compatibility problem.

In the spirit of open source sharing and avoiding forgetting, I wrote the following example program.

Sample program

Special note:

A total of 3 files, all in the web root directory under the test directory, while ensuring that the directory is writable. Uploaded pictures are also saved in this directory.

If you want to run the program files in a different directory, you must change the relevant URL in the php code, otherwise the example may not run.


<html>
<head>
  <title> Upload sample </title>
</head>
<body>
  <div> Upload the file to the intermediate script below :</div>
  <br />
  <form action="upload.php" method="post" enctype="multipart/form-data">
     Select a file :
    <input type="file" name="file" />
    <input type="submit" value=" Upload " />
  </form>
</body>
</html>


<?php
/**
 *  Receive files uploaded through browsers 
 *
 * @author Straiway<straiway@qq.com>
 * @site  http://straiway.sinaapp.com
 */
if (empty($_FILES['file'])) {
  exit(' No file with the specified name was uploaded ');
}
//  Save to local first , Upload again 
$file   = $_FILES['file'];
$file_name = __DIR__ . "/{$file['name']}";
move_uploaded_file($_FILES['file']['tmp_name'], $file_name);
//  When testing locally , You may need to change the following URL
$ch = curl_init('http://localhost/test/upload_via_curl.php');
//  From php5.5 Begin , Oppose the use of "@" Upload in prefix mode , You can use the CURLFile Substitution ;
//  It is said that php5.6 Begin to remove "@" How to upload prefixes 
if (class_exists('CURLFile')) {
  $file = new CURLFile($file_name);
  //  Disable "@" Upload method , In this way, it can be transmitted safely "@" Parameter value at the beginning 
  curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
} else {
  $file = "@{$file_name}";
}
//  From php5.2 Begin , To upload a file , Must be given CURLOPT_POSTFIELDS Passing array , Not a string. 
//  Only passing arrays ,http Head "Content-Type" Will be set to "multipart/form-data"
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file_via_curl' => $file));
//  The transmission result is used as curl_exec Return value of , Instead of direct output 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$error = curl_error($ch);
if ($result) {
  $result_array = json_decode($result, true);
  if ($result_array) {
    if ($result_array['status']) {
      exit(" Upload succeeded !curl Return to Picture Address :{$result_array['data']['url']}<br /><img src='{$result_array['data']['url']}' />");
    } else {
      exit("curl Upload failed ! Error message :{$result['info']}");
    }
  } else {
    exit(" An error occurred ,curl Return results :{$result}");
  }
} else {
  exit('curl Error in request ' . var_export($error, true));
}


<?php
/**
 *  Accept and pass curl Uploaded files. 
 *
 * @author Straiway<straiway@qq.com>
 * @site  http://straiway.sinaapp.com
 */
if (empty($_FILES['file_via_curl'])) {
  $return = array('status' => 0, 'info' => ' No file with the specified name was uploaded ');
} else {
  //  Save a file 
  $file = $_FILES['file_via_curl'];
  //  Rename file , Easy to identify 
  $base_name = explode('.', $file['name']);
  $base_name[0] .= '_upload_var_curl';
  $base_name = implode('.', $base_name);
  $file_name = __DIR__ . "/{$base_name}";
  if (move_uploaded_file($file['tmp_name'], $file_name)) {
    //  When testing locally , You may need to change the following URL
    $url  = "http://localhost/test/{$base_name}";
    $return = array('status' => 1, 'info' => ' Upload succeeded ', 'data' => array('url' => $url));
  } else {
    $return = array('status' => 0, 'info' => ' Upload failed ');
  }
}
exit(json_encode($return));

References

http://php.net/manual/en/function.curl-setopt.php

https://www.ofstack.com/article/139950.htm

For more readers interested in PHP related content, please check the topics of this site: "php curl Usage Summary", "PHP Network Programming Skills Summary", "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary" and "PHP Operation and Operator Usage Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: