有一种已知的方法可以包括文件并在加载时将其内容捕获到字符串中。
$string = get_include_contents('somefile.php');
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
https://www.php.net/manual/en/function.include.php
是否有一种方法来" include"内容加载从字符串而不是文件?
我的意思是这样:
$string = file_get_contents("file.php");
include_from_string($string);
如果要将字符串解析为PHP代码,就像加载了include()
的文件的内容一样,您需要的函数是eval()
。
请注意,与include()
加载的代码不同,由eval()
执行的代码自动启动以PHP模式开始,因此您无需(也不应该!)以<?php
前缀。如果您想模仿include()
恰好的行为,则可以将字符串前缀为eval()
ED,以离开?>
以离开PHP模式:
$string = file_get_contents( 'somefile.php' );
eval( '?>' . $string );
还请注意,eval()
是一个非常危险的功能!虽然在这种特定情况下,它不应该比include()
本身更具风险,但在任何可能包含不启动(或不充分消毒的)用户输入的字符串上使用eval()
极其危险的,可能会被攻击者利用以在系统上执行恶意代码,从而获得对其的控制。
这可能不是您要寻找的东西,但我得到了" 在上使用"。
只需使用tempnam()创建临时文件,然后将其包含在内,然后unlink()。
$path = "somefile.php";
$stringFile = file_get_contents($path);
$pathTmp = tempnam("tmp/", ""); // you pass directory in which you will store tmp files for me it's "tmp/"
$file = fopen($pathTmp, "w+");
fwrite($file,$widget);
fclose($file);
include $pathTmp; // include the file, and PHP will be automatically parsed
unlink($pathTmp); // delete file
这是错误的:
我不确定这是否是好的练习(但是黑客该死,很简单),因为没有人建议它,但是它比eval()更好,这基本上是" 代码危险"。
这是正确的:
@chris harrison评论说这是安全风险,它等于eval()。因此,您基本上可以这样做:
eval($string);
这是您的一个简单示例,如果您通过est eval()将这将在字符串变量中执行代码。
<?php
//here your PHP Code goes
$string = get_include_contents('somefile.php');
//evaluating the string this will work
eval($string); //output
这不等于使用Include。这是问题:eval()将提供的PHP获取,并在当前环境中执行它。因此,任何全球,函数,类,什么,什么都不是,您在eval()之前都定义了处理器。这一切都很好,返回后,原始(evel'd)字符串的唯一东西是任何回声(或等效)语句的结果。
这与包含不同。在那里,文件内容与您的源代码合并,并将其传递给eval()。非常非常不同。看到此的最简单方法是将字符串定义为'class fu {static函数bar(){echo" wow";}]'将其放入文件中,然后致电fu :: bar(),您将显示"哇"。在代码中的同一时刻,如果您进行eval('class fu ...')并从代码中调用fu :: bar(),您将获得"致命错误:致电私有方法fu :: bar(bar()从上下文..."
但是,只要您不需要与" Include"互动,结果就会看起来相同。
只是 echo 无论您想要什么,而不是 include 在您的功能中!
update
您的功能应该像这样:
$string = "Whatever";
$str = get_var($string);
function get_var($str) {
ob_start();
echo $str;
return ob_get_clean();
}