I have a question, i want to make some search page, and it needs a get variable to sort the results. So if someone enters the page without that GET variable, reload the page and make it appear, for example you enter www.myweb.com/search and automatically reloads and changes to www.myweb.com/search/?sort=ascending (because that variable is necessary) .
I hope you understand me, good bye
I think this will work for what you're looking to do:
if (empty($_GET['sort'])) {
header('Location: ' . $_SERVER['REQUEST_URI'] . '?sort=ascending');
exit();
}
From within the file executed when www.myweb.com/search
is requested, you should have a default setting when $_GET['sort'] isn't available. For this Answer, I'll be using PHP for my examples since you didn't specify.
<?php
if (empty($_GET['sort'])) {
$sort = 'ascending';
}
// the rest of your code
Alternatively, you could force a redirect, but the previous example is more elegant.
<?php
if (empty($_GET['sort'])) {
header('Location: www.myweb.com/search/?sort=ascending');
exit;
}
Keep in mind, the second solution would throw away anything else, i.e., other $_GET's, like item=widget
or color=blue
Note to others posting !isset
as an answer. That will not work! Example:
www.myweb.com/search/?sort=&foo=bar
!isset($_GET['sort'])
=== false!
empty($_GET['sort'])
is the proper route to take in this circumstance.
It is better to define the variable by yourself rather then redirecting. Just check with isset if the variable is defined or not. It it has not been defined you can set it yourself as below.
if(!isset($_GET['sort']))
{
$_GET['sort']='ascending";
}