Search code examples
phpjavascriptdirectoryscandir

Covert ../ Into Real Directories PHP


I am making a small file browsing script using PHP and Javascript and I have come into a small issue. The current directory is stored as GET in the url as index.php?dir=/projects/jphp when it is in the base. I then store this in the variabe $scandir using:

$scandir = $_GET['dir'];

as the fiels are listed in a table so users can look thorugh them, folders are hyperlinked like this:

<td><a style="color: red;" href="edit.php?pid=<?php echo $project['id'] ?>&dir=<?php echo $scandir . "/" . $thisfile; ?>"><?php echo $thisfile; ?></a></td>

The variable $thisfile is populated using a foreach() loop that goes through every file in the directory.
As The user starts to browse the folders and files, the file address gets messy so, for example, after a minute of browsing the files, the $_GET['dir']; looks like

projects/jphp/js/../js/../../../projects/jphp

is there any way to keep the paths simple as the path above is the exact same as

projects/jphp

If you know how to covert the top into the bottom, that would be great, thanks! I might not have explained this well so let me know you I am not making sense.


Solution

  • The function realpath() does what you're looking for. If you're not getting any results, check your folder permissions:

    The running script must have executable permissions 
    on all directories in the hierarchy, otherwise 
    realpath() will return FALSE.