Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: fopen: No such file or directory

Tags:

php

fopen

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.

like image 257
Heshan Perera Avatar asked Jun 04 '12 06:06

Heshan Perera


People also ask

What does fopen () function do in 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.

Does fopen create a new file in PHP?

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

When using the fopen () function to open a file in PHP What made should you use for appending data to a file?

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.

What is FTP fopen?

fopen() binds a named resource, specified by filename , to a stream.


1 Answers

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

like image 95
Gavriel Avatar answered Oct 05 '22 23:10

Gavriel