PHP File Create Write

PHP File Create Write


PHP Create file : In php fopen() function also used to create a file.It may seem a little confusing,lets understand this.
 
In PHP the fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function call. So if you use fopen on a file that does not exist, it will create it, given that you open the file for writing or appending (more on this later).
The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).
 
Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.

Example : 

The file "testFile.txt" should be created in the same directory where this PHP code resides. PHP will see that "testFile.txt" does not exist and will create it after running this code.
 
Here we create the name of our file, "php.txt" and store it into a PHP String variable $handle.
As we can see The file "testFile.txt" should be created in the same directory where this PHP code resides.

 

PHP Write function :We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite's first parameter is the file handle and its second parameter is the string of data that is to be written. Just give the function those two bits of information.

Example :

The $handle variable contains the file handle for hello.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.

 Each time we wrote to the file we sent the string $data that first contained hello and second contained world!. After we finished writing we closed the file using the fclose() function.

Output :