PHP Errors


The default error handling in PHP is simple. An error message with filename, line number and a message describing the error is sent to the browser. When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.

Basic Error Handling: Using the die Function
The first example shows a simple script that opens a text file. If the file does not exist, an error occurs.
 
 <html><body>
 <?php
  $file = fopen( "", "r" );
  fclose( $file );
 ?>
 </body></html>
       


To avoid that the user gets an error message like the one above, we test if the file exists before we try to access it. The example uses a simple error handling mechanism to stop the script after the error by using the PHP functions:
  • die(message), which prints a message and exits the current script, and

  • file_exists(path), which checks whether or not a file or directory exists.
 
 <html><body>
 <?php
  $filename = "";
  if( !file_exists( $filename ) )
   die( "" );
  else {
   $file = fopen( $filename, "r" );
   echo "File opened successfully";
   fclose( $file );
  }
 ?>
 </body></html>
       




      In elementary school, in case of fire you have to line up quietly    
      in a single file line from smallest to tallest.    
      What is the logic? Do tall people burn slower?    
      — Warren Hutcherson