Php 以curl作为字符串发布文件

Php 以curl作为字符串发布文件,php,curl,Php,Curl,我正在尝试使用curl和php上传一个文件,代码如下。我使用http_build_查询而不是数组将post数据作为字符串传递,因为post数据是由多部分组成的数组。代码工作,除了我不能得到图片上传 $ch = curl_init(); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, true)

我正在尝试使用curl和php上传一个文件,代码如下。我使用http_build_查询而不是数组将post数据作为字符串传递,因为post数据是由多部分组成的数组。代码工作,除了我不能得到图片上传

$ch = curl_init();
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIE, $cookie1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);

$image=file_get_contents(realpath('image.jpg'));
    $postFields = array(
         'authenticity_token'=>$token1.'=',
         'menu_item'=>array('name'   => $name,
         'body'=>'',
         'published'=>0,
         'published'=>1,
         'picture'=>$image,
    );


        $postData=http_build_query($postFields);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_exec ($ch);

首先,确定你想做什么。如果你想做正常的表单发布,那么从你的代码中删除下面的标题,它应该可以工作

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
现在,如果要通过curl进行多部分/表单数据过帐,请执行以下操作:

$postFields = array(
     'authenticity_token'=>$token1.'=',
     'menu_item'=>array('name'   => $name,
     'body'=>'',
     'published'=>0,
     'published'=>1,
     'picture'=> '@' . $image, // better to use path like 'c:/temp/image.jpg'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

无法在我的多维post数组上使用http\u build\u查询完成此操作。。。服务器不会上载该文件。必须像http那样使用嵌套部分创建数组

    $postFields['authenticity_token'=$token1.'=';
    $postFields['menu_item[name]']=$name;        
    $postFields['menu_item[body]']='';
    $postFields['menu_item[published]']=0;
    $postFields['menu_item[published]']=1;
    $postFields['menu_item[picture]']='@'.$image;

curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);

你能发布你的完整代码吗?你能检查一下前面提到的这些问题的答案吗。[链接]还有这个。[链接]在这些链接中找不到我的问题的答案。。。尽管对第一个链接的评论可能会让我对我的问题有所了解:VolkerK完全正确,但我的经验表明,发送file@operator只能处理数组$post['file']=@file\u Path现在您可以使用CURLOPT\u postfield发送文件您是正确的,删除头并没有阻止我的代码工作。。。但仍然没有上传图像。但是,在没有http_build_查询的情况下发布数组不起作用,并且会给我一个400错误,因为$postFields是一个多维数组;使用您的代码,并通过更新您的问题向我们显示日志打印。curl_setopt$ch,CURLOPT_VERBOSE,1$verbose=fopen'verboselog.txt','ab+';curl_setopt$ch,CURLOPT_STDERR$verbose;curl_exec$ch-添加此代码会给我一个空日志verboselog.txt从何而来??检查apache访问日志或错误日志文件以获取调试消息!