PHP7基于curl實(shí)現(xiàn)的上傳圖片功能
本文實(shí)例講述了PHP7基于curl實(shí)現(xiàn)的上傳圖片功能。分享給大家供大家參考,具體如下:
根據(jù)php版本不同,curl模擬表單上傳的方法不同
php5.5之前
$curl = curl_init();
if (defined('CURLOPT_SAFE_UPLOAD')) {
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
}
$data = array('file' => '@' . realpath($path));//‘@' 符號告訴服務(wù)器為上傳資源
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);
下面提供一個(gè)兼容的方法:
$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:目標(biāo)服務(wù)器地址
例如
$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); ?>
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php curl用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計(jì)算法總結(jié)》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。
相關(guān)文章
深入理解curl類,可用于模擬get,post和curl下載
本篇文章是對curl類,可用于模擬get,post和curl下載進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06
php簡單實(shí)現(xiàn)短網(wǎng)址(短鏈)還原的方法(測試可用)
這篇文章主要介紹了php簡單實(shí)現(xiàn)短網(wǎng)址還原的方法,以腳本之家短網(wǎng)址http://t.cn/heEHwk為例介紹了php還原短網(wǎng)址的實(shí)現(xiàn)技巧,非常簡單實(shí)用,需要的朋友可以參考下2016-05-05
php 的加密函數(shù) md5,crypt,base64_encode 等使用介紹
php 在做注冊、登錄或是url 傳遞參數(shù)時(shí)都會(huì)用到 字符變量的加密,下面我們就來簡單的介紹下:php 自帶的加密函數(shù)2012-04-04

