test.php:
<?php
header('content-type:text/html;charset=utf8');
$ch = curl_init();
//加@符号curl就会把它当成是文件上传处理
$data = array('img'=>'@'. dirname(__FILE__).'/img/1.jpg');
curl_setopt($ch,CURLOPT_URL,"http://localhost:8088/curl/get_img.php");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$result = curl_exec($ch);
curl_close($ch);
echo json_decode($result);
?>
get_img.php:
<?php
if($_FILES){
$filename = $_FILES['img']['name'];
$tmpname = $_FILES['img']['tmp_name'];
if(move_uploaded_file($tmpname,dirname(__FILE__).'/upload/'.$filename)){
echo json_encode('上传成功');
}else{
$data = json_encode($_FILES);
echo $data;
}
}
?>
当我访问test.php时将会显示“上传成功”,且upload文件夹下会生成1.jpg图片文件。模拟php curl向远程服务器上传文件