PHP detect if slug URL starts with ES/ or EN/ - php

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?

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

To achieve what we want, we need to:
Find the URL of the current page - we can use $_SERVER['REQUEST_URI'] (Get the full URL in PHP
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
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';
}

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

Validate parts of URLs with PHP

I'm trying to check against an array of URL's with PHP, but one of the URL's will have some random strings in front of it (generated sub domain).
This is what I have so far:
<?php
$urls = array(
'127.0.0.1',
'develop.domain.com'
);
?>
<?php if (in_array($_SERVER['SERVER_NAME'], $urls)) : ?>
//do the thing
<?php endif; ?>
The only thing is that the develop.domain.com will have something in front of it. For example namething.develop.domain.com.
Is there a way to check for a wildcard in the array of URL's so that it can check for the 127.0.0.1 and and matches for develop.domain.com?
Simplest way is to go all regex like this
// Array of allowed url patterns
$urls = array(
'/^127.0.0.1$/',
'/^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*(develop.domain.com)$/i'
);
// For each of the url patterns in $urls,
// try to match the $_SERVER['SERVER_NAME']
// against
foreach ($urls as $url) {
if (preg_match($url, $_SERVER['SERVER_NAME'])) {
// Match found. Do something
// Break from loop since $_SERVER['SERVER_NAME']
// a pattern
break;
}
}
Assuming that URL will use one word in sub-domain like you mentioned in your question.
If URL consists of more than one word then the following code needs to be modified as per expected word in sub-domain.
<?php
// Supported URLs array
$urls = array(
'127.0.0.1',
'develop.domain.com'
);
// Server name
//$_server_name = $_SERVER['SERVER_NAME'];
$_server_name = 'namething.develop.domain.com';
// Check if current server name contains more than 2 "." which means it has sub-subdomain
if(substr_count($_server_name, '.') > 2) {
// Fetch sub-string from current server name starting after first "." position till end and update it to current server name variable
$_server_name = substr($_server_name, strpos($_server_name, '.')+1, strlen($_server_name));
}
// Check if updated/filterd server name exists in our allowed URLs array
if (in_array($_server_name, $urls)){
// do something
echo $_server_name;
}
?>
Output:
PASS domain.develop.domain.com
PASS namething.develop.domain.com
FAIL subsubdomain.domain.develop.domain.com
FAIL namething1.namething2.develop.domain.com

How can I check the post slug?

