How do I get the depth of a URL using PHP? - php

I'd like to echo the depth (or number of directories from my home) of my current page's URL using PHP. How would I do that?
For example, if I'm on mysite.com, the output displays "0", if I'm on mysite.com/recipes, the output displays "1", and if I'm on mysite.com/recipes/pies, the output displays "2", and so on.
How do I do that?
I tried simplifying it and doing this, but it's exporting as 0:
$folder_depth = substr_count($_SERVER["PHP_SELF"] , "/");
echo $folder_depth;

Just for fun, here is my cheap and cheezy solution using PHP's parse_url() and its PHP_URL_PATH return value along with a couple of other functions:
$url = 'http://universeofscifi.com/content/tagged/model/battlestar_galactica.html';
echo var_dump(parse_url($url, PHP_URL_PATH));
echo count(explode('/', (parse_url($url, PHP_URL_PATH)))) - 2;
This returns:
string(47) "/content/tagged/model/battlestar_galactica.html"
3
I subtract 2 from the count to discard the domain at the front and the file at the end, leaving only the directory depth count.

If you won't have a query string, you can explode on /. If you will have a query string, you need to remove that first, such as...
$url = preg_replace('/?.*$/','',$url);
If you have http:// or https:// at the front of your URL, that can mess it up also. So remove it...
$url = preg_replace('~^https*://~','',$url);
Now, you only have the url as example.com/some/path/to/something. You can explode on / and get a count:
$a = explode('/',$url);
The size of $a will be 1 more than what you want. So, you need to subtract one:
$depth = sizeof($a)-1;
New problem... I just counted the file itself, such as example.com/links.html will come up as 1, not just 0. So, before the explode I need to get rid of the file name. But... how do I know if it is a file or a directory? That isn't built into the URL specification. For example, example.com/test could be a file or it could be a directory (and then it automatically goes to example.com/test/index.html). You need to assume what file extensions you will have and remove those files before you explode, such as:
$url = preg_replace('~/[^/]+.(html|php|gig|png|mp3)$~','',$url);

#kainaw, I like your answer! Thanks!
I took a spin on that. First, I noticed I was using the wrong PHP function to get the part of the URL I needed. Second, I needed to use #kaniaw's example and get the parts of the URL which I'm supposed to count, and ignore the others.
I also had to account for urls without content between the "/", so something like /word//// would still count as 1. Therefore, I only counted array elements after explode() which were not empty.
Here's my code:
$url = $_SERVER['REQUEST_URI'];
//echo "*".$_SERVER['REQUEST_URI']."*";
//$url = preg_replace('/?.*$/','',$url);
//$url = preg_replace('~^https*://~','',$url);
//$url = preg_replace('~/[^/]+.(html|php|gig|png|mp3)$~','',$url);
$a = explode('/',$url);
$depth =count(array_filter($a));
echo $depth;
I commented out some of those lines because I didn't seen them, but they were mentioned above.
Thanks!

Related

save the last part of url in variable

I want to get the last part of an url that looks like this:
http://localhost:8888/blog/public/index.php/categories/Horror
I've tried it with
$endOfUrl = end(explode('/',$url));
but the thing is I get a notice that "Only variables should be passed by reference"
I need this "Horror" to get it's ID in my database and get all the posts with this id, since I'm trying to code a blog to get experience with php.
Another question linked to this: Is it possible to make it dynamic so it can be used for all the other categories as well? Or do I have to do this for every single category?
I'm new to the world of php so I would really appreciate it if someone could help me on this.
Try like this way for end() but If I were you I will try basename() to get my job done.
<?php
$url = 'http://localhost:8888/blog/public/index.php/categories/Horror';
$exploded = explode('/',$url);
$endOfUrl = end($exploded);
echo $endOfUrl;
?>
Reason why it is not working on single line:
end() requires a reference, because it modifies the internal
representation of the array (i.e. it makes the current element pointer
point to the last element).The result of explode('.', $url) cannot be
turned into a reference and this is a restriction in the PHP language itself.
DEMO: https://3v4l.org/ttKui
Using basename(),
$url = 'http://localhost:8888/blog/public/index.php/categories/Horror';
echo basename($url);
DEMO: https://3v4l.org/pt2cQ

Make the URL path count backwards

I learned how to parse an URL and return me a specific part of it.
For now, I'm currently working in a localhost server, which contains a long basename:
localhost/mydocs/project/wordpress/mexico/cancun
If I want to get the word mexico I would have to count 4 until there.
$url = localhost/mydocs/project/wordpress/mexico/cancun
$parse = parse_url($url);
$path = explode('/', $parse[path]);
echo = $path[4]
Even though it works fine for localhost, when uploading in the server, the basename get shorter and the number 4 can not reach mexico, because the URL becomes:
example.com/mexico/cancun
I'd like to know if there is a global solution for it. I thought about counting backwards, like using -2, so it would start counting from the word "cancun", but I don't know whether is possible or not!
Thank you!
use $path[count($path)-2] -2 being the configurable part.
Note this will only work for numeric indices, like for your case.

