Reputation: 335
I am trying to write a simple text into a php file. The snap of the code is below:
$a = $_GET["option"];
$a = (string)$a;
$b = $_GET["ip_address"];
$myfile = fopen("newfile.txt", "w");
fwrite($myfile,$a);
fwrite($myfile,$b);
echo $a;
echo $b;
When I open the file through the terminal , its empty. however the echo commands in the php code display output as expected.
Should the file retain the content after the program has finished execution ? I am using syntax from here
EDIT: The new file is created by PHP however it does not have write permissions. I changed it. It works now
Upvotes: 1
Views: 737
Reputation: 905
Although the other answers saying you must use fclose
do solve your problem, this is incidental. The actual issue is when you use fwrite
the output is buffered - it's stored in memory but not yet committed to the filesystem. In order to commit this output to your file you should use fflush($myfile)
(fflush documentation); you can do this multiple times before closing your file handle. Do bear in mind you should always close file handles with fclose
to ensure resources are cleaned up correctly.
Upvotes: 0
Reputation:
you should must be close the connection. please read this manual fclose manual
$myfile = fopen("newfile.txt", "w");
fwrite($myfile,"some text");
fwrite($myfile,"another text");
fclose($myfile);
echo $a;
echo $b;
Upvotes: 0
Reputation: 27503
$a = $_GET["option"];
$a = (string)$a;
$b = $_GET["ip_address"];
$myfile = fopen("newfile.txt", "w");
fwrite($myfile,$a);
fwrite($myfile,$b);
fclose($myfile);
echo $a;
echo $b;
try this once, as you were not closing the connection, thus the output was not getting stored
Upvotes: 3
Reputation: 101
use fclose($myfile);
to close the file and check the permission of the file/folder in which you are writing.
Upvotes: 1