Write Post data to file with PHP

1) In PHP, to get POST data from an incoming request use the $_POST array. The POST array in PHP is associative, which means that each incoming parameter will be a key-value pair. In development it's helpful to understand what you're actually getting in $_POST. You can dump the contents using printf() or var_dump() like the following.

var_dump($_POST);

-- or --

printf($_POST);

2) Choose a useful string-based format for storing the data. PHP has a serialize() function, which you could use to turn the array into a string. It's also easy to turn the array into a JSON string. I suggest using JSON since it's natural to use this notation across various languages (whereas using a PHP serialization would somewhat bind you to using PHP in the future). In PHP 5.2.0 and above the json_encode() function is built-in.

$json_string = json_encode($_POST);

// For info re: JSON in PHP:
// http://php.net/manual/en/function.json-encode.php

3) Store the string in a file. Try using fopen(), fwrite(), and fclose() to write the json string to a file.

$json_string = json_encode($_POST);

$file_handle = fopen('my_filename.json', 'w');
fwrite($file_handle, $json_string);
fclose($file_handle);

// For info re: writing files in PHP:
// http://php.net/manual/en/function.fwrite.php

You'll want to come up with a specific location and methodology to the file paths and file names used.

Note: There's also the possibility of getting the HTTP request's POST body directly using $HTTP_RAW_POST_DATA. The raw data will be URL-encoded and it will be a string that you can write to a file as described above.


Simple as:

file_put_contents('test.txt', file_get_contents('php://input'));

Tags:

Php

Http

Text

Post