i

PHP Tutorial

PHP File Create/Write

You can create a file using fopen() function in PHP by using w or a mode that allows you to create a new file and write it. If you use fopen() function with a file that is not present currently, it will create a new file and open it for writing or appending.

For example: $new_file = fopen(“mynewfile.txt”);

To write a file, you can use fwrite() function and it accepts two parameters. First parameter specifies the name of the file and second parameter specifies the text that needs to be written to the file.

For example:

$text = “ This is my new file”;

fwrite($new_file, $text);

fclose($new_file);

The output of the above file will be: This is my new file

if you use fopen() function again with w mode, the existing data of the file will be removed, and the new contents will overwrite the existing data in the file as w mode will erase the data and open the file for writing.

For example:

$new_file = fopen(“mynewfile.txt” , “w” );

$text = “ Welcome to file writing functions \n”;

fwrite($new_file, $text);

$text = “ We have overwritten the existing file.”);

fwrite($new_file, $text);

fclose($new_file);

?>

The output of the above php script will be:

Welcome to file writing functions

We have overwritten the existing file.