RE: validating directory and file name with preg_match

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



> -----Original Message-----
> From: Frank Stanovcak [mailto:blindspotpro@xxxxxxxxxxx]
> Sent: Wednesday, January 28, 2009 11:08 AM
> To: php-general@xxxxxxxxxxxxx
> Subject:  validating directory and file name with preg_match
> 
> I'm limiting access to certain proceedures based on the file trying to
> use
> them, and the directory they are located in on my server.  Right now I
> am
> using two preg_match statments as you will see.  What I want to know
is
> this.  Is there a way to write a single regex for this that will
supply
> the
> file name as a match, and only return if the directory is valid?
> 
> ------------
> //make sure we are calling from the propper directory, and get the
file
> name
> that included to determine
> //database access needs
>
preg_match('#^C:\\\\Inetpub\\\\wwwroot\\\\folder\\\\(entry|edit)\\\\(\w
> *\\.(php|pdf))#i',
> $included_files[0], $check1);
>
preg_match('#^C:\\\\Inetpub\\\\wwwroot\\\\folder\\\\(\w*\\.(php|pdf))#i
> ',
> $included_files[0], $check2);
> if(isset($check1)){
>  if(is_array($check1)){
>   $matches[4] = $check1[2];
>  };
>  unset($check1);
> };
> if(isset($check2)){
>  if(is_array($check2)){
>   $matches[4] = $check2[1];
>  };
>  unset($check2);
> };
> if(isset($matches[4]){
> more code here
> };

I don't see why you're double-escaping the backslashes like that. If you
want a period, \. will do it for you. \\. Will match a backslash and
then any character (or delimiter).

As for failing if the directory isn't valid, read up on regex
look-arounds [1]. You could do a look-ahead to ensure that the directory
matches before continuing with the file portion of the pattern.

But, seriously... why are you double-escaping? Why not just C:\\Inetpub
instead of C:\\\\Inetpub? I would think that C:\\\\Inetpub would turn
into C:\\Inetpub, which is not a valid FAT/NTFS/etc. locator.

Try this:

/^c:\\inetpub\\wwwroot\\folder\\(?=entry|edit)\\(\w+\.(?:php|pdf))$/i

The (?=entry|edit) group is the look-ahead. If folder\\ isn't followed
by entry or edit, the look-ahead fails. The (?:php|pdf) group uses the
?: syntax to tell the regex engine not to save this capture group. You
could just as easily remove the ?: and ignore the extra capture in your
code (as you have done).

	1. http://www.regular-expressions.info/lookaround.html 

HTH,


// Todd

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux