I am passing a URL in the browser like http:mydomain.com/Code/LT1234/
In my page template I am using
<?php echo $_SERVER['REQUEST_URI'];?>
to get the URL, which prints <strong>/Code/LT1234/</strong>
From here, how do I get ONLY "LT1234" I need it to put in a variable.
like:
$code=LT1234
<em>Note: I cannot pass the link http:mydomain.com/Code/?id=LT1234/ So I cant use GET to get the variable</em>
Thanks!
Kailey Lampert answers:
This should work for what you describe above
$r = $_SERVER['REQUEST_URI']; // /Code/LT1234/
$r = explode('/', $r);
$r = array_filter($r);
$r = array_merge($r, array()); //reset keys
$code = $r[1];
But may require modification if you need more flexibility.
platinum comments:
Thank you this worked perfectly.
Maor Barazany answers:
If you need always to take the last part of the uri you got (i.e - <strong>/Code/LT1234/</strong>), than you can use php explode -
<?php
$uri = $_SERVER['REQUEST_URI'];
$tmp = explode('/', $uri);
$param = end($tmp);
echo $param;
?>
Luis Cordova answers:
This should do, even better as you want to make sure you get the Code part in the url for security or error reporting purposes:
<?php
$urlPlusKey = $_SERVER['REQUEST_URI'];
$urlArray = explode('/', $urlPlusKey); // array(Code, LT1234)
$param = end($urlArray);
$codeIf = prev($urlArray);
if ($codeIf == 'Code') {
$key = $param;
} else {
$key = 'null';
}
?>
Comments:
The other approach with untrailingslashit is only wp based so be careful using that function
$url_part = untrailingslashit($url_parts['path']);
The other simplifications with basename online also could lack the security although it is simpler but will fail if your path does not contain the 'Code' string right before.
Jurre Hanema answers:
The single most simple way to do this in this case is the following one-liner:
$code = basename($_SERVER['REQUEST_URI']);
:-)
Luis Abarca answers:
$url = parse_url($_SERVER['REQUEST_URI']);
$path = explode('/', $url['path']);
// First element is a empty
$yourvar = array($path[1] => $path[2]);
var_dump($yourvar);
Luke America answers:
one more example ...
$url = $_SERVER['REQUEST_URI'];
$url_parts = parse_url($url);
$url_part = untrailingslashit($url_parts['path']);
$url_pieces = explode('/', $url_part);
$url_end_piece = end($url_pieces);