Un-setting variable in URL gives error - php

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

Related

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

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.

Getting the second part of a URL through PHP

I'm trying to setup a page that pulls just a part of the URL but I can't even get it to echo on my page.
Since I code in PHP, I prefer dynamic pages, so my urls usually have "index.php?page=whatever"
I need the "whatever" part only.
Can someone help me. This is what I have so far, but like I said, I can't even get it to echo.
$suburl = substr($_SERVER["HTTP_HOST"],strrpos($_SERVER["REQUEST_URI"],"/")+1);
and to echo it, I have this, of course:
echo "$suburl";
If you need to get the value of the page parameter, simply use the $_GET global variable to access the value.
$page = $_GET['page']; // output => whatever
your url is index.php?page=whatever and you want to get the whatever from it
if the part is after ? ( abc.com/xyz.php?......) , you can use $_GET['name']
for your url index.php?page=whatever
use :
$parameter= $_GET['page']; //( value of $parameter will be whatever )
for your url index.php?page=whatever&no=28
use :
$parameter1= $_GET['page']; //( value of $parameter1 will be whatever )
$parameter2= $_GET['no']; //( value of $parameter2 will be 28 )
please before using the parameters received by $_GET , please sanitize it, or you may find trouble of malicious script /code injection
for url : index.php?page=whatever&no=28
like :
if(preg_match("/^[0-9]*$/", $_GET['no'])) {
$parameter2= $_GET['no'];
}
it will check, if GET parameter no is a digit (contains 0 to 9 numbers only), then only save it in $parameter2 variable.
this is just an example, do your checking and validation as per your requirement.
You can use basic PHP function parse_url for example:
<?php
$url = 'http://site.my/index.php?page=whatever';
$query = parse_url($url, PHP_URL_QUERY);
var_dump(explode('=', $query));
Working code example here: PHPize.online

how to separate the request uri into a for loop to break down variables

i have the need to break down a REQUEST_URI to perform a few functions for each string between the slashes
the request that is passed from the url looks something like the below url however i cannot assign them static variables as the url could get longer or shorter per different pages
https://www.domain.com/accounts/customers/details
what im looking to do is capture the "accounts/customers/details" section which i have done by this variable on the page
$requested_url = $_SERVER['REQUEST_URI']; // this outputs /accounts/customers/details
i wish to create a for loop extracting the information from between the brackets and displaying it on page like
accounts
customers
details
how can this be achieved
try this
$requested_url = $_SERVER['REQUEST_URI'];
$seperate = explode("/",$requested_url); //this will explode in to array with "/" seperator
foreach($seperate as $seprt) {
echo $seprt."<br/>"; //it echo's each array variable seperately
}
$requested_url = $_SERVER['REQUEST_URI'];
$seperate = explode("/",$requested_url);
$count = 0;
foreach($seperate as $seprt) {
$count++;
if($count == count($seperate)){
echo $seprt;
}
}

Add/Replace URL GET parameter depending on current URL

