Php File Handling

First of all, an important aspect to keep in mind when working with files, is that Windows and Mac OS X filenames are not case-sensitive, but Linux and Unix ones are. So is a good practice to assume that the system is casesensitive
and use a convention such as all filenames are lowercase.

How to create a file in Php?

Create a file in Php

fopen() function can be used both to open a file and also to create a file. If you use fopen() on a file that does not exist, it will create it. The example below creates a new file called “webpedia.txt”

if(file_exists("webpedia.txt")){
	echo "File exists";
}else{
$fh = fopen('webpedia.txt','w') or die('Failed to creat the file');
$text = <<<END
Welcome
to
Webpedia
END;
fwrite($fh,$text) or die('Could not write to file');
fclose($fh);
echo 'file created successfully';
}
//Result: file created successfully

If you run first time, will get the message “file created successfully”. The script will create the file webpedia.txt in same directory.
After that, if you run again, will get the message: “File exists”.

The procedure is as follows:
Always start by opening the file, then you can call other functions and finally do not forget to close the file.

If you receive an error message, it means that either your hard disk is full or you do not have permission to create or write to the file.

The supported fopen parameters

‘r’
Open for reading only; place the file pointer at the beginning of the file.

‘r+’
Open for reading and writing; place the file pointer at the beginning of the file.

‘w’
Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

‘w+’ Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

‘a’
Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

and ‘a+’, ‘x’, ‘x+’, ‘c’, ‘c+’, ‘e’.

Checking if a file exists

To check if a file already exists, use the file_exists function, which checks whether a file or directory exists. file_exists returns TRUE if the file or directory specified by filename exists, FALSE otherwise.

if(file_exists("webpedia.txt")):
echo 'File exists';
endif;
//Result: File exists

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

Leave a Comment

WebPedia.net