File Handling or processing in PHP is not different than any other language. There are 3 steps to using data in a file.

  1. Open the file. If the file doesn’t already exist create it or catch the error gracefully.
  2. Write/Read data from the file.
  3. Close the file.

To open a file in PHP use the fopen() function. We supply it with a filename, but we also need to set the file mode that tells how we intend to use it.

fopen()

fopen() expects 2 parameters – the location of the file and the file mode.

$fp = fopen(“$DOCUMENT_ROOT/orders/orders.txt”, “w”);

If no path is specified the current directory is used. If you are in a windows environment you must use double back slashes.

$fp = fopen(“$DOCUMENT_ROOT\\orders\\orders.txt”, “w”);

Summary of File Modes

  • r  (Read mode)
  • r+ (Reading and writing)
  • w  (OverWrite mode – if file already exists delete it and create a new one)
  • w+ (Overwrite and reading mode– if file already exists delete it and create a new)
  • a  (Append mode)
  • a+ (Appending and reading)

Step 1. Checking if file exists

Lots of things can go wrong when you try and open a file. The file might not exist. You might not have permission to view it. It may already be being written to. The following code handles this situation:

$fp = fopen("orders.txt", "a");
if (!fp)
{
   print "There were problems opening the file";
   exit();
}

Step 2. Writing to a file

Writing to a file in PHP is easy. You can either use the function:

  • fwrite()  – file write
  • fputs()  – file put sting (an alias to fwrite)
$fp = fopen("orders.txt", "a");
fwrite($fp, "adding something to the file");

Step 3. Closing the file

All that is left is to tidy everything up by closing the file using fclose($fp).

Reading from a File

fgets() is the most common function used. It is used to read one line at a fime from a file. In this case below it will read until it encounters a newline character, an EOF or has read 99 bytes from the file.

$fp = fopen("orders.txt", "a");
fwrite($fp, "adding something to the file");
while (!feof($fp))
{
   $order = fgets($fp, 100);
   print $order."<br>";
}

You can also use fread() and fgetc().

Other useful file functions

  • File_exists(path)   – whether file exists or not.
  • filesize(path)   – tells you how many bytes the file has.
  • Unlink(path)   – deletes the file given to it as a parameter.
  • Flock(path, option) – file locking function with options :

A PHP Web Counter

You can create a Web Counter using the filing. A Web Counter keeps track of how many people have visited a particular web page on your website. You can show these hits on your web page to show the popularity of your website. Code is given below:

<?
function update_counter()
{
  $fp = fopen("orders.txt", "r+");
  $hits = fgets($fp, 100);
  rewind($fp);
  $hits++;
  fwrite($fp, $hits);
  return $hits;
}
$count = update_counter();
print "page read ".$count." times";
?>

Note: You may need to first create a file and write “0” in the file showing that it starts with zero counter.

Problems using flat files

  • There are a number of problems with working with files:
  • When a file gets large it can be very slow to work with.
  • Searching through a file is difficult. You tend to have to read everything in to memory.
  • Concurrent access can become problematic.
  • Hard to enforce levels of access to data

What is the Solution then? :-) ask me

Its good to be Paranoid

The few people who use your site who aren’t muppets you can assume to be malevolent hackers. They will try and put javascript and HTML into your form fields. To stop them is easy:

$str = strip_tags($str)

This simply removes all HTML tags from the string supplied as the parameter – including <SCRIPT> tags.

Crypt()

  • crypt() will encrypt a string that you give it.
  • This is especially useful for encrypting items such as passwords.
  • This then cannot be reversed – but you can encrypt another string that is entered and then compare it with the stored encrypted string.
  • You should always encrypt your users access information if its privacy is essential.

Includes

One of your aims as a good programmer is to write as efficient flexible code as possible. Because of this you will write lots of functions for your PHP that can be used over and over. Instead of having tonnes of functions at the top of all your scripts they should be grouped together in a separate file and included in each script.

<?
 include("displayFunctions.fns");
include_once("myStringFunctions.fns");
?>

This means NEAT code. But also it is EFFICIENT – you don’t have to constantly retype functions.

Next >> Lecture 4. PHP-MySQL Affair

Tagged with: PHP
 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.