模拟php curl向远程服务器上传文件

时间:2024-06-13 10:04:26

test.php

<?php
header('content-type:text/html;charset=utf8'); $file = dirname(__FILE__).'/1.jpg';
$data['img'] = new CurlFile($file);
$url = "http://localhost/test/img/get_img.php"; $ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
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)
{
file_put_contents('img.txt', json_encode($_FILES));//记录log
$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图片文件