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

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

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试