如何通过查询字符串文件名执行php代码而不包含?



我正在尝试使用文件名作为查询字符串动态执行php代码,如index.php?q=script1。到目前为止,我所做的工作有效,但仅当我在主索引中对传递的文件使用 include 时。

<?php 
include("class.php"); 
if (!empty($_GET['q'])) {
$sp = $_GET['q'];
$sp = basename($sp);
$location = 'src/scripts/' . $sp . '.php';
if (file_exists($location)) {
file_get_contents($location); // Tried, does not work
shell_exec('php -f /' . $location); // This does not work either
include($location); // This works
}
}
?>

我正在寻找一种在不实际将文件包含在主索引中的情况下执行 em 的方法。可能吗?

TRY

if (!empty($_GET['q']))
{
$sp = $_GET['q'];
$sp = basename($sp);
$location = __DIR__.'/src/scripts/' . $sp . '.php';

if (file_exists($location))
{
$output = shell_exec('php -f /' . $location);
//to see output
echo $output;
}
}

如果你不想包含文件,至少有三种不同的方法可以让PHP脚本执行。 我使用引用以下文件的查询字符串进行了测试:

您好.php:

<?php
function greet() {
$h = "hello";
$w = "world";
return "$h, $w!";
}
echo greet();

为了便于执行 hello.php,可以使用以下代码中描述的任何技术:

<?php
if ( !empty( $_GET['q'] ) ) {
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\');
$file = basename( htmlentities( $_GET['q'] ) );  // "hello.php";
if (file_exists($file)) {
/*$contents = file_get_contents("http://$host$uri/$file"); // works
print_r($contents);*/
/*$output = shell_exec('php -f ./' . $file); // works, too
print_r($output);*/
if (headers_sent()) {  // tip fr:https://stackoverflow.com/a/8028987/701302
$url = "http://$host$uri/$file";
die("Please click this link: <a href="$url">$url</a>");
}
else
{
header("Location: http://$host$uri/$file");
exit;
}
}        

}

使用 file_get_contents(),您需要传入 url 或相对 url。 如果传入文件的路径,则该函数将检索脚本本身,而不是执行它。 此外,使用 file_get_contents(),如果您希望捕获变量,则需要将任何返回值分配给变量。

另一种方法是使用 shell_exec() 使用命令行 PHP 和 -f 选项来解析和执行 PHP 文件。 使用此函数,如果您希望访问该值,则必须将任何返回值分配给变量。

最后,您可以指示 PHP 使用 header() 将 Web 服务器重定向到指定的文件。

注意:在没有进行一些验证的情况下,不应使用 $_GET 变量。此代码检查是否存在值,并使用 htmlentities() 来避免 XSS 攻击。

最新更新