Re: Comparing strings... need advice. :)
| From: | Ivo F.A.C. Fokkema | Date: | Tue, 29 Aug 2006 07:07:59 +0000 |
| Subject: | Re: Comparing strings... need advice. :) | ||
| References: | 1 2 3 4 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-241172@lists.php.net to get a copy of this message | ||
On Mon, 28 Aug 2006 19:39:49 -0400, Robert Cummings wrote:
> On Mon, 2006-08-28 at 16:50 +0200, Ivo F.A.C. Fokkema wrote:
>> On Mon, 28 Aug 2006 09:47:02 +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);
>> >
>>
>> Personally, this seems simpler to me:
>>
>> $valid = (dirname($haystack) == $needle);
>>
>> But the way the above folders are presented, it should become
>>
>> $valid = (dirname($haystack) == rtrim($needle, '/'));
>>
>> less simple already... Possibly, this is not the best solution for some
>> reason I don't know. If so, I would like to know :)
>
> The above technique doesn't allow for sub-directories. It only allows
> for files within the needle directory.
Ah, thanks. Misunderstood the question, then. Thought just checking if
it's a file in that directory was what's needed.