Reputation: 107
I have a script that uses $_GET to retrieve directory names and appends it to a URL to retrieve files in a folder outside the webroot.
Here is my current code:
<php
$getdir = $_GET['dir'];
$getdoctype = $_GET['doctype'];
$dir = "/var/www/uploads/$getdir/$getdoctype";
$subdir1 = scandir($dir); /* This function sorts dirs */
$list = array_diff($subdir1,array(".","..","index.php"));
echo "<ol>";
foreach ($list as $file)
{
if (!is_dir($file)) echo "<li><a href='https://example.ca/private/download_files.php?dir=$getdir&doctype=$getdoctype&filename=$file'>$file</a></li>\n";
}
echo "</ol>";
?>
I understand that using $_GET is very unsecure in this situation so I want to clean my $_GET variables with a preg_match function. I've been given this function from a user on this board and can't seem to get it to work.
Here is my code with the function:
<?php
$getdir = $_GET['dir'];
$getdoctype = $_GET['doctype'];
// CLEANING GET VARIABLES
if (!preg_match('/^[a-zA-Z0-9]+$/', $getdir) || !preg_match('/^[a-zA-Z0-9]+$/', $getdoctype)) {
die('Bad parameter!');
}
$dir = "/var/www/uploads/$getdir/$getdoctype";
$subdir1 = scandir($dir); /* This function sorts dirs */
$list = array_diff($subdir1,array(".","..","index.php"));
echo "<ol>";
foreach ($list as $file)
{
if (!is_dir($file)) echo "<li><a href='https://example.ca/private/download_files.php?dir=$getdir&doctype=$getdoctype&filename=$file'>$file</a></li>\n";
}
echo "</ol>";
?>
The get variables can contain spaces in the directory names. Also %20
is an http escape string that can also be accepted. I just don't want hackers getting into my server.
I will also accept alternatives to $_GET in this implementation if you guys have any.
Upvotes: 0
Views: 685
Reputation: 9782
Directory name should start with a-zA-z
according to regex and added space,_,-
also valid
////////////////////////////////////////////
// Explanation
// \s : new folder
// \_ : new_folder
// \- : new-folder
if ( !preg_match('/^[a-zA-Z]+[a-zA-Z0-9\s\_\-]+$/', urldecode($getdir)) ||
!preg_match('/^[a-zA-Z]+[a-zA-Z0-9\s\_\-]+$/', urldecode($getdoctype))) {
die('Bad parameter!');
}
Essential Guide To Regular Expressions Tools, Tutorials and Resources
Upvotes: 1