简体   繁体   中英

Php How do you redirect without copying the same url query

I am validating a form on a page and I need to redirect back to the same page with the same url query and a additional &valid=false at the end of the query when redirected.

How would you do this so that the url is not repeated on redirect:

http://test.com/index.php?a=1&b=2&valid=false&a=1&b=2&valid=false

I am using $_SERVER['REQUEST_URI']

There are many ways to do it, here is a simple one:

$url = $_SERVER['REQUEST_URI'];
if (!isset($_GET['valid'])) {
    $url.='&valid=false';    //assuming there are always additional parameters, otherwise you must check whether to use '?' or '&' 
}

But you can also use parse_url(), strpos(), regular expressions etc

You can use of http_build_query() after modifying parameters:

<?php
    $_GET['a'] = 1;
    $_GET['b'] = 2;
    $_GET['valid'] = 'true';

    $url = $_SERVER['SCRIPT_NAME'].'?'.http_build_query($_GET);
?>

Like that, if $_GET['valid'] is not defined then it will be created, else it will be modified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM