Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

security - 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_

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...