Undefined index

Hey, I’m working on Kevin Yank books (fifth edition). Now I’m stuck on page 65. My browsers keep said undefined index for both first and last name, even when I used code archive. Can somebody help me? (here I quoted the code)

<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“utf-8”>
<title>Query String Link Example</title>
</head>
<body>
<p><a href=“name.php?firstname=Kevin&lastname=Yank”>Hi, I’m Kevin Yank!</a></p>
</body>
</html>

<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“utf-8”>
<title>Query String Link Example</title>
</head>
<body>
<p>
<?php
$firstName = $_GET[‘firstname’];
$lastName = $_GET[‘lastname’];
echo 'Welcome to our website, ’ .
htmlspecialchars($firstName, ENT_QUOTES, ‘UTF-8’) . ’ ’ .
htmlspecialchars($lastName, ENT_QUOTES, ‘UTF-8’) . ‘!’;
?>
</p>
</body>
</html>

thanks before

$firstName = $_GET['firstname'];
$lastName = $_GET['lastname'];

If the URL does not have firstname and lastname queries the indexes will be undefined

http;//domain.com/page.php?firstname=John&lastname=Doe

To get around the issue, check to see of the indexes are defined

if(isset($_GET['firstname']) {
    $firstName = $_GET['firstname'];
} else {
    $firstName = '';
}
if(isset($_GET['lastname']) {
    $lastname = $_GET['lastname'];
} else {
    $lastname = '';
}

but don’t forget to sanitize the input.

@captaincss

thanks for the solution, it was helpful.
also I want to ask another thing, why in the browser the result appear without the space (like when you use space bar) between the name?

Glad to be of help but I don’t understand the space question. Where does the space not appear? And what code is supposed to produce that missing space?

it supposed to appeared ‘Welcome to the website, John Doe’ but instead it just ‘Welcome to the website, JohnDoe’ (John Doe, based on the input like you gave)
I think the . (dot) supposed to give a space between John and Doe.

No. The dot is to join stuff. You need to add the space:

$output = "Welcome to the website, " . $firstName . ' ' . $lastName;
echo $output;

or put the variables inside the string

$output = "Welcome to the website, $firstName $lastName";
echo $output;

]
or better yet for clarity

$output = "Welcome to the website, {$firstName} {$lastName}";
echo $output;

I see now, that’s my mistake. thanks once again. and btw among those three solution above, for number one it works on me with (") instead of (')

It should work with both single and double quotes.

now I see where I did wrong, thanks again captain