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).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 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.
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>
Free Time Learning (www.freetimelearning.com)
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>
FreeTimeLearning