简体   繁体   中英

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

$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

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

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM