PHP7基于curl实现的上传图片功能

本文实例讲述了PHP7基于curl实现的上传图片功能。分享给大家供大家参考,具体如下:

根据php版本不同,curl模拟表单上传的方法不同

php5.5之前:

  1. $curl = curl_init();
  2. if (defined('CURLOPT_SAFE_UPLOAD')) {
  3. curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
  4. }
  5. $data = array('file' => '@' . realpath($path));//‘@' 符号告诉服务器为上传资源
  6. curl_setopt($curl, CURLOPT_URL, $url);
  7. curl_setopt($curl, CURLOPT_POST, 1 );
  8. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  9. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  10. curl_setopt($curl, CURLOPT_USERAGENT,"TEST");
  11. $result = curl_exec($curl);
  12. $error = curl_error($curl);

php5.5之后,到php7:

  1. $curl = curl_init();
  2. curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
  3. $data = array('file' => new \CURLFile(realpath($path)));
  4. url_setopt($curl, CURLOPT_URL, $url);
  5. curl_setopt($curl, CURLOPT_POST, 1 );
  6. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  7. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  8. curl_setopt($curl, CURLOPT_USERAGENT,"TEST");
  9. $result = curl_exec($curl);
  10. $error = curl_error($curl);

下面提供一个兼容的方法:

  1. $curl = curl_init();
  2. if (class_exists('\CURLFile')) {
  3. curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
  4. $data = array('file' => new \CURLFile(realpath($path)));//>=5.5
  5. } else {
  6. if (defined('CURLOPT_SAFE_UPLOAD')) {
  7. curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
  8. }
  9. $data = array('file' => '@' . realpath($path));//<=5.5
  10. } //phpfensi.com
  11. curl_setopt($curl, CURLOPT_URL, $url);
  12. curl_setopt($curl, CURLOPT_POST, 1 );
  13. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  14. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  15. curl_setopt($curl, CURLOPT_USERAGENT,"TEST");
  16. $result = curl_exec($curl);
  17. $error = curl_error($curl);

其中:

$path:为待上传的图片地址

$url:目标服务器地址

例如:

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

upload.php示例:

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