Reputation: 1628
I'm creating a very simple file browser, and am trying to limit the path to be /local/ANYTHING
, but NOT /local
it's self. (where ANYTHING can be any subfolder).
Currently I'm using:
$path = (strpos($path, '/local/') !== false) ? $path : "/local/ud";
But this accepts /local/
as the path. The aim is if its not /local/ANYTHING
then set it to /local/ud
.
I've tried to use preg_match()
and set it as /local/*
but again this allow access to /local
.
Is there any way to say the path can only be /local/ANYTHING
while excluding /local itself
?
Upvotes: 0
Views: 1881
Reputation: 78994
Why regex? There are path/directory tools:
if(dirname($path) == '/local' && basename($path) != 'local'){
// path is good
}
Or:
$path = (dirname($path) == '/local' && basename($path) != 'local') ? $path : '/local/ud';
Upvotes: 1
Reputation: 6702
You need delimiters surround your regexp pattern. Since there are slashes in your path string, another delimiter than the default /
is applicable, e.g.~
. The *
is a quantifier, not a wildcard. It matches 0 or more occurrences of the preceding character. A dot is a special symbol that matches any character. Brackets define a set of characters. A leading^
inverses the set, i.e. "not": [^abc]
means any character but a,b,c.
Since file names in many nowadays file systems can contain almost any character, we take the condition: "only one slash after local, accept any number of succeeding characters".
"~/local/[^/].*~u"
The modifier u
after the end delimiter makes the pattern UTF-8 compatible.
Upvotes: 0
Reputation: 7617
Using Regular expression should work for you. Here is one flavour of it:
<?php
$path = preg_match("&(\/local\/)(.+)&", $path)? $path : "/local/ud";
Upvotes: 1
Reputation: 23958
This forces at least one letter after /
preg_match("/\/local\/\w.*/", $input, $output);
http://www.phpliveregex.com/p/fB2
Edited to add \w to make sure you cant be at /local/
<- there is supposed to be a space after /
Maybe this is even better? "/\/local\/[\w|\d].*/"
One letter or digit then anything
Upvotes: 2