0

I need to detect the language the user is using to include the correct file using PHP if elseif or else like this:

users are comming from:

example.com/EN/nice-title-url-from-database-slug
example.com/DE/nice-title-url-from-database-slug
example.com/ES/nice-title-url-from-database-slug

the php I need is something like this:

PHP document.location.toString().split(...) etc detect the url paths

if url path <starts with /DE/>
  include de.php
elseif url <path starts with /EN/>
  include en.php
else url <path starts with /ES/>
  include es.php

so what I need is to detect the url after the domain (/ES/ or /EN/ or /DE/)

Any idea how to achieve this?

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • See [explode()](https://www.php.net/manual/en/function.explode) and [parse_url()](https://www.php.net/manual/en/function.parse-url). Also try to avoid if/else chains like this and instead use an array lookup or a `match` statement. – Alex Howansky Oct 23 '22 at 16:21

3 Answers3

1

what about

$check = "example.com/EN/";
if (substr($url, 0, strlen($check)) === $check) { ... }

?

timor33244
  • 61
  • 2
0

To get the page URL, use $_SERVER['REQUEST_URI']. Then use explode by / to get URL different parts.

$parts = explode('/',$_SERVER['REQUEST_URI']);

$parts now contain the below elements.

Array
(
    [0] => 
    [1] => EN
    [2] => nice-title-url-from-database-slug?bla
)

As you can see index 1 of the $parts array is what you need.

Lessmore
  • 1,061
  • 1
  • 8
  • 12
0

To achieve what we want, we need to:

  1. Find the URL of the current page - we can use $_SERVER['REQUEST_URI'] (Get the full URL in PHP
  2. From this, we want to figure out if it contains the language part. One way to do this, is to split the string, as you kindly suggest, and get second result (which is key 1): explode('/', $_SERVER['REQUEST_URI'])1
  3. Then we can do the include or what logic you need.

So following would be my suggestion.

// Get the uri of the request.
$uri = $_SERVER['REQUEST_URI'];

// Split it to get the language part.
$lang = explode('/', $uri)[1]; // 1 is the key - if the language part is placed different, this should be changed.

// Do our logic.
if ($lang === 'DE') {
  include 'de.php';
} else if ($lang === 'EN') {
  include 'en.php';
} else if ($lang === 'ES') {
  include 'es.php';
}
Aprilsnar
  • 521
  • 1
  • 5
  • 14