PHP & MySQL Tutorial
File Handling II - Reading and Writing
We can open a file using fopen() function. It needs two arguments which are file name and file mode. The fopen() function returns a file pointer which references the file and can be used to read file's contents.
Using fread() function we can read a file. The fread() function takes the file name as its argument and returns the size of the file in bytes.
The process of reading a file can be summarized as following:
- fopen()
Open the file - filesize()
Get the file's length - fread()
Read the contents of the file - close()
Close the file
The example below assigns the contents of a text file to a variable. Then, it displays those contents.
<html> <head><title>File Read</title></head> <body> <?php $fileName = "AnnabelLee.txt"; $file = fopen($fileName,'r'); $fileSize = filesize($fileName); $poe = fread($file, $fileSize); fclose($file); echo "File Size: $fileSize bytes"; echo "<pre>$poe</pre>"; ?> </body> </html>
We can write a new file or append to an existing file using fwrite() function. It takes two arguments which are a file pointer and the data to be written. A third argument which specifies the length of data to write is optional. If the third argument is included, writing continues until the specified length reached.
We get the file pointer from fopen() function with arguments stating the file name and writing mode. The fclose() should be used after writing to a file.
The file_exists() function can be used to test the existence of a file. It takes the file name as its argument, and it will return true if the file is located.
The following example creates a new text file. The existence test is performed after the file close.
<?php $fileName = "greatestWriters.txt"; $file = fopen($fileName,'w'); fwrite($file,"The Greatest Writers\n\n"); fclose($file); ?> <html> <head><title>File Write</title></head> <body> <?php if(file_exists($fileName)) { $fileLength = filesize($fileName); $msg = "File created, \"<b>$fileName</b>\" <br />"; $msg .= "containing $fileLength bytes"; echo $msg; } else echo "Could not create a file"; ?> </body> </html>
In the following example, we reopen the previous file, and appends string data. We'll use file mode a to append. Here is the file, fileWriterB.php:
<?php $fileName = "greatestWriters.txt"; $file = fopen($fileName,'a'); $writers = " 1. William Shakespeare\n 2. Charles Dickens\n 3. Fyodor Dostoevsky\n 4. Leo Tolstoy \n 5. J.R.R. Tolkien \n 6. Ernest Hemingway \n 7. Jane Austen \n 8. George Orwell \n 9. Mark Twain \n 10. John Steinbeck \n"; fwrite($file, $writers); fclose($file); ?>
After running the file, we get the greatestWriters.txt. When we open the file, we see the text we wrote:
Logging details about visitor to our web page is simple. It may be interesting to see how visitors landed at the page, by recording the values of the environment variable HTTP_REFERER. This holds the URL of the page containing the hyperlink that the visitor took to get to our page. Most web browsers pass the HTTP_REFERER variable by default, but in many this behaviour can be changed to not show it or to pass something else instead. There is also 3rd party anti-spyware etc software that can be installed on a user's computer which also prevents the referrer information from being passed to the web server. Because it can also be changed to something else, the HTTP_REFERER cannot be trusted, but it is still useful for working out where people have come from.
The frequency with which visitors return can be found by recording the IP addresses of visitors. These are stored in the environment variable REMOTE_ADDR.
The example below shows how to log these visitor details along with their browser type and the access time.
<?php $address = $_SERVER['REMOTE_ADDR']; $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''; $browser = $_SERVER['HTTP_USER_AGENT']; $file = fopen("log.html",'a'); date_default_timezone_set('America/Los_Angeles'); $accessTime = date("H:i dS F"); fwrite($file, "<b>Time:</b> $accessTime<br />"); if( $address != null) fwrite($file,"<b>IP Address:</b> $address<br />"); if($referer != null) fwrite($file,"<b>Referer:<b> $referer<br />"); fwrite($file,"<b>Browser:</b> $browser<hr>"); fclose($file); ?>
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization