I was trying to get what page the visitor visit:
Here is my code:
$url = $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
$urlcomplete = $url;
$url = explode(".com/",$url);
$urlcount = count($url);
$newurl = '';
for ($start = 1; $start < $urlcount; $start++) {
if ($newurl != '') {
$newurl .= '.com/';
}
$newurl .= $url[$start];
}
$url = explode('/',$newurl);
$urlcount = explode('?',end($url));
$url[count($url) - 1] = $urlcount[0];
$urlcount = count($url);
By using the code above, all the subpage will be store in the $url.
https://stackoverflow.com/questions/ask
$url[0] = 'questions'
$url[1] = 'ask'
Just want to ask, is this good way, or there are others better way?
First prepending SERVER_NAME to the REQUEST_URI, and then trying to split it off, is pointless. This should be a simpler solution:
# first, split off the query string, if any:
list( $path ) = explode( '?', $_SERVER['REQUEST_URI'], 2 );
# then just split the URL path into its components:
$url = explode( '/', ltrim( $path, '/' ) );
The ltrim removes any leading slashes from the path, so that $url[0] won't be empty.
Note that there might still be an empty element at the end of the $url array, if the path ends in a slash. You could get rid of it by using trim instead of ltrim, but you may not want to, since the trailing slash is significant for things like resolving relative URLs.
Related
I'm wanting to strip out everything from a URL but the domain. So http://i.imgur.com/rA81kQf.jpg becomes imgur.com.
$url = 'http://i.imgur.com/rA81kQf.jpg';
$parsedurl = parse_url($url);
$parsedurl = preg_replace('#^www\.(.+\.)#i', '$1', $parsedurl['host']);
// now if a dot exists, grab everything after it. This removes any potential subdomain
$parsedurl = preg_replace("/^(.*?)\.(.*)$/","$2",$parsedurl);
The above works but I feel like I should only being one preg_replace for this. Any idea how I may combine the two?
You can use parse_url() to get desired output like this,
$url = "http://i.imgur.com/rA81kQf.jpg";
$parseData = parse_url($url);
$domain = preg_replace('/^www\./', '', $parseData['host']);
$array = explode(".", $domain);
echo (array_key_exists(count($array) - 2, $array) ? $array[count($array) - 2] : "") . "." . $array[count($array) - 1];
which prints
imgur.com
Lets say my URL is:
http://www.example.com/news/media-centre/news/17/an-example-news-post/?foo=bar
I want to in PHP remove the last directory in the URL so I get:
http://www.example.com/news/media-centre/news/17/?foo=bar
How do I do this while making sure I maintain any other URL parameters?
I've tried using this:
$url = parse_url( $url );
$url['path'] = str_replace( strrchr($url['path'], "/"), "", $url['path'] );
But the replace would cause issues if the last directory is also somewhere else in the path too.
Not to mention stitching the URL back together seems like a long way round...
$url = "http://www.example.com/news/media-centre/news/17/an-example-news-post/?foo=bar";
$info = parse_url($url);
$info["path"]=dirname($info["path"]);
$new_url = $info["scheme"]."://".$info["host"].$info["path"];
if(!empty($info["query"])) $new_url .= "?".$info["query"];
if(!empty($info["fragment"])) $new_url .= "#".$info["fragment"];
I have some php which prints a url. Can I contain this with PHP to leave off the last segment?
So this:
www.mysite.com/name/james
would become this:
www.mysite.com/name
I'm using expression engine so the code is just {site_url}.
$url = (substr($url, -1) == '/') ? substr($url, 0, -1) : $url; // remove trailing slash if present
$urlparts = explode('/', $url); // explode on slash
array_pop($urlparts); // remove last part
$url = implode($urlparts, '/'); // put it back together
I need to get the very last word from an URL. So for example I have the following URL:
http://www.mydomainname.com/m/groups/view/test
I need to get with PHP only "test", nothing else. I tried to use something like this:
$words = explode(' ', $_SERVER['REQUEST_URI']);
$showword = trim($words[count($words) - 1], '/');
echo $showword;
It does not work for me. Can you help me please?
Thank you so much!!
Use basename with parse_url:
echo basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
by using regex:
preg_match("/[^\/]+$/", "http://www.mydomainname.com/m/groups/view/test", $matches);
$last_word = $matches[0]; // test
I used this:
$lastWord = substr($url, strrpos($url, '/') + 1);
Thnx to: https://stackoverflow.com/a/1361752/4189000
You can use explode but you need to use / as delimiter:
$segments = explode('/', $_SERVER['REQUEST_URI']);
Note that $_SERVER['REQUEST_URI'] can contain the query string if the current URI has one. In that case you should use parse_url before to only get the path:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
And to take trailing slashes into account, you can use rtrim to remove them before splitting it into its segments using explode. So:
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', rtrim($_SERVER['REQUEST_URI_PATH'], '/'));
To do that you can use explode on your REQUEST_URI.I've made some simple function:
function getLast()
{
$requestUri = $_SERVER['REQUEST_URI'];
# Remove query string
$requestUri = trim(strstr($requestUri, '?', true), '/');
# Note that delimeter is '/'
$arr = explode('/', $requestUri);
$count = count($arr);
return $arr[$count - 1];
}
echo getLast();
If you don't mind a query string being included when present, then just use basename. You don't need to use parse_url as well.
$url = 'http://www.mydomainname.com/m/groups/view/test';
$showword = basename($url);
echo htmlspecialchars($showword);
When the $url variable is generated from user input or from $_SERVER['REQUEST_URI']; before using echo use htmlspecialchars or htmlentities, otherwise users could add html tags or run JavaScript on the webpage.
use preg*
if ( preg_match( "~/(.*?)$~msi", $_SERVER[ "REQUEST_URI" ], $vv ))
echo $vv[1];
else
echo "Nothing here";
this was just idea of code. It can be rewriten in function.
PS. Generally i use mod_rewrite to handle this... ans process in php the $_GET variables.
And this is good practice, IMHO
ex: $url = 'http://www.youtube.com/embed/ADU0QnQ4eDs';
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url_path = parse_url($url, PHP_URL_PATH);
$basename = pathinfo($url_path, PATHINFO_BASENAME);
// **output**: $basename is "ADU0QnQ4eDs"
complete solution you will get in the below link. i just found to Get last word from URL after a slash in PHP.
Get last parameter of url in php
Take this domain:
http://www.?.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html
How could i use PHP to find the everything between the first and second slash regardless of whether it changes or no?
Ie. elderly-care-advocacy
Any helo would be greatly appreciated.
//strip the "http://" part. Note: Doesn't work for HTTPS!
$url = substr("http://www.example.com/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html", 7);
// split the URL in parts
$parts = explode("/", $url);
// The second part (offset 1) is the part we look for
if (count($parts) > 1) {
$segment = $parts[1];
} else {
throw new Exception("Full URLs please!");
}
$url = "http://www.example.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html";
$parts = parse_url($url);
$host = $parts['host'];
$path = $parts['path'];
$items = preg_split('/\//',$path,null,PREG_SPLIT_NO_EMPTY);
$firstPart = $items[0];
off the top of my head:
$url = http://www.example.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html
$urlParts = parse_url($url); // An array
$target_string = $urlParts[1] // 'elderly-care-advocacy'
Cheers
explode('/', $a);
All you should do, is parse url first, and then explode string and get first part. With some sanity checks that would lok like following:
$url = 'http://www.?.co.uk/elderly-care-advocacy/mental-capacity-act-advance-medical-directive.html';
$url_parts = parse_url($url);
if (isset($url_parts['path'])) {
$path_components = explode('/', $ul_parts['path']);
if (count($path_components) > 1) {
// All is OK. Path's first component is in $path_components[0]
} else {
// Throw an error, since there is no directory specified in path
// Or you could assume, that $path_components[0] is the actual path
}
} else {
// Throw an error, since there is no path component was found
}
I was surprised too, but this works.
$url='http://www.?.co.uk/elderly-care-advocacy/...'
$result=explode('/',$url)[3];
I think a Regular Expression should be fine for that.
Try using e.g.: /[^/]+/ that should give you /elderly-care-advocacy/ as the second index of an array in your example.
(The first string is /www.?.com/)
Parse_URL is your best option. It breaks the URL string down into components, which you can selectively query.
This function could be used:
function extract_domain($url){
if ($url_parts = parse_url($url), $prefix = 'www.', $suffix = '.co.uk') {
$host = $url_parts['host'];
$host = str_replace($prefix,'',$host);
$host = str_replace($suffix,'',$host);
return $host;
}
return false;
}
$host_component = extract_domain($_SERVER['REQUEST_URI']);