【问题标题】:failed to open stream: No error in C:\xampp\htdocs\index.php on line 11无法打开流:第 11 行的 C:\xampp\htdocs\index.php 中没有错误
【发布时间】:2017-10-25 15:31:24
【问题描述】:

我正在使用 slim php 路由器,但由于某种原因我收到此错误。

警告:file_get_contents(C:\xampp\htdocs/views/users.php?userId=3): 无法打开流:C:\xampp\htdocs\index.php 第 11 行没有错误

这是我的索引代码。

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require dirname(__FILE__) . '/vendor/autoload.php';
$app = new \Slim\App;
$app->get('/users/{userId}', function ($request, $response, $args) {
    if (!ctype_alnum($args['userId'])) {
        $args['userId'] = '0';
    }
    $body = file_get_contents(dirname(__FILE__) . "/views/users.php?userId={$args['userId']}");
    return $response->write($body);
});
$app->run();
?>

出于测试目的,我将其放在位于 views 文件夹中的 users.php 文件中

<?php
echo $_GET['userId'];

?>

你可以在https://github.com/slimphp/Slim找到这个php路由器

【问题讨论】:

    标签: php file-get-contents router


    【解决方案1】:

    试试这个,file_get_contents不要使用url参数

    file_get_contents(dirname(__FILE__) . "/views/users.php");
    

    【讨论】:

    • 您是否有其他方法可以将用户 ID 传递给用户页面,以便在请求 ID 时显示正确的用户
    • 抱歉回复晚了我睡着了
    • 这只会返回 PHP 源代码,不会运行脚本。
    • 它不会显示 php 源代码。它显示 html 输出,当您在 file_get_contents 中使用 php 文件时,它会输出 html 源代码。例如index.php = &lt;?php echo file_get_contents(dirname(__FILE__) . '/homepage.php'); ?&gt;homepage.php = &lt;?php echo 'Hello!'; ?&gt;
    【解决方案2】:

    为了执行 PHP 脚本,您必须通过网络服务器,而不是作为本地文件访问它。所以应该是

    $body = file_get_contents(dirname($_SERVER['PHP_SELF']) . "/views/users.php?userId={$args['userId']}");
    

    【讨论】:

    • 这不起作用 dirname(FILE) 从你作为用户的文件目录开始 dirname(FILE)
    • 抱歉回复晚了我睡着了
    • 我知道dirname(__FILE__) 不起作用。它作为本地文件访问它,它不运行脚本,因为它必须通过网络服务器。
    • dirname(FILE) 与 file_get_contents 以及 dirname($_SERVER['PHP_SELF']) 一起使用。他们都工作。它们都不适用于“/views/users.php?userId={$args['userId']}”,我已经测试了你的代码和地雷,但它不起作用你的答案没有回答我的问题。
    猜你喜欢
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2014-01-07
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    相关资源
    最近更新 更多