Online
 
Thursday, 20 November 2008
 
 

PHP - Check for relative paths | Print |  E-Mail
 

Check for relative paths
When you need to allow the user to specify a filename in your application, you can use a combination of the realpath( ) and basename( ) functions to ensure that the filename is what it ought to be. The realpath( ) function resolves special markers such as "." and "..". After a call to realpath( ), the resulting path is a full path on which you can then use basename( ). The basename( ) function returns just the filename portion of the path.
Going back to our welcome message scenario, here's an example of realpath( ) and basename( ) in action:

$filename = $_POST['username'];
$vetted = basename(realpath($filename));
if ($filename !== $vetted) {
  die("$filename is not a good username");
}
In this case, we've resolved $filename to its full path and then extracted just the filename. If this value doesn't match the original value of $filename, we've got a bad filename that we don't want to use.
Once you have the completely bare filename, you can reconstruct what the file path ought to be, based on where legal files should go, and add a file extension based on the actual contents of the file:
include("/usr/local/lib/greetings/$filename");

This entry was posted on . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a comment.
Users' Comments (0)

Comment an article
  Name
  E-mail
   Title
Available characters: 4000
 Notify me of follow-up comments
This image contains a scrambled text, it is using a combination of colors, font size, background, angle in order to disallow computer to automate reading. You will have to reproduce it to post on my homepage
Enter what you see:

No comment posted

Jumbo Coklat
 
Top! Top!