Check URL for a folder - php

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

Related

php __FILE__ inside includes?

I have (maybe) an unusual issue with using __FILE__ in a file within a file.
I created a snippet of code (in the php 5 my server mandates) to take elements of the current filename and put it into a variable to use later. After some headache, I got it working totally fine. However, I realized I didn't want to have to write it every time and realized "oh no, if I include this it's only going to work on the literal filename of the include". If I wanted to grab the filename of the page the user is looking at, as opposed to the literal name of the included file, what's the best approach? Grab the URL from the address bar? Use a different magic variable?
EDIT1: Example
I probably should have provided an example in the first draft, pfft. Say I have numbered files, and the header where the include takes place in is 01header.php, but the file it's displayed in is Article0018.html. I used:
$bn = (int) filter_var(__FILE__, FILTER_SANITIZE_NUMBER_INT);
…to get the article number, but realized it would get the 1 in the header instead.
EDIT2: Temporary Solution
I've """solved""" the issue by creating a function to get the URL / URI and putting it into the variable $infile, and replaced all former appearances of __FILE__ with $infile, like so:
function getAddress() {
$protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
return $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];}
$infile = urlencode(getAddress());
$bn = (int) filter_var($infile, FILTER_SANITIZE_NUMBER_INT);
echo "$bn";
So if the file the user is looking at is called "005-extremelynormalfile.html", I can display the number 5 inside the page, e.g., to say it's article number five.
While it's not as bad as I initially thought based on your description your code is still very fragile, and really only works by accident. If you have any other digits or hyphens it's going to go wrong, as below.
$infile = 'https://example-123.com/foo/42/bar/005-extremelynormalfile.html?x=8&y=9';
var_dump(
filter_var($infile, FILTER_SANITIZE_NUMBER_INT),
(int)filter_var($infile, FILTER_SANITIZE_NUMBER_INT)
);
Output:
string(12) "-12342005-89"
int(-12342005)
Sanitize functions are a blunt instrument for destroying data, and should only ever be used as a last resort when all other good sense has failed.
You need to use a proper parsing function to parse the url into its component parts, and then a simple regular expression to get what you want out of the filename.
function getIdFromURL($url) {
$url_parts = parse_url($url);
$path = $url_parts['path'];
$path_parts = explode('/', $path);
$filename = end($path_parts);
if( preg_match('/^(\d+)/', $filename, $matches) ) {
return (int)$matches[1];
}
return null;
}
var_dump(
getIdFromURL($infile)
);
Lastly, a lot of people are tempted to cram as much logic as possible into a regular expression. If I wanted to the above could be a single regex, but it would also be rigid, unreadable, and unmaintainable. Use regular expressions sparingly, as there's nearly always a parser/library that already does what you want, or the majority of it.
Quickly threw together a function that gets the url from the page as a variable, and replaced all occurrences of __FILE__ with that variable, and it worked correctly. Assuming the user cannot edit the URL / URI in any way, this should work well enough.

How do I get the depth of a URL using 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!

using substring to add word to string

Not sure if the title for this is correct but here's my problem:
I have a table that hold image's url like so:
img/folder/imagename.jpg
Now I've created a thumbnail for each image in each folder, so if I want to display them I do a loop in my table and return all the url's but I need to add the word "thumbs" after "folder/" and before the "imagename.jpg"...Now because obviously the "folder" and "imagename" names differ in length then I can't do a count..the only thing I can figure is to look up that last "/" character and insert there and add on the "imagename.jpg" after it so end result would look like:
img/folder/thumbs/imagename.jpg
Just replace the path with a "deeper" path:
$path = str_replace('img/folder/', 'img/folder/thumbs/', $path);
There are lots of other ways to do this, but IMHO this one is perfectly clear on what it does. Theoretically it won't work universally (if your path contains multiple occurreces of img/folder/ for some reason), but let's just not go there.
you can also
$pathparts = explode("/",$path);
and then use $pathparts array to construct your path again. You would use it in cases you want to have more control over manipulating paths, but in heavy loads it's not very efficient.
echo $pathparts[0]."/".$pathparts[1]."/thumbs/".$pathparts[2];
//adition
And why not to update your database and script only save imagename.jpg
and then in the beginning of calling script define
define("IMGPATH", "img/folder/");
define("THUMBPATH", "img/folder/thumbs/");
and then call it
<?= IMGPATH."imagename.jpg" ?>
<?= THUMBPATH."imagename.jpg" ?>

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

How to extract substrings with PHP

PHP beginner's question.
I need to keep image paths as following in the database for the admin backend.
../../../../assets/images/subfolder/myimage.jpg
However I need image paths as follows for the front-end.
assets/images/subfolder/myimage.jpg
What is the best way to change this by PHP?
I thought about substr(), but I am wondering if there is better ways.
Thanks in advance.
you should save your image path in an application variable and can access from both admin and frontend
If ../../../../ is fixed, then substr will work. If not, try something like this:
newpath=substr(strpos(path, "assets"));
It might seem like an odd choice at first but you could use ltrim. In the following example, all ../'s will be removed from the beginning of $path.
The dots in the second argument have to be escaped because PHP would treat them as a range otherwise.
$path = ltrim('../../../../assets/images/subfolder/myimage.jpg', '\\.\\./');
$path will then be:
assets/images/subfolder/myimage.jpg
I suggest this
$path = "../../../../assets/images/subfolder/myimage.jpg";
$root = "../../../../";
$root_len = strlen($root);
if(substr($path, 0, $root_len) == $root){
echo substr($path, $root_len);
} else {
//not comparable
}
In this way you have a sort of control on which directory to consider as root for your images

Categories