Validating that URL Parameter is not empty (PHP)

PHP-logo url parameter

URL Parameters are sent to php like:

http://www.example.com?param1=true

when you work with URL parameters you should validate them first.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!--?php
// param name to be validated
$param = 'param1';
if (array_key_exists($param, $_GET)) {
    if (empty($_GET[$param])) { echo $param." is empty!"; } else  {
        $paramValue = $_GET[$param];
        // your code here:
        // you should perform your validation
        // on the $paramValue
    }
} else {
    echo "missing parameter '".$param."'";
}
?-->
<!--?php
// param name to be validated
$param = 'param1';
if (array_key_exists($param, $_GET)) {
    if (empty($_GET[$param])) { echo $param." is empty!"; } else  {
        $paramValue = $_GET[$param];
        // your code here:
        // you should perform your validation
        // on the $paramValue
    }
} else {
    echo "missing parameter '".$param."'";
}
?-->

http://www.example.com/Test.php
will return: “missing parameter param1”

http://www.example.com/Test.php?param1=
will return: “param1 is empty!”

http://www.example.com/Test.php?param1=1
will pass the validation

now you know you have a non empty URL parameter, what’s left is to validate it’s value.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.