ОПУБЛИКОВАТЬ строку файла с помощью cURL в PHP?


Мне было интересно, можно ли опубликовать файл - вместе с другими данными формы - когда файл представляет собой просто строку?

Я знаю, что вы можете опубликовать файл, который уже находится в файловой системе, добавив в путь к файлу префикс "@".

Однако я хотел бы обойти создание временного файла и отправить только файл в виде строки, но я не уверен, как построить запрос с помощью cURL в PHP.

Приветствия

    $postFields = array(
        'otherFields'   => 'Yes'
        ,'filename'     => 'my_file.csv'
        ,'data'         => 'comma seperated content'
    );

    $options = array(
        CURLOPT_RETURNTRANSFER  => true
        ,CURLOPT_SSL_VERIFYPEER => false
        ,CURLOPT_SSL_VERIFYHOST => 1
        ,CURLOPT_POSTFIELDS     => $postFields
        ,CURLOPT_HTTPHEADER     => array(
            'Content-type: multipart/form-data'
        )
    );
Author: gawpertron, 2010-06-21

2 answers

Должно быть возможно: вот форма, опубликованная через браузер (не относящиеся к делу поля опущены):

POST http://host.example.com/somewhere HTTP/1.1
Content-Type: multipart/form-data; boundary=---------------------------7da16b2e4026c
Content-Length: 105732

-----------------------------7da16b2e4026c
Content-Disposition: form-data; name="NewFile"; filename="test.jpg"
Content-Type: image/jpeg

(...raw JPEG data here...)
-----------------------------7da16b2e4026c
Content-Disposition: form-data; name="otherformfield"

content of otherformfield is this text
-----------------------------7da16b2e4026c--

Итак, если мы сами создадим текст сообщения и установим один или два дополнительных заголовка, мы сможем смоделировать следующее:

// form field separator
$delimiter = '-------------' . uniqid();
// file upload fields: name => array(type=>'mime/type',content=>'raw data')
$fileFields = array(
    'file1' => array(
        'type' => 'text/plain',
        'content' => '...your raw file content goes here...'
    ), /* ... */
);
// all other fields (not file upload): name => value
$postFields = array(
    'otherformfield'   => 'content of otherformfield is this text',
    /* ... */
);

$data = '';

// populate normal fields first (simpler)
foreach ($postFields as $name => $content) {
   $data .= "--" . $delimiter . "\r\n";
    $data .= 'Content-Disposition: form-data; name="' . $name . '"';
    // note: double endline
    $data .= "\r\n\r\n";
}
// populate file fields
foreach ($fileFields as $name => $file) {
    $data .= "--" . $delimiter . "\r\n";
    // "filename" attribute is not essential; server-side scripts may use it
    $data .= 'Content-Disposition: form-data; name="' . $name . '";' .
             ' filename="' . $name . '"' . "\r\n";
    // this is, again, informative only; good practice to include though
    $data .= 'Content-Type: ' . $file['type'] . "\r\n";
    // this endline must be here to indicate end of headers
    $data .= "\r\n";
    // the file itself (note: there's no encoding of any kind)
    $data .= $file['content'] . "\r\n";
}
// last delimiter
$data .= "--" . $delimiter . "--\r\n";

$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_HTTPHEADER , array(
    'Content-Type: multipart/form-data; boundary=' . $delimiter,
    'Content-Length: ' . strlen($data)));  
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);

Таким образом, мы сами выполняем всю тяжелую работу и доверяем Керлу, чтобы он не повредил ее.

 26
Author: Piskvor, 2012-09-06 18:43:00

Php имеет доступ к временному местоположению "php://память", что на самом деле делает то, что вы пытаетесь сделать, довольно простым.

$fh = fopen('php://memory','rw');
fwrite( $fh, $content);
rewind($fh);

$options = array(
    CURLOPT_RETURNTRANSFER  => true
    ,CURLOPT_SSL_VERIFYPEER => false
    ,CURLOPT_SSL_VERIFYHOST => 1
    ,CURLOPT_HTTPHEADER     => array(
        'Content-type: multipart/form-data'
    )
    ,CURLOPT_INFILE         => $fh
    ,CURLOPT_INFILESIZE     => strlen($content)
);
 15
Author: erik.wiffin, 2010-06-21 16:12:02