Scenario: As you know, StackOverflow checks the title in the question. I mean when you open this URL:
http://stackoverflow.com/questions/38839016/should-i-store-the-result-of-an-function
automatically it will be replaced with this:
http://stackoverflow.com/questions/38839016/should-i-store-the-result-of-an-function-into-an-array
That replacement is because of being incomplete the first URL.
Ok well, I'm trying to make such a system by PHP. Here is my attempt:
// getting this from the URL
$id = '38839016';
// fetching this from database based on that id (38839016)
$real_title = $result['title'];
//=> Should I store the result of an function into an array
$real_title = str_replace("-"," ",strtolower($real_title));
//=> should-i-store-the-result-of-an-function-into-an-array
// getting whole uri
$current_uri = $_SERVER["REQUEST_URI"];
//=> /questions/38839016/should-i-store-the-result-of-an-function
What I want to do: I need to compare $real_title with title-part of the $current_uri. How can I determine "title-part"? It is everything which is after $id.'/' until / or ? or $ (end of string). How can I do that comparison?
And then:
if ( preg_match("//", $current_uri) ) {
// all fine. continue loading the page
continue;
} else {
// replace title-part of the $current_uri with $real_title
preg_replace("//", $real_title, $current_uri);
// redirect to this post with correct slug
header('Location: '.$_SERVER["HTTP_HOST"].);
}
briefly, I want to complete these:
if ( preg_match("//", $current_uri) ) {
preg_replace("//", $real_title, $current_uri);
Ok, in simple words, there is a good url and a requested url
if the requested url not equal the good url
redirect the visitor to the good one
<?
$id = '38839016';
$good_url = '/questions/'.$id.'/'.str_replace("-"," ",strtolower($result['title']));
preg_match( '/\/[0-9]+\/([a-z0-9-]+)\/.*/', $_SERVER[REQUEST_URI], $matches);
if ($matches[1] != str_replace("-"," ",strtolower($result['title'])))
header('Location: '.$good_url);

Un-setting variable in URL gives error

I've recently been developing a multi-lingual website. I've got a slight problem though.
Every time a button is clicked the language variable needs to change. i did this using the anchor tag (i.e English ).
The problem arises when other variables besides the language are added to the URL. I would like to redirect the page without getting rid of other variables and just changing the lang variable. So if the url contains "var1=value&var2=value&lang=En", I would like to alter the lang variable and keep the rest as they are. The lang variable can have 3 values: En, Az, Ru.
The method I tried so far:
function URI_ADD_AZ(){
$URI = $_SERVER['REQUEST_URI'];
if(isset($_GET['lang'])){
$lang = $_GET['lang'];
unset($lang);
}
$new_URI = $URI . '?lang=Az';
return $new_URI;
}
Azeri
The problem:
Everytime the button is clicked the lang variable just gets added to the url not altered:
/?lang=Az?lang=Az?lang=Az?lang=Az
How can I make sure it does not keep getting repeated and avoid redirect loops?
The URI_ADD_AZ function posted in the question does not overwrite or remove preexisting occurrences of lang=* in the Query String, therefore duplication of "langs" in the URL. Also there is no handling of the requirement for ? or & depending on location of the key=value pair in the query string.
Here, to simplify things and limit the working string and therefore potential for introducing errors, the $_SERVER var QUERY_STRING is pulled, rather than the entire REQUEST_URI, and PHP_SELF is then prepended to the HREF value.
First thing here is to remove the lang=* including the & depending on it's position. A conditional reference is used to remove the trailing & only if the match is found at the beginning of the string.
Next $lang is retrieved from the $_GET var and validated. And if there's a valid $lang it is appended to the query string taking into consideration whether & is needed or not.
Finally, if not empty, the resulting query string is prepended with ? and returned.
function URI_ADD_AZ() {
$QS = preg_replace('/((^)|&)lang=[^&]*(?(2)&)?/', '', $_SERVER['QUERY_STRING']);
$lang = ( isset($_GET['lang']) && in_array($_GET['lang'], array('En','Az','Ru')) )? 'lang=' . $_GET['lang']: '';
if ( '' != $lang ) {
if ( '' == $QS ) { $QS = $lang; }
else { $QS .= "&$lang"; }
}
if ( '' != $QS ) {
return '?' . $QS;
}
}
Azeri
Simply provide Complete URL :-
Azeri
or, if you want to do it without reloading of page, you will have to use "jquery.history.js" file.
https://github.com/browserstate/history.js
History.pushState(null, 'title of my website', "?lang=<?php URI_ADD_AZ(); ?>);
Thanks

finding current url and splitting them into parts and checking if there is index.php or not in the url

I am suffering from a problem while i take the current url of the page and spliting them into parts and then checking for the index.php phrase.So far i have done this:
<?php
$domain=$_SERVER['REQUEST_URI'];
$values = parse_url($domains);
$path = explode('/',$values['path']);
if(array_search($path[2], "index.php"))
{
echo "hello";
}
?>
but its not working so guys help me out and thank you in advance coz i know i will be satisfied by your answers.
Try this:
$pathToFile = $_SERVER['PHP_SELF'];
$currentFilename = substr($pathToFile, strrpos($pathToFile, '/') + 1);
if($currentFilename == 'index.php')
{
echo 'This file is index.php!';
}
$_SERVER['PHP_SELF'] is the path to the current file on the local system. Since you don't care about the domain name or the query string, this is easier.
strrpos($pathToFile, '/') gets the index of the last occurrence of / in $pathToFile.
substr($pathToFile, strrpos($pathToFile, '/') + 1) get the portion of $pathToFile starting with the character after the index found by strrpos() in step 2.
You should be left with only the filename in $currentFilename, which you can compare with whatever you choose.
Note that this will match any index.php file, not just the one at your domain root. For example, if your site is located at http://example.com, http://example.com/subdir/index.php would also be true for $currentFilename == 'index.php'. If that's not what you want, you'd do it a little differently.
Use this:
$domain=$_SERVER['REQUEST_URI'];
$path = explode('/',$domain);
if(array_search($path[2], "index.php"))
{
echo "hello";
}
I'm not sure what parse_url() is, but it didn't seem to do anything in your code.

clean the url in php

I am trying to make a user submit link box. I've been trying all day and can't seem to get it working.
The goal is to make all of these into example.com... (ie. remove all stuff before the top level domain)
Input is $url =
Their are 4 types of url:
www.example.com...
example.com...
http://www.example.com...
http://example.com...
Everything I make works on 1 or 2 types, but not all 4.
How one can do this?
You can use parse_url for that. For example:
function parse($url) {
$parts = parse_url($url);
if ($parts === false) {
return false;
}
return isset($parts['scheme'])
? $parts['host']
: substr($parts['path'], 0, strcspn($parts['path'], '/'));
}
This will leave the "www." part if it already exists, but it's trivial to cut that out with e.g. str_replace. If the url you give it is seriously malformed, it will return false.
Update (an improved solution):
I realized that the above would not work correctly if you try to trick it hard enough. So instead of whipping myself trying to compensate if it does not have a scheme, I realized that this would be better:
function parse($url) {
$parts = parse_url($url);
if ($parts === false) {
return false;
}
if (!isset($parts['scheme'])) {
$parts = parse_url('http://'.$url);
}
if ($parts === false) {
return false;
}
return $parts['host'];
}
Your input can be
www.example.com
example.com
http://www.example.com
http://example.com
$url_arr = parse_url($url);
echo $url_arr['host'];
output is example.com
there's a few steps you can take to get a clean url.
Firstly you need to make sure there is a protocol to make parse_url work correctly so you can do:
//Make sure it has a protocol
if(substr($url,0,7) != 'http://' || substr($url,0,8) != 'https://')
{
$url = 'http://' . $url;
}
Now we run it through parse_url()
$segments = parse_url($url);
But this is where it get's complicated because the way domain names are constructed is that you can have 1,2,3,4,5,6 .. .domain levels, meaning that you cannot detect the domain name from all urls, you have to have a pre compiled list of tld's to check the last portion of the domain, so you then can extract that leaving the website's domain.
There is a list available here : http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1
But you would be better of parsing this list into mysql and then select the row where the tld matches the left side of the domain string.
Then you order by length and limit to 1, if this is found then you can do something like:
$db_found_tld = 'co.uk';
$domain = 'a.b.c.domain.co.uk';
$domain_name = substr($domain,0 - strlen($db_found_tld));
This would leave a.b.c.domain, so you have removed the tld, now the domain name would be extracted like so:
$parts = explode($domain_name);
$base_domain = $parts[count($parts) - 1];
now you have domain.
this seems very lengthy but I hope now you know that its not easy to get just the domain name without tld or sub domains.

Categories