Home > Mobile >  PHP detect if slug URL starts with ES/ or EN/
PHP detect if slug URL starts with ES/ or EN/

Time:10-24

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?

CodePudding user response:

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';
}

CodePudding user response:

what about

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

?

CodePudding user response:

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.

  • Related