PHP7基于curl實現的上傳圖片功能
本文實例講述了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示例:
<?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相關內容感興趣的讀者可查看本站專題:《php curl用法總結》、《PHP網絡編程技巧總結》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》、《PHP數據結構與算法教程》、《php程序設計算法總結》、《PHP運算與運算符用法總結》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
相關文章
深入理解curl類,可用于模擬get,post和curl下載
本篇文章是對curl類,可用于模擬get,post和curl下載進行了詳細的分析介紹,需要的朋友參考下2013-06-06
php 的加密函數 md5,crypt,base64_encode 等使用介紹
php 在做注冊、登錄或是url 傳遞參數時都會用到 字符變量的加密,下面我們就來簡單的介紹下:php 自帶的加密函數2012-04-04

