我有一个父函数,该函数传递了一个名为的变量$scriptName
。根据中存储的内容$scriptName
,我想调用相应的脚本。
我有一个名为childOneScript.php的文件
如果可以$scriptName=="childOne"
,我怎么打电话childOneScript.php
?
你可以正常使用 require
require_once $scriptName . 'Script.php';
但是请记住,如果脚本不存在,PHP将引发致命错误,因此您应检查脚本确实存在。
/**
Assumes that $name does not contain the PHP extension and
this function works with relative paths.
If the file does not exist, returns false, true otherwise
*/
function loadScript($name) {
$name = $name . '.php';
if (!file_exists($name) || !is_readable($name)) {
// raise an error, throw an exception, return false, it's up to you
return false;
}
require_once $name;
return true;
}
$loaded = loadScript('childOneScript');
或者,您可以使用include
,PHP仅在找不到脚本时才会发出警告。
上述功能存在一些安全问题。例如,如果允许用户定义$scriptName
攻击者的值,则攻击者可以使用它来读取Web服务器用户可读的任何文件。
这是将可动态加载的文件数限制为仅需要以这种方式加载的文件的替代方法。
class ScriptLoader {
private static $whiteList = array(
// these files must exist and be readable and should only include
// the files that need to be loaded dynamically by your application
'/path/to/script1.php' => 1,
'/path/to/script2.php' => 1,
);
private function __construct() {}
public static function load($name) {
$name = $name . '.php';
if (isset(self::$whiteList[$name])) {
require_once $name;
return true;
}
// the file is not allowed to be loaded dynamically
return false;
}
}
// You can call the static method like so.
ScriptLoader::load('/path/to/script1'); // returns true
ScriptLoader::load('/path/to/script2'); // returns true
ScriptLoader::load('/some/other/phpfile'); // returns false
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句