How to save a variable data into text file using PHP

H3mp

Beta member
Messages
5
I'm trying to write a code that takes two variables entered by the user via input boxes and saves them in a text file, without overwriting other entries. Unfortunately the strings are not showing up in the text file. Heres the code I'm using

PHP said:
$handle = fopen("datalog.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;

I am new to PHP, and I'm sure I'm making a dumb mistake. Any advice would be greatly appreciated.
 
The PHP may not have read/write permissions for your file. If you didn't it would probably throw some kind of error, but depending on the context you may not see it (eg via AJAX). Try outputing some values (ie the return values for fopen, fwrite and fclose) and maybe making the code a bit more robust by throwing in some ifs like

$test_var = is_readable("datalog.txt");
echo "Is Readable: ".$test_var;
if($test_var)
{
$handle = fopen("datalog.txt","a");
echo "File is ".$handle;
if($handle !== FALSE)
{
//print stuff to file
$test_var = fclose($handle);
echo "File Close: ".$test_var;
}
}

Something like that should help you trace the source of your error. I'm assuming the text file is in same folder as the php file, otherwise you have to specify the location more specifically.

Just a side note, because of the carriage return with the newline character I'm assuming you're processing this file on a windows system?
 
Back
Top Bottom