php curl 模拟post上传文件应用实例
今天工作中遇到一个问题,客户端上传头像,我得到这个$_FILES头像信息,还需要通过模拟表单的type=file方式传递给公司的静态图片地址服务器,并最终从图片服务器拿到图片的绝对地址。
通过思考,实践,确定通过curl模拟表单来进行上传文件;
测试代码如下:
表单:1.html
<form method="POST" action="http://localhost/up.php" enctype="multipart/form-data">
用户头像:<input type="file" name="image">
<input type="submit" name="dosubmit">
</form>
处理程序:up.php
<?php
echo "<pre>";
print_r($_FILES);
$uploaddir = 'D:/';
$uploadfile = $uploaddir . basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
$url = "http://localhost/app.php";
$data = array(
"file1" => "@D:/".$_FILES['image']['name'], (这里需要注意:不能上传临时地址,而只能是存在的物理绝对路径)
);
print_r(uploadByCURL($data,$url));
function uploadByCURL($post_data,$post_url){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $post_url);
curl_setopt($curl, CURLOPT_POST, 1 );
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl,CURLOPT_USERAGENT,"Mozilla/4.0");
$result = curl_exec($curl);
$error = curl_error($curl);
return $error ? $error : $result;
}
?>
第二次,file提交的处理程序
app.php
<?php
echo "<pre>";
print_r($_FILES);$uploaddir = 'e:/';
$uploadfile = $uploaddir . basename($_FILES['file1']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['file1']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
?>通过这三个程序,图片就可以经过两次提交,最终得到图片的地址;
php curl 模拟post上传文件应用实例
转载
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
PHP CURL HTTPS POST
php模拟提交数据函数
加密 浏览器 用户 证书 认证 -
springsecurity 部门权限
方法级别权限控制1.jsr250 1.需要坐标 <dependency> <groupId>javax.annotation</groupId> <artifactId>jsr250-api</artifactId> <vers
springsecurity 部门权限 spring ci 当前用户