2024年03月21日 php远程上传 php上传文件 curl上传文件 懒猪技术
当使用单独的服务器来存储图片的时候最大的问题就是如何把上传的图片从主服务器保存到图片服务器。而php中curl扩展可以实现向别的服务器发起请求和传送数据,今天要分享的实现远程上传图片到另一台服务器页正是利用curl扩展的这一特性来实现。
为了更好的理解下面通过代码示例来讲解。
主服务器程序:
echo "<pre>";
if(!empty($_FILES['img'])){
$tmp_name = $_FILES['img']['tmp_name'];
$url = "http://www.a.com/index.php";//这里是图片服务器的上传图片处理接口
img_curl($url, $tmp_name);
}
//把主服务器上传的图片通过curl传送给图片服务器
function img_curl($url, $path){
$curl = curl_init();
if (class_exists('\CURLFile')) {
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$data = array('file' => new \CURLFile(realpath($path)));//php版本>=5.5
} else {
if (defined('CURLOPT_SAFE_UPLOAD')) {
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
}
$data = array('file' => '@' . realpath($path));//php版本<=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);
var_dump($result);
}图片服务器对主服务器传送过来的图片进行处理:
//主服务器通过curl传递过来的图片数据存储在$_FILES,
$filename = date('YmdHis',time()).'.jpg';
$tmpname = $_FILES['file']['tmp_name'];
$url = 'image/';//图片服务器图片存储目录
var_dump(scandir($url));//scardir:浏览制定目录下的文件
var_dump(move_uploaded_file($tmpname, $url.$filename));//move_uploaded_file
// 将接受到的图片进行重命名保存
var_dump(scandir($url));
本文链接:http://so.lmcjl.com/news/112/