doujiu1447 2014-02-18 06:02
浏览 34
已采纳

使用PHP使用带有$ _GET的preg_match和目录名称时出现问题

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>
";

}
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>
";

}
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.

  • 写回答

1条回答 默认 最新

  • douyu0845 2014-02-18 06:10
    关注

    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!');
    }
    

    Learning Resources:

    Essential Guide To Regular Expressions Tools, Tutorials and Resources

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路