I’ve tried for some time now to solve what probably is a small issue but I just can’t seem get my head around it. I’ve tried some different approaches, some found at SO but none has worked yet.
The problem consists of this:
I’ve a show-room page where I show some cloth. On each single item of cloth there is four “views”
Male
Female
Front
Back
Now, the users can filter this by either viewing the male or female model but they can also filter by viewing front or back of both gender.
I’ve created my script so it detects the URL query and display the correct data but my problem is to “build” the URL correctly.
When firstly enter the page, the four links is like this:
example.com?gender=male
example.com?gender=female
example.com?site=front
example.com?site=back
This work because it’s the “default” view (the default view is set to gender=male && site=front) in the model.
But if I choose to view ?gender=female the users should be able to filter it once more by adding &site=back so the complete URL would be: example.com?gender=female&site=back
And if I then press the link to see gender=male it should still keep the URL parameter &site=back.
What I’ve achived so far is to append the parameters to the existing URL but this result in URL strings like: example.com?gender=male&site=front&gender=female and so on…
I’ve tried but to use the parse_url function, the http_build_query($parms) method and to make my “own” function that checks for existing parameters but it does not work.
My latest try was this:
_setURL(‘http://example.com?gender=male’, ‘site’, ‘back’);
function _setURL($url, $key, $value) {
$separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&';
$query = $key."=".$value;
$url .= $separator . $query;
var_dump($url); exit;
}
This function works unless the $_GET parameter already exists and thus should be replaced and not added.
I’m not sure if there is some “best practice” to solve this and as I said I’ve looked at a lot of answers on SO but none which was spot on my issue.
I hope I’ve explained myself otherwise please let me know and I’ll elaborate.
Any help or advice would be appreciated
You can generate the links dynamically using the following method:
$frontLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=front':'mydomain.com?site=front';
$backLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=back':'mydomain.com?site=back';
This is a 1 line if statement which will set the value of the variables $frontLink and $backlink respectively. The syntax for a 1 line if statement is $var = (if_statement) ? true_result:false_result; this will set the value of $var to the true_result or false_result depending on the return value of the if statement.
You can then do the same for the genders:
$maleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=male&site='.$_GET['site']:'mydomain.com?gender=male';
$femaleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=female&site='.$_GET['site']:'mydomain.com?gender=female';
Found this by searching for a better solution then mine and found this ugly one (That we see a lot on the web), so here is my solution :
function add_get_parameter($arg, $value)
{
$_GET[$arg] = $value;
return "?" . http_build_query($_GET);
}
<?php
function requestUriAddGetParams(array $params)
{
$parseRes=parse_url($_REQUEST['REQUEST_URI']);
$params=array_merge($_GET, $params);
return $parseRes['path'].'?'.http_build_query($params);
}
?>
if(isset($_GET['diagid']) && $_GET['diagid']!='') {
$repParam = "&diagid=".$_GET['diagid'];
$params = str_replace($repParam, "", $_SERVER['REQUEST_URI']);
$url = "http://".$_SERVER['HTTP_HOST'].$params."&diagid=".$ID;
}
else $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."&diagid=".$ID;

Pass an array from one file to another using include

How to pass an array from one file to another using include using PHP language?
I have one file with some language array(language/langen.php):
global $lang;
$lang['Here'] = 'Here';
$lang['Date'] = "Date";
In other file I have:
include base_url().'language/lang'.$_COOKIE['lang'].'.php';
var_dump($lang);
*(My mistake by coping code - true is var_dump($lang))*
But it shows me an error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: lang
How to solve this problem and what did I do wrong?
First of all:
You should never use cookie value directly in include statement - its pretty easy to make fake cookie and mess up in your application.
I suppose you just don't have cookie with name lang or variable $lang has never been initialized before.
To check if cookie exists and is in correct format you can do like that:
// set default lang code
$langCode = 'en';
// check if cookie exists and if contains string build from 2 characters from range a-z
// check also if file exists
if (isset($_COOKIE['lang'] && preg_match('/^[a-z]{2}$/', $_COOKIE['lang']) &&
file_exists(base_url().'language/lang'.$_COOKIE['lang'].'.php')) {
$langCode = $_COOKIE['lang'];
}
include base_url().'language/lang'.$langCode.'.php';
in included file you should check if variable $lang exists
if (!isset($lang)) $lang = array();
$lang['Here'] = 'Here';
$lang['Date'] = "Date";
also I think using global here is pointless as from your example it looks like its the same scope.
anyway for me much cleaner solution would be:
// first_file.php
$langCode = 'en';
if (isset($_COOKIE['lang'] && preg_match('/^[a-z]{2}$/', $_COOKIE['lang']) &&
file_exists(base_url().'language/lang'.$_COOKIE['lang'].'.php')) {
$langCode = $_COOKIE['lang'];
}
$lang = include base_url().'language/lang'.$langCode.'.php';
// langen.php
return array(
'Date' => 'Date',
'Here' => 'Here',
);
EDIT
One more thing - If base_url() is returning web URL (like http://example.com...) then it is also wrong (and also can cause problem as langen.php will contain at least Notice message when included this way) - should be included with valid file path
Shouldn't it be?
include base_url().'language/lang'.$_COOKIE['lang']['Here'].'.php';
Or else it would just return array()
First of all, I don't see the point of var-dumping variable $data, if there is no such thing in code you posted. If you have a cookie called "lang" in your browser, then you should be fine. You could always check this by
var_dump($GLOBALS['lang']);
in your code. It should print the array of values from your lang*.php file.

Categories