PHP: fopen: No such file or directory

Heshan Perera picture Heshan Perera · Jun 4, 2012 · Viewed 28.9k times · Source

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.

Answer

Gavriel picture Gavriel · Jun 4, 2012

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()