Upload picture function of PHP7 based on curl

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

In this paper, an example is given to describe the uploading picture function of PHP7 based on curl. Share it for your reference, as follows:

Depending on the php version, the curl simulation form upload method is different

Before php5.5


$curl = curl_init();
if (defined('CURLOPT_SAFE_UPLOAD')) {
  curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
}
$data = array('file' => '@' . realpath($path));// ' @'  Symbol tells the server to upload resources 
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1 );
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT,"TEST");
$result = curl_exec($curl);
$error = curl_error($curl);

After php5.5, to php7


$curl = curl_init();
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$data = array('file' => new \CURLFile(realpath($path)));
url_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1 );
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT,"TEST");
$result = curl_exec($curl);
$error = curl_error($curl);

Here is a compatible method:


$curl = curl_init();
if (class_exists('\CURLFile')) {
 curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$data = array('file' => new \CURLFile(realpath($path)));//>=5.5
} else {
 if (defined('CURLOPT_SAFE_UPLOAD')) {
  curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
 }
 $data = array('file' => '@' . realpath($path));//<=5.5
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1 );
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT,"TEST");
$result = curl_exec($curl);
$error = curl_error($curl);

Among them:

$path: Is the address of the picture to be uploaded

$url: Target server address

For example


$url="http://localhost/upload.php";
$path = "/bg_right.jpg"

upload. php example:


<?php
  file_put_contents(time().".json", json_encode($_FILES));
  $tmp_name = $_FILES['file']['tmp_name'];
  $name = $_FILES['file']['name'];
  move_uploaded_file($tmp_name,'audit/'.$name);
?>

For more readers interested in PHP related contents, please check out the topics on 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", "PHP Operation and Operator Usage Summary" and "php Common Database Operation Skills Summary"

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


Related articles: