文件发布/通过php中的curl上传

时间:2016-09-14 08:33:49

标签: php curl

这是我的卷曲启动代码:

  $target="url/curlUploadHandler.php";
  $args = new CURLFile('down.png', 'image/png','test'); //file to post
  $postFields = array('file' => $args);
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $target);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl,CURLOPT_SAFE_UPLOAD, true);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
  $r = curl_exec($curl);
  curl_close($curl);
  print_r($r); // to get response from the page 

这是为了检查给定文件是否被发布:

curlUploadHandler.php

       if($_REQUEST){
               var_dump($_REQUEST);
          }

if( $_FILES ) {
       var_dump($_FILES );}

我正在本地测试此代码。发布字符串或整数字段工作正常,但发布图像或任何其他文件并没有给我任何输出。我错过了cURL中的一些选项或做错了什么吗?我已经检查了文档php docs。请帮帮我。

请在downvoting之前发表评论:/如果你必须:(

2 个答案:

答案 0 :(得分:1)

$ target必须是" http://[HOST]/url/curlUploadHandler.php"

检查错误

if( $errno = curl_errno($curl) ) { 
    $error_message = curl_strerror($errno); 
    echo "cURL error ({$errno}):\n {$error_message}"; 
}   

  • 输入你的代码echo getcwd();检查完整路径
  • 使用is_readable图像检查
  • 检查图像的权限

答案 1 :(得分:1)

使用:

$target="url/curlUploadHandler.php";  
$file_name_with_full_path = realpath('down.png');
$post = array('extra_info' => 'test','file_contents'=>'@'.$file_name_with_full_path);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);
print_r($result);

您还可以参考以获得更好的理解:http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/