Lets see how to create a file in php. The code below will show you how to create and write to file using php. File handling is very useful, you dont want to store every data in MySQL database every time, such as log files or user uploaded avatars.
I like to follow a lower case naming convention when I am dealing with files, regardless of the programming language. The reason is Windows and Mac OS X filenames are not case-sensitive, but Linux and Unix ones are. Therefore we should always assume that the system is case-sensitive and stick to a lower-case naming convention.
Creating a simple text file.
$myfile = fopen("testfile.txt", "w") or die("Unable to open file!");
$txt = <<<_END
Visit ProjectDebug for amazing tutorials.
fwrite($myfile, $txt) or die("Could not write to file");
echo "File 'testfile.txt' written successfully";
When you run this in a browser, if everything is well, you will receive a message ” File ‘TestFile.txt’ written successfully “. If you receive an error message, chances are, your hard disk is full or you may not a permission to create or write to the file.
The file created above will be stored in the same directory in which you saved the php file.
Every open file requires a file resource so that PHP can access and manage it. I above example we created $myfile variable to hold the value returned by fopen() function. The variable $myfile can be used by each file-handling function that accesses the opened file e.g. fwrite and fclose.
If fopen() fails to open or create file, FALSE will be returned. The first parameter in fopen() is a file name, second parameter indicates the fopen mode. ‘w’ mode tell fopen to open the file in write mode. The function creates the file if it doesn’t already exists. If the file already exists, the w mode parameter causes the fopen to delete the old contents.
Whatever we write inside <<<_END and _END, will get stored in $txt, we will use this variable later to pass as an argument to fwrite(), this function will write to our file.
Even though the program closes our file at the end of execution but you should clean up by closing the file when you no longer need to access the file by using fclose().