Saturday, November 14, 2015

PHP: fopen: No such file or directory

http://stackoverflow.com/questions/10877007/php-fopen-no-such-file-or-directory

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.
shareimprove this question

    
Do you have write permissions to that folder? – alexn Jun 4 '12 at 6:13
    
did you checked your E:/wamp/www/logs/ folder for any file named "tagMetroLog.txt" ? – Miqdad Ali Jun 4 '12 at 6:15
    
Thanks for the response.. how can I check that ? – Heshan Perera Jun 4 '12 at 6:17
1  
yes.. the folder named logs doesn't event exists. – Heshan Perera Jun 4 '12 at 6:17
    
Create a folder inside your www folder named logs and create the file "tagMetroLog.txt" or you can use $file = @fopen($_SERVER['DOCUMENT_ROOT']."/logs/mylogfile.txt", "a+"); It will not show any error – Miqdad Ali Jun 4 '12 at 6:22

1 Answer

up vote 8 down vote accepted
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/", 0777, true);
(true is the key) before fopen()