Detecting browser language in PHP and redirect - php

I want to write a simple if statement using HTTP_ACCEPT_LANGUAGE function that redirects based on result of what the users browser language is. I am still a beginner so am obviously keeping it as simple as possible. This is what I have so far but the "if" statement needs work. Can anyone help me with a fix?
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ($lang=german) {
header("Location: http://www.example.com/german/index.html");
} else if ($lang=spanish) {
header("Location: http://www.example.com/spanish/index.html");
}
else if ($lang=french) {
header("Location: http://www.example.com/french/index.html");
}
else if ($lang=chinese) {
header("Location: http://www.example.com/chinese /index.html");
} else {
echo "<html>english content</html>";
}
?>

I don't know what your language literals are, so I'd say make them ISO language codes.
Use a switch statement, this is more readable and smaller:
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
switch($lang) {
case "de-DE":
case "es-ES":
case "cn-CN":
case "fr-FR":
header("Location: http://www.example.com/$lang/index.html");
break;
default:
header("Location: http://www.example.com/en-US/index.html");
break;
}
Further, you are assigning, not comparing. You compare with ==:
if ($lang == "de-DE")

Assuming you always redirect to /language/, you could do it this way:
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ( in_array( $lang,array("german","spanish","french","chinese") ) ) {
header("Location: http://www.example.com/$lang/index.html");
} else {
echo "<html>english content</html>";
}
?>
Also, the comparisons in your if need to be done with ==, it's assignment otherwise!

Try this:
<?php
$path = array(
'en-US' => 'english',
// etc
);
$accepts = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
if (in_array($accepts[0], $path)) { // if path exists for language then redirect to path, else redirect to default path (english)
header('Location: http://www.example.com/' . $path[$accepts[0]] . '/index.html');
} else {
header('Location: http://www.example.com/english/index.html');
}
?>

HTTP_ACCEPT_LANGUAGE returns not "english", but two signs symbol like "en", or region and language symbol like "en_us". You shouldn't use if statement it's hard to read. You should use array (in future you can simple write it to config files, or move to databases).
The proper code should look that:
$default_lang = 'en';
$lang_redirectors = array('de' => 'http://www.example.com/german/index.html',
'en' => 'http://www.example.com/english/index.html');
function redirect($url){
header("Location: " . $url);
}
$hal = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$langs = explode($hal, ',');
foreach($langs as $lang){
$lang_prefix = substr($lang, 0, 2);
if(in_array($lang_prefix, $lang_redirectors)){
redirect($lang_redirectors[$lang_prefix]);
break;
}
redirect($lang_redirectors[$default_lang]);
}

<?php
$browserlang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$lang = $browserlang[0] . $browserlang[1] . $browserlang[2] . $browserlang[3] . $browserlang[4];
if (($lang=="sk_SK") OR ($lang=="sk-SK")) {
header("Location: https://www.example.sk/sk");
}
else if (($lang=="en_EN") OR ($lang=="en-EN") OR ($lang=="en_GB") OR ($lang=="en_US") OR ($lang=="en-GB") OR ($lang=="en-US")) {
header("Location: https://www.example.sk/en");
}
else {
header("Location: https://www.example.sk/en");
}
?>

Related

How can I redirect without infinite loop in PHP code?

