Reputation: 544
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
Reputation: 26421
What you need is PHP function isset.
A simple way,
$name = isset($_GET['name']) ? test_input($_GET['name']) : "rkb";
Upvotes: 4
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
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
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