Nasıl form alanlarını göndermek ve PHP Curl kullanarak bir dosya?

2 Cevap php

Php curl kullanarak bir web hizmetine form alanları ve dosyayı göndermek çalışıyorum. Form zaten bir vekil php istemci web uygulaması için bir tarayıcıdan geçti ve ben web hizmetine iletmek için çalışıyorum.

Böyle curl_setopt bir dizi geçirdiğinizde:

curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->fields);

Bir dizi çekmek içindir rağmen ben dize haber için bir dizi olsun. İşte kurucusuna bu-> alanları $ geçirilir benim dizi var.

$fields = array('title'=>$title,
'content'=>$content,
'category'=>$category,
'attachment'=>$_FILES['attachment']);

I http_build_query benim web serivce hakkında multipart / form verilerini sahip yakınıyor kullanarak bir dize geçirirseniz.

Sonra kullanarak multipart / form EncType zorlarsanız curl_setopt Ben hiçbir sınır yoktur söyleyerek bir hata alıyorum:

org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

Herhangi bir fikir?

2 Cevap

Dize dizisi Aşağıdaki kod ile var dikkat edin:

$fields = array(
  'title'=>$title,
  'content'=>$content,
  'category'=>$category,
  'attachment'=>$_FILES['attachment']
);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $fields);

Eğer curl_setopt için 3 parametre olarak bir dizi geçiyoruz değil çünkü: Eğer attachment için bir dizi geçiyoruz çünkü bu.


If you want to pass a file this way, you should pass its absolute path, pre-pending a @ before it :

$fields = array(
  'title'=>$title,
  'content'=>$content,
  'category'=>$category,
  'attachment'=> '@' . $_FILES['attachment']
);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $fields);

(This is supposing that $_FILES['attachment'] dosyanızın tam yolunu içerir - gerekirse o ), doğru veri kullanıyor nedenle sizin kadar bu kodu değiştirmek için


As a reference, quoting the manual page of curl_setopt, for the CURLOPT_POSTFIELDS option :

The full data to post in a HTTP "POST" operation.
To post a file, prepend a filename with @ and use the full path.
This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.
If value is an array, the Content-Type header will be set to multipart/form-data.

Bu deneyin,

$filePath = "abc\\xyz.txt";         

$postParams["uploadfile"] = "@" . $filePath;


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_URL, 'https://website_address');
        curl_setopt($ch, CURLOPT_POST, 1 );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);

        if (curl_errno($ch))
            {
                echo curl_error($ch);               
                exit();                         
            }
        curl_close($ch);