I am trying to create write a log file for my web site. To do this I use the following code to try and open the file. Now the file does not exist yet, but the documentation states that adding "a+" flag ensures that the file is created if it does not exist.
$file = fopen($_SERVER['DOCUMENT_ROOT']."/logs/mylogfile.txt", "a+");
The above code gives me the following error...
Warning: fopen(E:/wamp/www/logs/mylogfile.txt) [function.fopen]: failed to open stream: No such file or directory
What am I doing wrong ? Please excuse me if this is stupid question, I am very new to PHP.
The fopen() function opens a file or URL. Note: When writing to a text file, be sure to use the correct line-ending character! Unix systems use \n, Windows systems use \r\n, and Macintosh systems use \r as the line ending character.
The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).
In order to append file text/file to the file, a mode or a+ mode is needed to be mentioned in the fopen() function to handle the file data.
fopen() binds a named resource, specified by filename , to a stream.
fopen's 2nd parameter "a+" can only create the file if the directory exists. Make sure the logs directory is there. If it's not the case use:
mkdir($_SERVER['DOCUMENT_ROOT']."/logs/", 0755, true);
(true is the key) before fopen()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With