On Mon, 2006-08-28 at 09:47 +0100, Stut wrote: > Micky Hulse wrote: > > I am looking for the most secure/efficient way to compare these two > > strings: > > > > /folder1/folder2/folder3/folder4/ > > /folder1/folder2/folder3/folder4/file.php > > > > Basically I am trying to setup as many security features as possible for > > a simplistic (home-grown/hand-coded) CMS... > > > > This appears to work: > > > > $haystack = '/folder1/folder2/folder3/folder4/someFileName.php'; > > $needle = '/folder1/folder2/folder3/folder4/'; > > if(substr_count($haystack, $needle) === 1) echo "yea"; > > > > Before making changes to "someFileName.php" I want to make sure it is > > within the allowed path ($needle). > > First of all make sure you are sending both strings through realpath > (http://php.net/realpath) to remove any symbolic links and relative > references. Then you can compare the two strings. The way you're doing > it will work but it's probably not very efficient. This is what I use... > > $valid = (strcmp($needle, substr($haystack, 0, strlen($needle))) == 0); <?php function isAllowedPath( $needle, $haystack ) { $needle = realpath( $needle ).'/'; $haystack = realpath( $haystack ); return (strpos( $haystack, $needle ) === 0); } ?> It is VERY important that you append the trailing slash onto the needle path returned by realpath otherwise it will match more than you expect. Stut didn't point that out so I thought I'd make sure you caught it. Also I'm not sure why Stut used 3 function calls when one suffices >:) Cheers, Rob. -- .------------------------------------------------------------. | InterJinn Application Framework - http://www.interjinn.com | :------------------------------------------------------------: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `------------------------------------------------------------' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php