Is it possible to get information from this type of url: website.com/hello/richard

For example, if there is a url like www.website.com/hello/richard, would it be possible to echo hello and 100 separately onto my page.
eg:
hello how are you today richard
You can get the data from $_SERVER['REQUEST_URI'] and then do whatever you like with it.
Yes it would be. Try this:
$myURL = $_SERVER['REQUEST_URI'];
$myTokens = explode('/', $myURL);
echo $myTokens[1] . "blah" . $myTokens[2];
This code gets the current URL into the myURL variable, then it calls a function called explode which turns it into an array based on the position of the '\' character. Then it echos out certain elements of that array. If you play around with output using echo you will soon see for yourself what is going on.
Sure that's possible. You can get URL as a string using $_SERVER['request_uri]. Then you might want to use explode function to firm array of strings where delimiter is /. Then you may parse it. Or you can do this via .htaccess using rewrite rule

Check URL for a folder

How can I check the URL path for certain folders? I ask so that if we're in a certain folder, we can make a tab selected in the nav bar (just apply a style to that specific li).
So far I know
$pagePath = $_SERVER['REQUEST_URI'];
So I can get a return that says something like /music/song/120/ (or whatever it is). What kind of php function can I use that says
if $pagePath has "music", then do this. Meaning, if the path is /music/ or /music/song, I should be able to
I plan on using this multiple times,
if $pagePath has downloads do this
if $pathPath has band do this
and so on.
Any suggestions?
You could explode() the path on / and then use in_array() to check for existence.
However, this could yield problems with paths like /bands/something/music where the state would depend on whether you check for bands before music or vice versa. In that case you could explode() with $limit = 2 (to get only two parts, i.e., split on first / only) and compare your predefined path segments to the first part of the exploded path.
E.g.
$path = trim('/bands/something/music', '/');
$parts = explode('/', $path, 2); // ['bands', 'something/music']
switch ($parts[0]) {
case 'music':
// ...
case 'bands':
// ...
}
Try strpos()
e.g.
if(strpos($_SERVER['REQUEST_URI'],'music')>0)
{
# URL contains music
}
A quick way: you could use strpos: http://www.php.net/manual/en/function.strpos.php

How to get just last word for a variable in a PHP "$_SERVER['REQUEST_URI']" request?

I'm using WAMP and the root folder of my page is: http://localhost/projects/bp/
In a Worpress application and I want to give unique id's to the body tag of every Page. So I did the following:
<?php
$page = $_SERVER['REQUEST_URI'];
$page = str_replace("/","",$page);
$page = str_replace(".php","",$page);
$page = str_replace("?s=","",$page);
$page = $page ? $page : 'default'
?>
<body id="<?php echo $page ?>">
When I clicked the Aboutpage the URL change to the following: http://localhost/projects/bp/about and $page showed the following value:projectsbpabout
What can I do so that $page just show the last word of the URL. In this case, about, I don't want the projectsbp part)?
Do I have to change something in the Wordpress routing?
I would use PHP's built-in path parsing functions to do this.
Use parse_url() to cut off the query and get only the path part:
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
(parse_url is used to parse full URLs but should work fine for this. The second parameter is available since PHP 5.1.2.)
Then use basename() to extract the file name:
$pagename = basename($path, ".php"); // Will remove `.php` suffix
Additional thougths
Depending on how your site is structured, this method will not necessarily make for unique IDs. What if about is a sub-page in /bp and /bc? (If that is possible in Wordpress.) You would have two different pages with the same ID. In that case, you may want to use the full path as an identifier, converting slashes into underlines:
<body id="projects_bp_about">
also from own experience, I recommend using classes for this to avoid ID collisions if a page is named like an already existing elements on the page!
<body class="projects_bp_about">
As / is your separator, first create an array of all the loose parts:
$parts = explode('/', $_SERVER['REQUEST_URI']);
Now you just want the last element:
$last_part = end($parts);
of course this can also be done in one go:
$last_part = end(explode('/', $_SERVER['REQUEST_URI']));
to get only the last bit you can use
$page = array_pop(explode('/', $_SERVER['REQUEST_URI']));
explode the string by '/' and get the last piece.
instead of using str_replace you can use..
$pageArr = explode("/",$page);
it will give you array with three values you can capture the last one as about

Categories