Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PHP curl methods upload a file and a string with a leading @ character in the same request?

Tags:

php

curl

I'd like to construct a POST request using PHP curl_* methods that does the following:

  1. uploads a file (so the request must be submitted as multipart/form-data)
  2. sends a string of text, where the string starts with an "@" character

For example, the following code works because there is no leading "@" character in the string of text:

<?php

$postfields = array(
    'upload_file' => '@file_to_upload.png',
    'upload_text' => 'text_to_upload'
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://example.com/upload-test');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
curl_exec($curl);
curl_close($curl);

?>

But, it breaks if the string starts with an "@" character which causes curl looks for a non-existent file named "text_to_upload" (Note that the only change is the addition of a leading "@" character in the upload_text field):

<?php

$postfields = array(
    'upload_file' => '@file_to_upload.png',
    'upload_text' => '@text_to_upload'
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://example.com/upload-test');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
curl_exec($curl);
curl_close($curl);

?>

So... is it possible to send text with a leading "@" character while uploading a file at the same time using the curl_* methods in PHP?

The end result (if possible) should be the equivalent of this command line use of curl:

curl -F 'upload_=@file_to_upload.png' --form-string 'upload_text=@text_to_upload' 'http://example.com/upload-test'

Thanks!

like image 207
user167628 Avatar asked Nov 05 '22 00:11

user167628


1 Answers

Prepend the string with the null character"\0":

<?php
    $postfields = array(
        'upload_file' => '@file_to_upload.png',
        'upload_text' => sprintf("\0%s", '@text_to_upload')
    );

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, 'http://example.com/upload-test');
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
    curl_exec($curl);
    curl_close($curl);
?>
like image 166
rcambrj Avatar answered Nov 12 '22 10:11

rcambrj