Alex Cracknell Alex Cracknell - 3 months ago 32
PHP Question

Combining header and htmlspecialchars

How do I add this script

<?php header('Location: example.com/login.php?name='); ?>


to this

<?php echo 'Hello' . htmlspecialchars($_GET["name"]) . ', welcome'; ?>


I want the
htmlspecialchars
to be behind the
=
in
example.com/login.php?name=
but I don't know how to add it; when I tried to, it didn't work.

How would I do this?

Answer

You can use string concatenation; in PHP, you can combine two strings together (concatenate string) with a period (.)

<?php
header('Location: http://www.example.com/login.php?name=' 
           . htmlspecialchars($_GET['name']));
exit();

A few other changes that you'll see:

  • I added an explicit exit() call after I set the Location header; this will cause the redirect to happen without executing any more code, which is frequently undesireable.
  • I added a protocol (http, https) to the Location.

Assuming that $_GET['name'] = 'Mary';, this would redirect the user to

http://www.example.com/login.php?name=Mary