air
air

Reputation: 6264

passing empty query string to php

i have question for query string

i have page wehere i pass query string like that

      abc.php?id=12

some time query sting "id" is not passed like

      abc.php

and some time value of id is empty

     abc.php?id=

and in the above 2 possibilities pages gives error.

how to fix this ?

Upvotes: 1

Views: 2739

Answers (5)

Gumbo
Gumbo

Reputation: 655559

You should always validate the incoming data before using it. In this case use isset to test if the variable exists and has a value other than null and use ctype_digit to check if the value consists only of digit characters.

Upvotes: 0

Paul Dragoonis
Paul Dragoonis

Reputation: 2333

Applying checks using the isset() language construct will supress errors and allow you to access array keys that may not exist. Here is a small function for transparent existance of a value.

$myID = getInput('id'); // Returns 'null' if ID doesn't exist but throws no PHP errors
$myID = getInput('id', 50); // Returns 50 if your ID doesn't exist

With this you can perform validation checks to make sure you have an ID

if( ($myID = getInput('id', 0)) < 1) {
     die('Invalid ID Value');
}
die("My ID is: $myID");


function getInput($key, $default = null) {
    return isset($_GET[$key]) && $_GET[$key] != null ? $_GET[$key] : $default;
}

Upvotes: 0

Fero
Fero

Reputation: 13315

check the below condition

if($_GET['id'] == '') {

 // Your Condition Here

} else if($_GET['id'] != '') {

 // Your Condition Here

} else if(isset($_GET['id'])) {

 // Your Condition Here

} 

Hope this Helps.

Upvotes: -1

spinon
spinon

Reputation: 10857

If you check it correctly using isset() and empty() you should be able to avoid any problems.

Upvotes: 2

Mchl
Mchl

Reputation: 62405

Check if $_GET['id'] is set (using isset() ) before attempting to do anything with it.

Upvotes: 2

Related Questions