Can PHP curl methods upload a file and a string with a leading @ character in the same request?
I'd like to construct a POST request using PHP curl_* methods that does the following:
- uploads a file (so the request must be submitted as multipart/form-data)
- 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' => '@tex开发者_如何学编程t_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);
?>
Alternative 1
Most probably you will have to urlencode the parameter.
$postfields = array(
'upload_file' => '@file_to_upload.png',
'upload_text' => urlencode('@text_to_upload')
);
Also, urldecode at server side.
Alternative 2
Simply add an space at the beginning of upload_text
regardless of its content.
$postfields = array(
'upload_file' => '@file_to_upload.png',
'upload_text' => ' @text_to_upload'
);
精彩评论