PHP:如果使用preg_replace仅允许以下-A-Za-z0-9_,则包含基于GET变量的文件是否安全? [英] PHP: Is it safe to include a file based on a GET variable, if you use preg_replace to only allow the following -A-Za-z0-9_

查看:227
本文介绍了PHP:如果使用preg_replace仅允许以下-A-Za-z0-9_,则包含基于GET变量的文件是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这有多安全?

   if (isset($_GET["var"]) && file_exists("path/".$_GET["var"].".php")) { 
        include("path/".$_GET["var"].".php");
    } else {  
        echo 'File Does Not Exist!';   
    }

我想知道是否需要对$ _GET ["var"]进行清理",而不是让它在尝试包含或不包含file_exists函数之前运行.这很危险吗?

+++ UPDATED +++

谢谢大家的回应!请参阅下面的更新...

function mrClean($var) {
$clean_var = (isset($var) && !empty($var)) ? $var : 'index';
$clean_var = preg_replace('/[^-A-Za-z0-9_]/', '', $clean_var);
return $clean_var;
}

$var = mrClean($_GET["var"]);

if (file_exists("path/".$var.".php")) { 
  include("path/".$var.".php");
} else {  
  echo 'File Does Not Exist!';   
}

当我调用mrClean替换所有内容时,除了以下内容:

通过 preg_replace

-A-Z a-z 0-9 _

...现在将其视为安全的吗?有什么可以添加的以使其更安全吗?

我将按照建议实施白名单...但是还有其他什么?

谢谢!

-安德鲁

解决方案

是的,问题更新中的正则表达式替换是SAFE.但是请注意,任何包含都是危险的,并且如果您允许用户包含一些不安全的脚本,则会如此.

How safe is this?

   if (isset($_GET["var"]) && file_exists("path/".$_GET["var"].".php")) { 
        include("path/".$_GET["var"].".php");
    } else {  
        echo 'File Does Not Exist!';   
    }

I'm wondering if $_GET["var"] needs to be "sanitized" opposed to just letting it run against the file_exists function before trying to include it or not. Is this dangerous?

+++UPDATED+++

Thank you all for your responses! Please see updated below...

function mrClean($var) {
$clean_var = (isset($var) && !empty($var)) ? $var : 'index';
$clean_var = preg_replace('/[^-A-Za-z0-9_]/', '', $clean_var);
return $clean_var;
}

$var = mrClean($_GET["var"]);

if (file_exists("path/".$var.".php")) { 
  include("path/".$var.".php");
} else {  
  echo 'File Does Not Exist!';   
}

When I call on mrClean to replace all, but the following:

- A-Z a-z 0-9 _ via preg_replace

...will this now be considered safe? Is there anything that can be added to make this any safer?

I will implement a whitelist as suggested... but anything else?

Thank you!!

-Andrew

解决方案

Yes, the regex replace within your question update is SAFE. But be aware of that ANY include is dangerous and if you will allow the user to include some unsafe script.

这篇关于PHP:如果使用preg_replace仅允许以下-A-Za-z0-9_,则包含基于GET变量的文件是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