john
john

Reputation: 335

Cannot Write to a file in PHP

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

Answers (4)

Ben
Ben

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

user5350813
user5350813

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

Exprator
Exprator

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

Vivek D.
Vivek D.

Reputation: 101

use fclose($myfile); to close the file and check the permission of the file/folder in which you are writing.

Upvotes: 1

Related Questions