Self-Redirect With Adding Parameters in PHP
Let the GET parameter named arg be passed
to the page index.php.
Let's display its content on the screen:
<?php
echo $_GET['arg'];
?>
Let's assume our page cannot work correctly
without the GET parameter. In our case,
this is indeed true, because if the parameter
is not passed, then accessing $_GET['arg']
will cause an error.
The question may arise, why would a person end up on our page without the parameter at all? After all, we can put links with this parameter everywhere on our site. However, this is not a guarantee: a user of our site might, for example, copy a link from somewhere and lose the parameter in the process. Or simply accidentally delete it while editing the address bar.
In any case, our code should anticipate such a situation and do something about it. What can be done?
We can check our GET parameter for existence and output it only if it exists:
<?php
if (isset($_GET['arg'])) {
echo $_GET['arg'];
} else {
// react somehow, for example, with a message
}
?>
We can act more cleverly:
<?php
if (!isset($_GET['arg'])) {
$_GET['arg'] = 'default'; // default value
}
echo $_GET['arg']; // will guaranteed output something without error
?>
Or we can make it so that when accessing the page without a parameter, a redirect to the same page with the parameter occurs:
<?php
if (!isset($_GET['arg'])) {
header('Location: ?arg=default');
}
echo $_GET['arg']; // parameter is guaranteed to exist
?>
Explain the difference between the second option and the third one.
Let the number be passed to the page page.php
using a GET parameter named
num. Make it so that when accessing
without this parameter, a redirect
to the same page is automatically performed, but with the parameter
num set to the value 1.