• Have Any Question?
  • contact@eitworld.com

PHP-File Open





In the Previous we used the fopen() function to create a file. However this function is basically used to open a file in a particular mode (read, write, appent). Now in this chapter we will study fopen() function in detail.

PHP File Opening modes

Given table shows the file opening mode in PHP with description:

Mode Meaning Description
r Reading This mode opens a file for read only use. If the file does not exists then it returns NULL.
w Writing This mode opens a file for write only use. In addition, you can erase the data present in the file and begin writing data at the beginning of the file.If the file does not exists then it creates new file.
a Append This mode also opens a file for write only use but data present in the file preserved and you will begin writing data at the end of the file.If the file does not exists then it creates new file.
r+ Reading + Writing This mode opens a file so that it can be read from and written to. In this mode you can begin writing data at the beginning of the file.If the file does not exists then it creates new file.
w+ Reading + Writing This is exactly the same as r+, except that it deletes all information in the file when the file is opened.If the file does not exists then it creates new file.
a+ Reading + Writing This is exactly the same as r+, except that it appends new data at the end of file.If the file does not exists then it creates new file.

How to open a file?

 

fopen function needs two main elements to open a file, first one is the name of the file and the second one is the mode in which we want to open that file.

Here is the section of PHP code which shows creation of a file in PHP:

 


$myfile = "open.txt";
$myfilehandle = fopen($myfile, 'w') or die("can't open file");
fclose($myfilehandle);

 

Note: The file “open.txt” should be created in the same directory where this PHP code resides. PHP Interpreter will see that “open.txt” does not exist and will create it after running this code.

 

In the above example:

  • $myfile = “open.txt”; this statement specifies that we create the name of our file, “open.txt” and store it into a PHP String variable $myfile.
  • $myfilehandle = fopen($myfile, ‘w’) or die(“can’t open file”); this statement specifies that First of all we use the function fopen and give it two arguments: first one is the name of the file that is “$myfile” and the second one is the mode in which we want to open that file that is “w” (write mode).. Secondly, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the $myfilehandlevariable.
  • close($myfilehandle); this statement close the opened file. fclose function takes the file handle that is to be closed.


Real Time Web Analytics