PHP die()

Basically error handling is very simple in php. While writing the code for your applicationsĀ  you might struggle to find out the errors . InĀ  that case you can use die() to handle errors.

Let us consider the following example:

<?php
$file=fopen("sample.txt","r");
?>

If the file does not exist you will be getting an error like this:
OUTPUT:
Warning: fopen(sample.txt) [function.fopen]: failed to open stream: No such file or directory in C:\www\simple.php on line 2

To avoid getting the error message like this you can use die()

die()
Is used to stop the script after an error

For eg:

<?php
if(!file_exists("sample.txt"))
  {
  die("File not found");
  }
else
  {
  $file=fopen("sample.txt","r");
  }
?>

Now if the file does not exist you will getting an error like this:
OUTPUT:
File not found

Posted in Php Tagged with: ,