Question: I have a base path /whatever/foo/

and
`$_GET['path']` should be relative to it.

However how do I accomplish this (reading the directory), without allowing directory traversal?

eg.

```
/\.\.|\.\./

```

Will not filter properly.

Answer: 
I have written a function to check for traversal:

```
function isTraversal($basePath, $fileName)
{
    if (strpos(urldecode($fileName), '..') !== false)
        return true;
    $realBase = realpath($basePath);
    $userPath = $basePath.$fileName;
    $realUserPath = realpath($userPath);
    while ($realUserPath === false)
    {
        $userPath = dirname($userPath);
        $realUserPath = realpath($userPath);
    }
    return strpos($realUserPath, $realBase) !== 0;
}

```

This line alone `if (strpos(urldecode($fileName), '..') !== false)` should be enough to prevent traversal, however, there are many different ways hackers can traverse directories so its better to make sure the user starts with the real base path.

Just checking the user starts with the real base path is not enough because a hacker could traverse to the current directory and discover the directory structure.

The `while` allows the code to work when $fileName does not exist.
I assume you mean without allowing **users** to traverse the directory yes?

If you are trying to stop your own PHP from traversing the directory you should just make the php work properly in the first place.

What you need to stop users is a modified .htaccess file...

```
Options -Indexes

```

(This all assumes you are talking about users)