简体   繁体   中英

PHP: If URL doesn't have parameter, redirect to URL with it

How can I redirect requests to http(s)//domain.tld/WHATEVER.php to http(s)//domain.tld/WHATEVER.php?lang=<?php substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); ?> http(s)//domain.tld/WHATEVER.php?lang=<?php substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); ?> in PHP?

So, if you visit a URL already with a lang parameter, fine, do nothing. If the lang parameter is not present, 301 redirect to the URL containing the lang param.

Try this. Note that the exit is important, because setting the header as location will not terminate the current page. Also, be aware that you can only send headers if you haven't sent out anything to the client yet (aka not having done any echos or prints).

if ( !isset( $_GET[ 'lang' ] ) ) {
    header( 'Location: http(s)//domain.tld/WHATEVER.php?lang=' . substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) );
    exit;
}

Since lang is a GET variable, you can simply check if it is set. If so, redirect to the desired URL.

if(!isset($_GET['lang'])){
header('location: ' . 'http(s)//domain.tld/WHATEVER.php?lang='. substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
exit;
}

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