先研究完curl同域上传图片然后再研究curl跨域上传,先把同域上传代码总结如下:
index.php
<?php //图片上传 $url = "http://192.168.1.230/curl/receive.php"; $post_data = array ( "foo" => "bar", // 要上传的本地文件地址;从php5.5.0开始弃用@方式,改用new CURLFile()方式 "upload" => new CURLFile("D:/workspace/xlyy/curl/img/1.png"),//路径必须是磁盘的绝对路径 ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); $output = curl_exec($ch); curl_close($ch); echo '<pre>'; print_r(json_decode($output,true)); echo '</pre>';
receive.php
<?php if($_FILES){ $filename = $_FILES['upload']['name']; $tmpname = $_FILES['upload']['tmp_name']; if(move_uploaded_file($tmpname,dirname(__FILE__).'/upload/'.$filename)){ echo json_encode('上传成功',JSON_UNESCAPED_UNICODE); }else{ echo json_encode('上传失败',JSON_UNESCAPED_UNICODE); } } ?>
注意:php5.5.0开始弃用@方式,改用new CURLFile()方式