PHP Tutorial

PHP Tutorial #5

Fear not, we are now starting to get to the more interesting stuff. Now we can create and read files. First we want to create a file to read:-

<?php
	$filename="testfile.txt";
	$file=fopen($filename,"w");
	fwrite($file, "Hello\n");
	fclose($file);

	if(file_exists($filename))
	{
		$file_length=filesize($filename);
		$msg="File $filename created";
		$msg.=" and contains $file_length bytes";
		echo($msg);
	}
	else
	{
		echo("File error");
	} 
  ?>

There, not too difficult is it? From the top. We create a filename in a variable $filename and then open it ready for writing (denoted by the "w"). We write a simple text message and terminate using a \n newline character. Then we close the file. Then if the file exists, we get the length of the file to prove something has been written to it and that it has been created in the current directory (in my case /var/www/html) and construct a variable containing a string that lloks like this in the browser:-

File testfile.txt created and contains 6 bytes

otherwise (else) an error has occured. For some strange reason, if I specify a valid path for the filename (such as /home/linux/testfile.txt) it didn't seem to work - just gave errors. Oh well...the above code seems to work fine. Now to read it:-

<?php
	$filename = "testfile.txt";
	$filesize = filesize($filename);
	$file = fopen( $filename, "r" );
	$text = fread( $file, $filesize );
	fclose( $file ); 

	echo( "File Size: $filesize bytes" ); 
	echo("<pre>$text</pre>");
?>

Because we know the file exists then for clarity I have dispensed with the if exists statement (but you could put it in if you like as a bit of homework). We create a filename then get the file size, open it, read it into a variable and close the file again. Then we print out as below:-

File Size: 6 bytes

We can also append to the file as follows:-

<?php
	$filename="testfile.txt";
	$file=fopen($filename,"a");
	fwrite($file, "again\n");
	fclose($file);

	if(file_exists($filename))
	{
			$file_length=filesize($filename);
			$msg="File $filename appended to ";
			$msg.=" and now contains $file_length bytes";
			echo($msg);
	}
	else
	{
		echo("File error");
	} 
?>

Note the use of the "a" for append in the fopen statement. Now amazingly, the original read program will still work and will list both lines of data. It can do this because we specify the filesize in the fread statement which avoids having while loops ans EOF statements to collect all the data like yiou ave to in C. Very impressive.

So we can now read and write files. So what? Well we could use it to create a file containing a log of who has accessed a particular website. Here is the code:-

<?
	$file = fopen("log.html",  "a");  
	$time = date("H:i dS F");
	fwrite( $file, "<b>Time:</b> $time<br/>" );

	if( $REMOTE_ADDR != null)
	{
  		fwrite( $file, "<b>IP Address:</b> $REMOTE_ADDR <br/>");
	}  

	fwrite( $file, "<b>Browser:</b> $HTTP_USER_AGENT<P><HR>");  
	fclose($file);
	echo("Log written");
?> 

Note the .html in the file name. This produces a text file but it contains HTML code that the browser can understand. So opening this file in a browser will display this:-

Time: 15:45 17th April
IP Address: 127.0.0.1
Browser: Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.6) Gecko/20040115


Time: 15:45 17th April
IP Address: 127.0.0.1
Browser: Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.6) Gecko/20040115


Finally for this tutorial, it is possible to keep a count of the number of vists to a site by creating a file containing a number, reading it each time the page is visited and adding one to the total. It looks like this:-

<?php
	$filename="count.txt";

	if(file_exists($filename))
	{
		// if exists then read
		$filesize = filesize($filename);
		$file = fopen( $filename, "r" );
		$int = fread( $file, $filesize );
		fclose( $file ); 

		// add 1 to int value
		$int = $int + 1;
		$file=fopen($filename,"w");
		fwrite($file, $int);
		fclose($file);

		$msg = "Count: ";
		$msg .= $int;
		echo($msg);
	}
	else
	{
		// if not exist set to zero
		$file=fopen($filename,"w");
		fwrite($file, "0");
		fclose($file);
	} 
?>

This will create a file called count.txt that will simply contain a number. This is read into a variable, one is added to it and then it is written back again and the count is displayed in the browser window. If the file doesn't exist then it is created and zero appended to it. And that completes this tutorial. You can find working versions of some of these scripts here. Next time we'll be delving into databases...

Back

Written by Nick Cheesman. Last updated: 01/04/2004
Please eMail me at:
nickjc@nickjc.co.uk if you need help