rkb
rkb

Reputation: 544

How to test if a specific variable is present in URL query string or not?

I have written following php codes to catch name and email from URL query string.

   <?php
        $name = "rkb";                // Default name
        $email= "[email protected]";    // Default email
        if ($_GET['name']) {
            $name = test_input($_GET['name']);
        }
        if ($_GET['email']) {
            $email = test_input($_GET['email']);
        }

        function test_input($data) {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            return $data;
        }

    ?>

It works well when I pass variables name and email in URL. But when I load this page without query string, I get these two errors

Notice: Undefined index: name in path\to\folder\index.php on line 4
Notice: Undefined index: email in path\to\folder\index.php on line 7

I want to make the PHP to behave such that $name and $email get default values when query string is absent.

Upvotes: 0

Views: 283

Answers (5)

Rikesh
Rikesh

Reputation: 26421

What you need is PHP function isset.

A simple way,

$name = isset($_GET['name']) ? test_input($_GET['name']) : "rkb";

Upvotes: 4

Krish R
Krish R

Reputation: 22711

You can use isset() to determine if a variable is set and is not NULL. Also, check the empty() as well

    if (isset($_GET['name']) && !empty($_GET['name'])) {
       $name = test_input($_GET['name']); 
    }

Upvotes: 2

Bhavin Radadiya
Bhavin Radadiya

Reputation: 63

use isset function to check $_GET is set or not. change your code like this.

<?php
    $name = "rkb";                // Default name
    $email= "[email protected]";    // Default email
    if (isset($_GET['name'])) {
        $name = test_input($_GET['name']);
    }
    if (isset($_GET['email'])) {
        $email = test_input($_GET['email']);
    }

    function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }

?>

Upvotes: 1

aikutto
aikutto

Reputation: 592

Use if (isset($_GET['name'])) instead of if ($_GET['name'])

Upvotes: 2

Barmar
Barmar

Reputation: 780818

Use empty(). It tests whether the variable is set and whether it contains a non-null value.

    if (!empty($_GET['name'])) {

Upvotes: 3

Related Questions