本文实例讲述了PHP7基于curl实现的上传图片功能-formdata格式上传图片

 

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

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

php5.5之前

1
2
3
4
5
6
7
8
9
10
11
12
$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

1
2
3
4
5
6
7
8
9
10
$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);

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$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:目标服务器地址

例如

1
2
$path = "/bg_right.jpg"

upload.php示例:

1
2
3
4
5
6
<?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);
?>

 

PHP7.0演示示例

/**xm编写php7.0模拟fomadata文件上传
 * @param $url
 * @param $arr
 */
function curl_post_file($url,$arr){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
    //$data = array('media' => new \CURLFile(realpath($p)));
    $data=$arr;
    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);
    return $result;
}

  调用演示-微信敏感人物检测

 $url = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=".$token;
 $p=str_replace("\\","/",ROOT_PATH."public".$pic);//图片路径
 $data = array('media' => new \CURLFile(realpath($p)));
 $mgan_json=curl_post_file($url,$data);

  

posted @ 2020-09-14 18:52  心雨星空  阅读(822)  评论(0编辑  收藏  举报