How to add a GET variable to the current URL?

2019-08-16 05:13发布

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

3条回答
神经病院院长
2楼-- · 2019-08-16 05:28

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";
}
查看更多
相关推荐>>
3楼-- · 2019-08-16 05:31

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.

查看更多
beautiful°
4楼-- · 2019-08-16 05:35

I think this will work for what you're looking to do:

if (empty($_GET['sort'])) {
    header('Location: ' . $_SERVER['REQUEST_URI'] . '?sort=ascending');
    exit();
}
查看更多
登录 后发表回答