NiniGeek NiniGeek - 24 days ago 10
PHP Question

PHP didn't receive file from JAVA app

A Java app which I can't modify is sending a csv file to my PHP script via a

POST
request.
$_POST
and
$_FILES
are empty.

Max file size are set
5Mb
and my file don't exceed it.

Here is the wireshark dump of the Java app's request:

http://i.stack.imgur.com/mFX6z.jpg

How I can receive the file with PHP?

Here is my actual test code:

$old_error_handler = set_error_handler('myErrorHandler');
set_exception_handler('myExceptionHandler');

file_putcontents(dirname(__FILE__).DIRECTORY_SEPARATOR.'post.txt',
print_r(array_merge($_REQUEST, $_FILES), true));

$expectedAmountOfDataInBytes = $_SERVER['CONTENT_LENGTH'];
$contents = '';
while(0 < $expectedAmountOfDataInBytes--) {
$contents .= fread( STDIN, 1 );
}

fclose(STDIN);

file_put_contents(dirname(__FILE__).DIRECTORY_SEPARATOR.'file.csv', $contents);


function myErrorHandler($errno, $errstr, $errfile, $errline) {
file_put_contents(dirname(__FILE__).DIRECTORY_SEPARATOR.'error.txt',
print_r(array(
'date' => date(DateTime::W3C),
'no' => $errno,
'error' => $errstr,
'file' => $errfile,
'line' => $errline
), true), FILE_APPEND);
die();
}

function myExceptionHandler(Exception $exception) {
file_put_contents(dirname(__FILE__).DIRECTORY_SEPARATOR.'error.txt',
print_r(array(
'date' => date(DateTime::W3C),
'code' => $exception->getCode(),
'file' => $exception->getFile(),
'Line' => $exception->getLine(),
'Message' => $exception->getMessage(),
'Trace' => $exception->getTrace()
), true), FILE_APPEND);
die();
}


My results (post.txt):

Array
(
)


file.csv
is empty.

Web server specs:


  • Apache/2.2.22

  • PHP 5.4.4-14


Answer

http_get_request_body or HttpResponse didn't work. And now the PHP doc is outdated. To use it: \http\Env::getRequestBody(). See the doc.

The solution that worked in the end (PHP 5.4):
Php configuration in the php.ini:

enable_post_data_reading = 0

Or .htaccess:

php_value enable_post_data_reading 0

Documentation

PHP code:

$write = fopen(dirname(__FILE__).DIRECTORY_SEPARATOR.'test.csv','w+');
$read = fopen('php://input','r');
stream_copy_to_stream($read,$write);

With enable-post-data-reading, you can use php://input with multipart/form-data request.