Reputation: 3
I am trying to write content from a form to a text file, and don't know why it is not working. I have uploaded the code on a free host like 000webhost and everything works fine. So not sure if there is some misconfiguration to my CentOS server which is CentOS release 6.5 (Final). Or if there is something wrong with the code, any help would be much appreciated.
<?php
header("Location: http://www.example.com");
$handle = fopen("data.txt", "a");
foreach($_POST as $variable => $value)
{
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
Upvotes: 0
Views: 691
Reputation: 2617
Make sure you have the correct permissions to the folder you're trying to write to. It's probably getting by the apache user (www-data) or equiv.
Also, PHP has some nicer methods of writing to files. Try something like:
$output = '';
foreach($_POST as $key => $val)
$output .= sprintf("%s = %s\n", $key, $val);
file_put_contents('data.txt', $output);
That should be clear as long as $_POST
isn't 2D. If it's 2D, or more for debugging purposes, why not use print_r()
(as it's recursive), eg.
file_put_contents('data.txt', print_r($_POST, true));
The second argument makes it return a string rather than actually print.
For clarity, I'd consider putting the header('Location: xxx')
call at the end (even though it won't make a functional difference).
Upvotes: 1