I have two WordPress sites using the multi-site function, the URLs are below:
A: sample.com
B: sample.com/en
I tried to write a code in PHP following these conditions, but when I access the RUL of A:sample.com, a browser(chrome) shows an error.
So would you mind telling me how should I solve this problem?
Thank you in advance.
the conditions for access
The first access is only to [A: sample.com]
Users whose browser language is set to Japanese access to [A:
sample.com]
All users whose browser language setting is not set to Japanese
access [B: sample.com/en]
The errors messages in the browser(chrome)
This page isn’t working
sample.com redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
The code for adding in functions.php
<?php
$uri = $_SERVER['REQUEST_URI'];
$BASE_LANG = 'en';
if (!preg_match('/^[!-~][a-zA-Z]{2}[!-~]/', $uri)) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$lang = $BASE_LANG;
if (isset($languages)) {
$browser_lamguage = $languages[0];
$base_languages = array('ja', 'en');
foreach ($base_languages as $base_language) {
if (preg_match("/^$base_language/i", $browser_lamguage)) {
$lang = $base_language;
break;
}
}
}
$url = get_site_url()."/$lang/";
if ($lang == 'ja') {
$url = get_site_url();
}
header("Location: $url");
exit();
}
?>
Development environment
CentOS (7 x86_64)
Apache (2.4.6 CentOS)
PHP (7.1.33)
wordpress(5.2.5)
Just make below change in your code:
if ($lang != 'ja') {
header("Location: $url");
exit();
}
Edited:
$uri = $_SERVER['REQUEST_URI'];
$BASE_LANG = 'en';
if (!preg_match('/^[!-~][a-zA-Z]{2}[!-~]/', $uri)) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$lang = $BASE_LANG;
if (isset($languages)) {
$browser_lamguage = $languages[0];
$base_languages = array('ja', 'en');
foreach ($base_languages as $base_language) {
if (preg_match("/^$base_language/i", $browser_lamguage)) {
$lang = $base_language;
break;
}
}
}
$url = get_site_url()."/$lang/";
if ($lang != 'ja') {
header("Location: $url");
exit();
}
}

PHP Header Redirect, If Variable Then Redirect

I want to use one URL to redirect users to various outgoing URLs. For example http://example.com/out.php?ofr=2 where ofr will refer to the appropriate URL the user should be redirected to.
I have the following php code for out.php
Is this acceptable, or is there a more efficient way to accomplish this (assuming there were 10 or so different URLs in the below script)?
<?php
$ofr = $_GET['ofr'];
if ($ofr == 1) {
header('location: http://google.com');
}
elseif ($ofr == 2) {
header('location: http://yahoo.com');
}
else {
header('location: http://msn.com');
}
?>
Edit: Looking at switch statements as suggested, I believe it would look like:
$ofr = $_GET['ofr'];
switch ($ofr){
case 1: header('location: http://example_1.com');
break;
case 2: header('location: http://example_2.com');
break;
default: header('location: http://example_2.com');
break;
}
Does that look correct? Thanks!
First of all I suggest to make a redirect function like so:
function redirect($url)
{
$baseUri=_URL_;
if(headers_sent())
{
$string = '<script type="text/javascript">';
$string .= 'window.location = "' . $baseUri.$url . '"';
$string .= '</script>';
echo $string;
}
else
{
if (isset($_SERVER['HTTP_REFERER']) AND ($url == $_SERVER['HTTP_REFERER']))
header('Location: '.$_SERVER['HTTP_REFERER']);
else
header('Location: '.$baseUri.$url);
}
exit;
}
then in a file called redirectFiles.php make array of the urls that you want to redirect:
$redirecUrls = [
'location: http://example_1.com',
'location: http://example_2.com',
'location: http://example_3.com',
]
then make a function to do the redirecting:
function redirectUrls($index){
if(isset($redirecUrls[ $index])
return redirect($redirecUrls[ $index])
return false;
}
After that you can do something like this:
$ofr = $_GET['ofr'];
if($ofr!='')
redirectUrls($ofr)
Try something like this:
<?php
$ofr=$_GET['ofr'];
$url_array=array([1]=>http://google.com [2]=>http://yahoo.com);
foreach($url_array as $key=>$value)
{
if($ofr==$key)
header('location: ".$value."');
}
?>

Using PHP function for shortening repeating code

My code in PHP is pretty long and I want to make it shorter with creating one function with different values and than I would just write one line with function name instead of many lines of code, but it doesn't seem to work.
This is that repeating code:
if (!isset($_POST['ID_user']) || empty($_POST['ID_user'])) {
$_SESSION['ID_user_missing'] = "error";
header("location: index.php");
} else {
$ID_user = $_POST['ID_user'];
}
if (!isset($_POST['meta_name']) || empty($_POST['meta_name'])) {
$_SESSION['meta_name_missing'] = "error";
header("location: index.php");
} else {
$meta_name = $_POST['ID_user'];
}
if (!isset($_POST['meta_value']) || empty($_POST['meta_value'])) {
$_SESSION['meta_value_missing'] = "error";
header("location: index.php");
} else {
$meta_value = $_POST['meta_value'];
}
And this was the plan, instead of that code up ther, I would just have this down below:
function ifIssetPost($value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
} else {
$$value = $_POST[$value];
}
}
ifIssetPost('ID_user');
ifIssetPost('meta_name');
ifIssetPost('meta_value');
But it just doesn't work, when you try to echo for example variable $meta_name it shows that it's empty. Can you help me ? Thank you very much.
NOTE: when I doesn't that function and do it the long way, everything works just fine, but the problem comes when I use that function.
The variable is in the scope of function. That's why you cannot access to it outside the function. You could return the value:
function ifIssetPost($value) {
if (empty($_POST[$value])) { // Only empty is needed (as pointed out by #AbraCadaver)
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
exit; // add exit to stop the execution of the script.
}
return $_POST[$value]; // return value
}
$ID_user = ifIssetPost('ID_user');
$meta_name = ifIssetPost('meta_name');
$meta_value = ifIssetPost('meta_value');
You can also follow your specification, using $$value:
function ifIssetPost($value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
} else {
return $_POST[$value];
}
}
$value = 'ID_user';
$$value = ifIssetPost($value);
echo $ID_user;
$value = 'meta_name';
$$value = ifIssetPost($value);
echo $meta_name;
You can use an array to iterate over the $_POST vars. If you want to declare a variable using a string or another variable containing an string, you need to use {}. like ${$value}
$postValues = ["ID_user", "meta_name", "meta_value"];
foreach ($postValues as $value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value."_missing"] = "error";
header("location: index.php");
} else {
${$value} = $_POST[$value];
}
}

