0

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); ?> 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.

MultiformeIngegno
  • 6,959
  • 15
  • 60
  • 119

2 Answers2

1

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 (a.k.a 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;
}
Pedro M. Silva
  • 1,298
  • 2
  • 12
  • 23
0

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;
}
Phiter
  • 14,570
  • 14
  • 50
  • 84
  • Thank you both! I'm accepting this cause it was the most recent. – MultiformeIngegno Mar 01 '16 at 17:19
  • Can I add a check of whether `$_SERVER['HTTP_ACCEPT_LANGUAGE']` is set? Cause many requests (for example from Crawlers) will be redirected to "lang=" without lang.. could I add a check that is `$_SERVER['HTTP_ACCEPT_LANGUAGE']` is not set, "en" is applied? – MultiformeIngegno Mar 01 '16 at 17:23
  • Yeah, you can do this. But the check will be done every time just as this one. – Phiter Mar 01 '16 at 17:26