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 you might get an error like this:
Warning:
fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in C:\webfolder\test.php on line 2
To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it:
Now if the file does not exist you get an error like this:
File not found
Buy with 40% discountThe first example shows a simple script that opens a text file:
<?php $file=fopen("welcome.txt","r"); ?> |
If the file does not exist you might get an error like this:
Warning:
fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in C:\webfolder\test.php on line 2
To avoid that the user gets an error message like the one above, we test if the file exist before we try to access it:
<?php if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?> |
Now if the file does not exist you get an error like this:
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.
However, simply stopping the script is not always the right way to go. Let's take a look at
alternative PHP functions for handling errors.
0 comments:
Post a Comment