Path traversal prevention in PHP As with other inputs, file paths should be validated before thay could be passed to operating system interfaces. Since chroot(2) has a bit more than some portability issues, oftentimes it is desireable to use a path-validating function. 

The general idea, is that no path component should be .., and that if we chdir(2) to the path in question, we must make sure it doesn't begin with a &lt;slash&gt; ("/"). 

Also, for some application, files or directories with certain prefix (say &lt;dot&gt; (".")) should be outright rejected. 

Here's my example of PHP code that does path-validation. I'd like some expertized opinion from the members of the site. 

&lt;?php
 function antitraversal($s)
 {
   if( !is_string($s) ) die("Invalid argument: $s");

   $components = explode("/", $s);
   foreach($components as $component) {
     if( $component[0] === "." ) die("Invalid argument: $s");
   }

   if( $s[0] === "/" ) { return ".$s"; } else { return $s; };
 }


For simplicity, we'll assume the script runs in Unix-like environments.
Security

This can be bypassed by /\... 

You are currently checking if / is followed by . and reject the input if that is the case. But as you can see, it is possible to traverse with different sequences (null bytes would be another candidate for bypasses).

It would be a bit more secure if you checked for ... To really prevent directory traversal, you should check if the resolved path is inside the desired directory.

Misc


dieing inside a function is always a bad idea, as you have no more control over the code. The calling function can't recover, the function can't be reused, etc.
You are vulnerable to XSS.
I would put each statement on it's own line (e.g. if/else on the same line is a bit difficult to read).