Google News
logo
PHP File Create/Write
The fopen() function is also used to create a file or URL and returns resource. A file is created using the same function used to open files. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).

The below example  creates a new file called "create_file.txt".  The file will be created in the same directory where the PHP code resides :
Syntax

<?php  
$my_file = 'MY_FILE.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file');
fclose($handle);
?>    

1. $my_file = 'MY_FILE.txt'; : Here we create the name of our file, "MY_FILE.txt" and store it into a PHP String variable $my_file.

2. $handle = fopen($my_file, 'w') or die('Cannot open file'); : This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform PHP that we want to write by passing the character "w".

Second, 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 $my_file variable. We will talk more about file handles later on.

3. fclose($handle); : We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file closing lesson.

PHP Write File

PHP fwrite() and fputs() functions are used to write data into file. To write data into file, you need to use w, r+, w+, x, x+, c or c+ mode.

PHP Write File - fwrite()
The PHP fwrite() function is used to write content of the string into file.
Syntax

int fwrite ( resource $handle , string $string [, int $length ] )

The example below writes a couple of names into a new file called "MY_DATA.txt" :

<!DOCTYPE HTML>  
<html>
<head>
	<title>File Writen - fwrite()</title>
</head>
<body>  
 
<?php  
	$file = fopen('MY_DATA.txt', 'w');//opens file in write-only mode  
	fwrite($file, 'Free Time Learning ');  
	fwrite($file, ' (www.freetimelearning.com)');  
	fclose($file);  
	  
	echo "File written is successfully";  
?>
</body>
</html>  
MY_DATA.txt

Free Time Learning (www.freetimelearning.com)

File Overwriting - fwrite()
Now that "newfile.txt" contains some data we can show what happens when we open an existing file for writing. All the existing data will be ERASED and we start with an empty file.

In the example below we open our existing file "MY_DATA.txt", and write some new data into it:

<!DOCTYPE HTML>  
<html>
<head>
	<title>File Overwriting - fwrite()</title>
</head>
<body>  
 
<?php  
	$file = fopen('MY_DATA_1.txt', 'w');//opens file in write-only mode  
	fwrite($file, 'FreeTimeLearning');  
	fclose($file);  
	echo "File written successfully";   
?>

</body>
</html>  
MY_DATA_1.txt

FreeTimeLearning