周六 13 3月 2010
PHP使用CURL上传文件的函数
Posted by Semon under DEV, PHP
No Comments
一般的文件上传是通过html表单进行的,通过CURL可以不经过浏览器,直接在服务器端模拟进行表单提交,完成POST数据、文件上传等功能。需要被上传的文件需要在文件名前加上“@”以示区分,并且,文件名需要是完整路径。
以下php函数来模拟html表单的提交数据:
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; }
函数的使用:
$url = "http://127.0.0.1/app.php"; $data = array( "username" => $username, "password" => $password, "file1" => "@".realpath("photo1.jpg"), "file2" => "@".realpath("file2.xml") ); print_r(uploadByCURL($data,$url));