本篇文章为大家展示了怎么在PHP7项目中使用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示例:
<?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项目中使用curl实现一个图片上传功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。