PHP GET String with explode and if statements

I am writing what I thought would be a simple script but I am stuck.
The scenario is that I want to create 2 strings from the GET request.
eg: domain.com/script.php?Client=A12345
In script.php it needs to grab the "Client" and create 2 variables. One is $brand and needs to grab the A or B from the URL. The Other is $id which needs to grab the 12345 from the URL.
Now, after it has these 2 variables $brand and $id it needs to have an if statement to redirect based on the brand like below
if ($brand=="A") {
header('Location: http://a.com');
}
if ($brand=="B") {
header('Location: http://b.com');
At the end of each URL I want to apend the $id though and I am unsure on how to do this.
So for example I would access the script at domain.com/script?Client=A1234 and it needs to redirect me to a.com/12345
Thanks in advance!
$fullCode = $_REQUEST['Client'];
if(strpos($fullCode, 'A') !== false) {
$exp = explode('A',$fullcode);
header('Location: http://a.com/' . $exp[1]);
}
else if(strpos($fullCode, 'B') !== false) {
$exp = explode('B',$fullcode);
header('Location: http://b.com/' . $exp[1]);
}
else {
die('No letter occurence');
}
You can easily do,
$value = $_GET['Client'];
$brand = substr($value, 0, 1);
$rest = substr($value, 1, strlen($brand)-1);
now you have the first character in $brand string and you can do the if statement and redirect the way you want...
You mean like this?
Notice: this will only work if brand is just 1 character long. If that's not the case, please give better examples.
<?php
$client = $_GET['Client'];
$brand = strtolower(substr($client, 0, 1));
$id = substr($client, 1);
if ($brand == 'a')
{
header("Location: http://a.com/$id");
}
elseif ($brand == 'b')
{
header("Location: http://b.com/$id");
}
?>
Try using:
preg_match("/([A-Z])(\d*)/",$_GET['Client'],$matches);
$matches[1] will contain the letter and $matches[2] will contain your id.
Then you can use:
if ($matches[1]=="A")
{
header('Location: http://a.com/{$matches[2]}');
}
if ($matches[1]=="B")
{
header('Location: http://b.com/{$matches[2]}');
}
suggest you could also try
$requested = $_GET["Client"];
$domain = trim(preg_replace('/[^a-zA-Z]/',' ', $requested)); // replace non-alphabets with space
$brand = trim(preg_replace('/[a-zA-Z]/',' ', $requested)); // replace non-numerics with space
$redirect_url = 'http://' . $domain . '/' . $brand;
header('Location:' . $redirect_url);
but it'd be better if you could get the domain name and brand as two individual parameters and sanitize them individually before redirecting them to prevent the overhead of extracting them from a single parameter.
Note: this expression might be useless when the domain name itself has numerics and because the Client is obtained through get a good deal of validation and sanitation would be required in reality.
$brand = strtolower($_GET['Client'][0]);
$id = substr($_GET['Client'], 1);
header("Location: http://{$brand}.com/{$id}");
If for some purpose you want to use explode, then you need to have a separator.
Let's take '_' as the separator, so your example would be something like this: domain.com/script.php?Client=A_12345
$yourstring = explode("_",$_GET["Client"]);
echo $yourstring[0];
//will output A
echo $yourstring[1];
//will output 12345
//your simple controller could be something like this
switch($yourstring[0]){
case: 'A':
header('Location: http://a.com?id='.$yourstring[1]);
exit();
break;
case: 'B':
header('Location: http://b.com?id='.$yourstring[1]);
exit();
break;
default:
//etc
}

Optimising a PHP If/Else statement

I'm attempting to optimise the following PHP If/Else statement. Could I rewrite the code to make use to case and switch, or should I leave it as it is, or what?
Code:
if(empty($_GET['id'])){
include('pages/home.php');
}elseif ($_GET['id'] === '13') {
include('pages/servicestatus.php');
}elseif(!empty($_GET['id'])){
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if(!$rawdata){
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
}else{
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if(!$rawdata){
error_404();
}
}
Thanks
I hate switch statements, but its personal preference to be honest. As far as further optimization i'd suggest taking a look at some form of assembly language. It will give you some general ideas on how to make conditional statements more efficient. That is, it will give you a different out look on things.
if(!empty($_GET['id']))
{
if($_GET['id'] == '13')
{
include('pages/servicestatus.php');
}
else
{
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if (!$rawdata) {
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
} else {
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if (!$rawdata) {
error_404();
}
}
}
else
{
include('pages/home.php');
}
switch would be appropriate if you had several discrete values for $_GET['id'] that you were checking for.
One suggestion I can make for the sake of readability is that
} elseif (!empty($_GET['id'])) {
only needs to be
} else {
Well i don't think it's necessary to switch to a swith
but you could change
} elseif (!empty($_GET['id'])) {
to just
}else{
You may want to look into breaking up your code into a MVC form; that would make it much easier to maintain your code. At least put the last clause into another file, probably called default.php and include it. Also, you might create an array of id => file key/value sets, lookup the id, and include the file.
if (isset($_GET['id'])) {
$pages = array(
0 => 'home.php',
13 => 'servicestatus.php'
);
if (isset($pages[$_GET['id']])) {
include('pages/' . $pages[$_GET['id']]);
} else {
include('pages/default.php');
}
}
Yes, switch is evaluate once, is efficient than if elseif,
and is easier to maintain with this given structure
switch ($_GET['id'])
{
case 13: ... break;
case 0 : ... break;
default: ... break;
}
I dont know, if you should, or should not, but here I wouldnt. The main reason is, that there is at least one statement, you can omit, and then, you will have just a if-elseif-else-Statement
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
elseif (!empty($_GET['id'])) { /* code* }
is the same as
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
else { /* code* }
In the block after that, the statement if(!$rawdata) is also duplicated.

Categories