Reputation: 222
I want to remove all dot dot slashes in the URL string so user doesn't have access to parent level directory. What I could have is ../../../file
, is the below approach safe to use?
$str = '../../../file';
$str = str_replace('..','', ltrim($str,'/'));
EDIT: Thanks for your suggestions and answers, but I also like to know why NOT to use this code? Is it not safe enough? Can it be exploited?
Upvotes: 0
Views: 2152
Reputation: 165
We can also do using multiple character select :
echo str_replace(array('..', '/'), ' ', $string);
Upvotes: 0
Reputation: 150
I'm not clear with your question, I suspect you need to rewrite your URLs. if it so you can rewrite it by using .htaccess file
RewriteEngine On
RewriteRule ^$ /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /$1
Or you just want to remove sub-folders from $str alone you just use the below code
$str = preg_replace('/..\//', '', $str);
or
$str = str_replace('../','', $str);
Upvotes: 0
Reputation: 284
You can use preg_replace like this:
$string = '../../../file';
echo preg_replace("/(\.\.\/)/","", $string);
Upvotes: 2
Reputation: 452
$str = '../../../file';
$str = str_replace('../','', $str);
echo $str;
Upvotes: 1