PHP7及PHP5.5以下基于curl实现多文件上传功能代码

时间:2019-06-24 作者:佚名 编辑:xiaoxin 来源:不甘平庸网

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

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

php5.5之前

<?php
$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

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

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

<?php
$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示例:

<?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);
?>
php curl上传多文件实现方法:

php5.5之前版本的写法

<?php
$file = array(
            'pic'=>"@E:\\wwwroot\\10003\\temp_56.ini;type=text/html;filename=temp_56.ini",
            'pic'=>"@E:\\wwwroot\\10003\\temp_29.html;type=text/html;filename=temp_29.html"
        );
?>
PHP5.5以上版本的写法

<?php

       $file = array(

           'pic'=>new CURLFile('E:\\wwwroot\\10003\\temp_56.ini', 'text/html', 'temp_56.ini'),

           'pic'=>new CURLFile('E:\\wwwroot\\10003\\temp_29.html', 'text/html', 'temp_29.html')

       );

?>


相关阅读
PHP心得推荐
频道推荐
本周推荐
点击排行