I’m using the code below to automatically load and declare classes so that I only need to put class files in a folder named classes. The part in spl_autoload_regsister() may seem to be unnecessary for you but it is needed to work as a WordPress plugin without errors.
It uses eval()
and I’ve seen so many web pages talking about using eval()
is bad and can create a security hole. So how could this be dangerous?
$strDirPath = dirname(__FILE__) . '\classes';
$arrClassFiles = array_map(create_function( '$a', 'return basename($a, ".php");' ), glob($strDirPath . '*.php'));
spl_autoload_register(
create_function('$class_name', '
global $arrClassFiles, $strDirPath;
if (in_array($class_name, $arrClassFiles))
include($strDirPath . $class_name . ".php");' )
);
foreach ($arrClassFiles as $strClassName) {
$strClassName_alpha = $strClassName . "_Alpha";
eval("class $strClassName_alpha extends $strClassName {};");
}
print_r(get_declared_classes());
Maybe, somebody can put a file name of php code in the folder? But I don’t see it can compromise the system.
If they can name a class file something like
randomclass {}; echo $db_password;//.php
, then you could have a code execution attack.I’m pretty sure that’s not a valid file name, but there are people far wilier than me at crafting valid malicious inputs.
It’s just usually not an attack surface you need to open yourself up to, given that it’s practically always possible to avoid with better code structure.
If an error condition is handled, I don’t see a problem here.
Just be sure that if someone tries to call a different class that does exist (i.e. code that would be valid here, but that you wouldn’t want your hacker to run directly because it would bypass a restriction on your system), that it won’t be a security problem – or that it wouldn’t be possible to run that class at all from this context.
Just in case, deny any attempts to run code with the words “class,” or other keywords, or any built in class names, or built in function names, other builtins, etc. and you should be fine, but even that probably isn’t necessary in your particular case here because would probably result in an error.