How to add a GET variable to the current URL?

扶醉桌前 提交于 2019-12-25 03:40:26

问题


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


回答1:


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

if (empty($_GET['sort'])) {
    header('Location: ' . $_SERVER['REQUEST_URI'] . '?sort=ascending');
    exit();
}



回答2:


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.




回答3:


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";
}


来源:https://stackoverflow.com/questions/14311643/how-to-add-a-get-variable-to-the-current-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!