15 August 2013

PHP Get Page Parameter Safe $_GET

Most of us have to use the $_GET in PHP to get the desired content id and print the contents on page. But we cannot trust the incoming paremeter directly from the url.
We should check the parameter and validate it.

If it is set
Check if the parameter is set or not
if ( isset($_GET['id']) )
{
 // ok it is set.
}

Now I also check if it is empty or not;

If it is not empty

if ( isset($_GET['id']) && !empty($_GET['id']) )
{
 // ok it is set and not empty
}

If you know the parameter must be integer, than lets check
If it is a valid number. 

if ( isset($_GET['id']) && !empty($_GET['id']) && is_numeric($_GET['id']) )
{
 // ok it is set, not empty, and a number, get it;
$id = trim($_GET['id']);
}

Finally we get our parameter safely in PHP.

No comments: