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

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

php5.5之前

$curl = curl_init();
if (defined('CURLOPT_SAFE_UPLOAD')) {
  curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
}
$data = array('file' => '@' . realpath($path));//‘@' 符号告诉服务器为上传资源
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);

php5.5之后,到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);

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

$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);

其中:

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

$url:目标服务器地址

例如

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

upload.php示例:

<".json", json_encode($_FILES));
  $tmp_name = $_FILES['file']['tmp_name'];
  $name = $_FILES['file']['name'];
  move_uploaded_file($tmp_name,'audit/'.$name);
"_blank" href="https://www.jb51.net/Special/66.htm">php curl用法总结》、《PHP网络编程技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《PHP数据结构与算法教程》、《php程序设计算法总结》、《PHP运算与运算符用法总结》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

标签:
PHP7,curl,上传图片

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
桃源资源网 Design By www.nqtax.com

评论“PHP7基于curl实现的上传图片功能”

暂无“PHP7基于curl实现的上传图片功能”评论...