O'Reilly logo

Learning PHP 5 by David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Checking for Errors

So far, the examples in this chapter have been shown without any error checking in them. This keeps them shorter, so you can focus on the file manipulation functions such as file_get_contents( ), fopen( ), and fgetcsv( ). It also makes them somewhat incomplete. Just like talking to a database program, working with files means interacting with resources external to your program. This means you have to worry about all sorts of things that can cause problems, such as operating system file permissions or a disk running out of free space.

In practice, to write robust file-handling code, you should check the return value of each file-related function. They each generate a warning message and return false if there is a problem. If the configuration directive track_errors is on, the text of the error message is available in the global variable $php_errormsg .

Example 10-19 shows how to check whether fopen( ) or fclose( ) encounters an error.

Example 10-19. Checking for an error from fopen( ) or fclose( )

require 'DB.php'; $db = DB::connect('mysql://hunter:w)mp3s@db.example.com/restaurant'); // Open dishes.txt for writing $fh = fopen('/usr/local/dishes.txt','wb'); if (! $fh) { print "Error opening dishes.txt: $php_errormsg"; } else { $q = $db->query("SELECT dish_name, price FROM dishes"); while($row = $q->fetchRow( )) { // Write each line (with a newline on the end) to // dishes.txt fwrite($fh, "The price of $row[0] is $row[1] \n"); } if (! fclose($fh)) { print "Error ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required