How to get first 3 parts of current URL by using PHP.
For example:
My Url: http://something.com/somebody/somegirls/whatever/
The result after getting parts: http://something.com/somebody/somegirls/
This is my code PHP which get current URL:
<?php function curPageURL() {
$url = isset( $_SERVER['HTTPS'] ) && 'on' === $_SERVER['HTTPS'] ? 'https' : 'http';
$url .= '://' . $_SERVER['SERVER_NAME'];
$url .= in_array( $_SERVER['SERVER_PORT'], array('80', '443') ) ? '' : ':' . $_SERVER['SERVER_PORT'];
$url .= $_SERVER['REQUEST_URI'];
return $url;
}
$current_url = str_replace("www.", "", curPageURL());
?>
The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.
Get Last URL Segment If you want to get last URI segment, use array_pop() function in PHP.
The necessary superglobal variables such as $_SERVER['HTTPS'], $_SERVER['REQUEST_URI'], $_SERVER['SERVER_PORT'] are used to get full URL in PHP. The variable HTTPS can easily retrieve the protocol in the URL of a webpage. If it returns a value “on”, then the protocol is HTTPS.
php $url = 'http://www.example.com/register?name=demo&[email protected]'; $res = parse_url($url); parse_str($res['query'], $params); echo 'Email = '.
Try this,
<?php
$url = 'http://something.com/somebody/somegirls/whatever/';
$parts = explode('/', $url);
$new_url = $parts[0].'/'.$parts[1].'/'.$parts[2].'/'.$parts[3].'/'.$parts[4].'/';
echo $new_url;
?>
OUTPUT
http://something.com/somebody/somegirls/
Assuming that you have grabbed this URL from your function...
<?php
$url='http://www.something.com/somebody/somegirls/whatever/';
$parts=explode('/',parse_url($url)['path']);
array_unshift($parts,trim(strstr(parse_url($url)['host'],'.'),'.'));
print_r(array_filter($parts));
OUTPUT :
Array
(
[0] => something.com
[2] => somebody
[3] => somegirls
[4] => whatever
)
Demonstration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With