我有一个父函数,它传递了一个名为$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
您可以简单地执行:
if ($scriptName=="childOne"){
require_once(childOneScript.php);
}
require_once语句将检查文件是否已包含,如果已包含,则不再包含(要求)该文件。
Readup:require_oce()|PHP
只需在If条件中使用include语句。
if $scriptName == "childOne" {
include childOneScript.php;
}
您可以在PHP
中使用include或require方法
<?php
function loadScript($scriptName) {
if ($scriptName=="childOne") {
include("childOneScript.php");
}
}
?>
请记住,所包含的脚本包含在您加载它的位置。因此它位于loadScript
函数内部。这意味着您不能访问其范围之外的内容。