If I have url like this: www.example.com/product/yellow-bed
is it possible to retrieve product name from url? For example, if url would be like www.example.com?page=product&product_name=yellow_bed
I would use:
$product = $_GET['page'];
$product_name = $_GET['product_name'];
But how to get it from www.example.com/product/yellow-bed
?
Get the URI by "$_SERVER["REQUEST_URI"]". Convert the string into an array with explode:
$uri = 'www.google.com/product/yellow-bed' //uri = $_SERVER["REQUEST_URI"]
$uriArray = explode('/', $uri);
$product = $urlArray[1];
$product_name = $urlArray[2];
0 = www.google.com, 1 = product, 2 = yellow-bed
PHP manual: array explode ( string $delimiter , string $string [, int $limit ] )
.
Some php frameworks (like CodeIgniter) has already this function implemented. Never the less you can have a look here: http://erunways.com/simple-php-get-uri-or-segment-element/ , and that should solve your problem.
You could fetch the complete URI with $_SERVER['QUERY_STRING']
and then split it apart. Or you work with an .htaccess and internally rewrite the url.
Try $_SERVER[ 'PATH_INFO' ]
or $_SERVER[ 'REQUEST_URI' ]
.
You should have a look at $_SERVER['REQUEST_URI']
. This will be /product/yellow-bed
in your example.
You can then use strrpos()
, explode() or
preg_match()` (or other string manipulation functions) to extract what you want.
you can use the following function to retrive current url:
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
now you can take url and parse its elements using parse_url : http://php.net/manual/en/function.parse-url.php