In PHP, is there a function that can perform logic similar to realpath() but on files that may not exist in the filesystem? Obviously it would not be able to resolve links etc, but my goal is to see if a path provided by a user is in a certain directory (or a sub-directory of that directory) without having to account for /.././path types of issues on my own. Calling realpath would be perfect if it did not return false when the file does not exist.
Asked
Active
Viewed 1,365 times
2
-
1If it shouldn't return false, what should it return? – Andreas Stokholm Feb 21 '12 at 21:19
-
1"users" providing paths on your server sound like a bad idea to start with. – Feb 21 '12 at 21:20
-
maybe http://www.php.net/manual/en/function.pathinfo.php will help – Kuba Feb 21 '12 at 21:23
-
You could always make yourself a function using [dir](http://php.net/manual/en/language.constants.predefined.php). – Marcin Szulc Feb 21 '12 at 21:26
-
Ideally, it could take something like "/var/www/foo/../bar" and return "/var/www/bar" even if that path does not exist (there is already another built in PHP function that can tell me if a file exists or not, so I don't really need this one to do it too) – jmkelm08 Feb 21 '12 at 21:40
-
if it returns false, try to open it for writing – miki Feb 21 '12 at 22:06
2 Answers
1
If your concern is only files try:
function unrealpath($path){
$rp = realpath(dirname($path));
if( false === $rp )
return false;
return $rp.basename($path);
}
If you have concerns about the directories existing or not as well this won't work.

scragar
- 6,764
- 28
- 36
0
If you only need to remove the /../ a self written function wouldn't be that difficult. Just split the string onto a array, iterate over the array and insert the values in a new one. If you hit a .. remove the last element inserted in the new array. Then merge the second array back into a string.

Johni
- 2,933
- 4
- 28
- 47
-
I have hesitated to do this only because I have heard of hacks people have used where they did things like specify a multi-byte representation of the '.' character to get around people naively stripping the '.' character. Maybe I don't need to worry about these things in PHP? – jmkelm08 Feb 22 '12 at 04:09
-
Actually, i have no idea if php interprets those multibyte "." as directory up action. It's worth to try it yourself if this is the case. If i have the time i will try it too. – Johni Feb 25 '12 at 16:38