Php file handling

Creating file or making file, in php is done with fopen() function. The fopen() function opens file and returns file handle. The function fopen() takes minimum two arguments, first argument is for path of file including file name and second is for mode of file. Mode of file is specified by using one of three characters "r","w" and "a".

If the character "r" is used , the file is opened for read only. The pointer of file is set in the beginning of the file.

If the character "w" is used, the file is opened for write mode. The pointer of file is set in the beginning of the file. When we use "w" for mode and if file already exists, fopen() function deletes old contents of the file,It will write data from the beginning. If file does not exists, it will create new file on hard drive.

If character "a" is used , the file is opened for write mode.But the pointer of file is set at the end of the file. Old data is not deleted, In this case new data is written at the end of the file.

File closing is done with function fclose().



<?php
$fp=fopen("C:\\myfile.txt","w") or die("Cannot open file");
if($fp){
fcose($fp);
}
?>
Now we have learnt opening and closing of file. The next step is writing contents in the file. In php fopen() function returns file handle, which we use for writing and closing file. For writing contents in file we use fwrite() function. The function fwrite() takes two arguments first one is file handle and second is string or contents. As shown in example:
<?php
$fp=fopen("C:\\myfile.txt","w") or die("Cannot open file");
if($fp){
$str="Hello, world";
fwrite($fp,$str);
fcose($fp);
}
?>
If we want to check whether file exists or does not exist, we can do this with file_exists() function. Just give path of file as a argument.If file exists, it returns true otherwise false. The function unlink() is used to delete the existing file. See as given below .
<?php
if(file_exists("C:\\myfile.txt")){
unlink("C:\\myfile.txt");
}
?>