Catching exceptions while using "get" in php
I am new to php and I am wondering how to catch errors that occur when using "get" on post parameters.
My page will have the following url:
http://www.mysite.com/page.php?id=5
However, I want to be able to redirect a user to the main page if the id does not exist on the s开发者_运维技巧ite. How can I do this in php?
The pages crashes when it reaches this line:
$ID = $_GET['id'];
It gives me this error:
<b>Notice</b>: Undefined index: id in <b>//test.php</b> on line <b>36</b><br />
In general terms, redirecting is not proper way of handling for invalid id.
By a standard, a 404 header should be issued.
So, just query your database for given id, and if no data returned, show 404 page with appropriate header. However, this latter page may use JS redirect to the main page.
Speaking of exceptions, in general, any exception, if properly used, should raise a 503 error.
But absence of certain id in the table shouldn't raise any system-level errors. It's program logic level and such errors should be handled without exceptions.
For starters, you'll need to have some way to check if the id that was passed is valid for your site. The best approach would probably to write a function that checks for you, and then redirect based on its result.
function valid_id( $id ){
// Talk to your database and check the ID, then return TRUE or FALSE
}
if( !valid_id( $_GET["id"] ) ){
// Redirect to a 404 page or the site index
}
// Normal page loading goes here
If you're looking for the simplest solution, just check if the variable is set before using it:
if (isset($_GET['id']) {
// 'id' exists, do anything you want with it
}else {
// 'id' wasn't provided, redirect with header() or call a 404 page
}
精彩评论