且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用curl和PHP上传文件

更新时间:2023-02-21 20:40:29

使用:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

您也可以参考:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

PHP 5.5+ 的重要提示:

现在我们应该使用 https://wiki.php.net/rfc/curl-文件上传,但如果您仍想使用这种已弃用的方法,则需要设置 curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);