Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Dangerous Assumptions

Our code makes assumptions that:

  1. that the file will be available in the first place
  2. that the file will be opened successfully
  3. that the file will be closed successfully

If the above assumptions were to evaluate to TRUE, our life would just... roll on smoothly but... things are not always what we want and expect them to be. It is very naive to think otherwise.

Fortunately, we are in luck because:

  • The $filehandle returned by fopen() is an integer which is set to FALSE if opening fails. Testing the value of this integer can always tell you whether the file was opened successfully or not.
  • fclose() returns an integer, again set to FALSE on failure and TRUE on success.

    With these considerations in mind we can alter our code to become a little more smarter:

    <?php
     $file2open="/www/home/list.txt";
     if(!$listfile=fopen ($file2open, 'r')){
    	print ("cannot open $file2open for read-only";
     } else {
    	print "file: $file2open successfully opened";
      	if(!fclose($listfile)){
    	  print "cannot close $file2open";
    	}
     }
    ?>

    If you notice, we are using the bang (!) to test for failure. The line...

    if(!listfile = fopen($file2open,'r'))

    ... tests if the file CANNOT be opened by TRYING to open it. Get the logic in that piece of code?! This is sometimes called reverse logic thought it really looks straight to me.

    Remember in PHP the bang (!) means not true.

    Fine. In our code we open a file and then immediately close it. What's the point? Let's do something with the data inside the file.

    << Opening and Closing Files | Reading from Files >>

  • JamHitz Productions