I'd like to construct a POST request using PHP curl_* methods that does the following:
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!
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);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With