PHP Error Handling- die() Statement
Posted by tutor | Posted in PHP Tutorial | Posted on 16-12-2009-05-2008
0
PHP provides a default error handling, which is very simple. An error message is sent to the browser, with filename, line number and a message describing the error.
Error handling is a vital part while working with scripts and creating web applications.
Error checking and handling helps you handle the errors your way, ie you can do what you want to do in case an error occurs. It makes your code look more professional and also provides security.
This tutorial contains some of the most common error checking methods in PHP.
Some of the most common error checking methods of PHP are:
- Simple “die()” statements
- Custom errors and error triggers
- Error reporting
Using the die() function
The first example shows a simple script that opens a text file:
$file=fopen(”welcome.txt”,”r”);
?>
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:No such file or directory in C:\webfolder\test.php on line 2
You can avoid this situation by simple methods. First look for the file if it exists, then open it and if not then you can use the die() function.
if(!file_exists(”welcome.txt”))
{
die(”File not found”);
}
else
{
$file=fopen(”welcome.txt”,”r”);
}
?>
File not found
The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.
