I have a script that sends a post
request to /usr/bin/php-cgi
. The script is working fine when dealing with plain text, but fails when the data is binary:
$data = file_get_contents('example.jpg');
$size = filesize('example.jpg') + 5;
$post_data = 'file='.$data;
$response = shell_exec('echo "'.$post_data.'" |
REDIRECT_STATUS=CGI
REQUEST_METHOD=POST
SCRIPT_FILENAME=/example/script.php
SCRIPT_NAME=/script.php
PATH_INFO=/
SERVER_NAME=localhost
SERVER_PROTOCOL=HTTP/1.1
REQUEST_URI=/example/index.html
HTTP_HOST=example.com
CONTENT_TYPE=application/x-www-form-urlencoded
CONTENT_LENGTH='.$size.' php-cgi');
I get the following error:
sh: -c: line 1: unexpected EOF while looking for matching `"'
sh: -c: line 5: syntax error: unexpected end of file
I guess this is because the data I'm trying to send is binary and must be encoded/escaped somehow.
Like I said the above code works if the data is plain text:
$post_data = "data=sample data to php-cgi";
$size = strlen($post_data);
I also tried to encode the data using base64_encode()
but then I face another problem; the data must be decoded from within the receiving script. I was thinking that perhaps I could encode the data in base64
and then add some content or mime type header to force the php-cgi
binary to make the conversation?
One other problem is that I like to send the data as an attachment and therefore I think we must set CONTENT_TYPE
to multipart/form-data; boundary=<random_boundary>
and CONTENT_DISPOSITION
to form-data
, but I'm not sure how to set these headers from the commandline.