PHP regular expression to match file path

Can someone please help me with this preg_match

 if (preg_match('~[^A-Za-z0-9_\./\]~', $filepath)) // Show Error message. 

I need to map a possible file path. So I need to check for double slashes, etc. Valid file path lines should only look like this:

 mydir/aFile.php 

or

 mydir/another_dir/anyfile.js 

So, you also need to check the slash at the beginning of this line. Please, help.

Thanks:)

EDIT : Also guys, this path is read from a text file. This is not a file path on the system. Therefore, I hope it should support all systems in this case.

RE-EDIT : Sorry, but the line might also look like this: myfile.php or myfile.js , or myfile.anything

How to allow such lines? I apologize for not being too specific about this ...

+7
php regex preg-match
source share
2 answers

You can do:

 if(preg_match('#^(\w+/){1,2}\w+\.\w+$#',$path)) { // valid path. }else{ // invalid path } 
+10
source share

Note that there are many types of possible file paths. For example:

  • "./"
  • "../"
  • "........" (yes, it could be a file name)
  • "File / file.txt"
  • File / File
  • "file.txt"
  • "File /../.// file / file / file"
  • "/file/.././/file/file/.file" (UNIX)
  • "C: \ Windows \" (Windows)
  • "C: \ Windows \ asd / asd" (Windows php accepts this)
  • "File /../.// file / file / file! @ # $"
  • "File /../.// file / file / file! @ #. Php.php.php.pdf.php"

All of these file paths are valid. I can't think of a simple regex that can make it perfect.

Suppose this is just a UNIX path, this is what I think should work in most cases:

 preg_match('/^[^*?"<>|:]*$/',$path) 

It checks the entire string for ^, *,?, ", <,>, | ,:: (removes this for windows). These are all characters that do not allow you to specify the file name with / and.

If these are windows, you should replace the path \ with /, and then explode it and check if it is absolute. Here is one example that works on both unix and windows.

 function is_filepath($path) { $path = trim($path); if(preg_match('/^[^*?"<>|:]*$/',$path)) return true; // good to go if(!defined('WINDOWS_SERVER')) { $tmp = dirname(__FILE__); if (strpos($tmp, '/', 0)!==false) define('WINDOWS_SERVER', false); else define('WINDOWS_SERVER', true); } /*first, we need to check if the system is windows*/ if(WINDOWS_SERVER) { if(strpos($path, ":") == 1 && preg_match('/[a-zA-Z]/', $path[0])) // check if it something like C:\ { $tmp = substr($path,2); $bool = preg_match('/^[^*?"<>|:]*$/',$tmp); return ($bool == 1); // so that it will return only true and false } return false; } //else // else is not needed return false; // that t } 
+12
source share

All Articles