Page 193 - Open Soource Technologies 304.indd
P. 193
Open Source Technologies
Notes PHP Code
$myFile = “testFile.txt”;
$fh = fopen($myFile, ‘w’);
11.6.2 File Write Fwrite 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 and you’re good to go!
Below we are writing a couple of names into our test file testFile.txt and separating them with
a carriage return.
PHP Code
$myFile = “testFile.txt”;
$fh = fopen($myFile, ‘w’) or die(“can’t open file”);
$stringData = “Bobby Bopper\n”;
fwrite($fh, $stringData);
$stringData = “Tracy Tanner\n”;
fwrite($fh, $stringData);
fclose($fh);
The $fh variable contains the file handle for testFile.txt. The file handle knows the current file
pointer, which for writing, starts out at the beginning of the file.
We wrote to the file testFile.txt twice. Each time we wrote to the file we sent the string $stringData
that first contained Bobby Bopper and second contained Tracy Tanner. After we finished writing
we closed the file using the fclose function.
If you were to open the testFile.txt file in NOTEPAD it would look like this:
Contents of the TestFile.txt File
Bobby Bopper
Tracy Tanner
We can write to a file by using fwrite() function PHP. Please note that we have to open the
file in write mode and if write permission is there then only we can open it in write mode. If
the file does not exist then one new file will be created. We can change the permission of the
file also. However we can check the presence of a file by using file_exists function. You can
read the content of a file by using fopen() function in PHP. This is the way to write entries to a
guestbook, counter and many other scripts if you are not using any database for storing data.
Here we will see how to write to a file.
188 LOVELY PROFESSIONAL UNIVERSITY