如何解决问题 :: file_get_contents(http://localhost:8085/assets/data/test.txt): 无法打开流:HTTP 请求失败

How to resolve issue :: file_get_contents(http://localhost:8085/assets/data/test.txt): Failed to open stream: HTTP request failed

通过使用 CodeIgniter 4 框架,我开发了 RESTful api 并且我需要访问文件 (.json 和.txt) 来获取内容。但无法访问 php 内置函数 file_get_contents()。 有关详细信息,请查看随附的屏幕截图 API_curl_file_get_content_error.PNG

和test.txt 文件也可以使用相同的文件路径访问。有关详细信息,请查看屏幕截图 Input-txt-file-content.png

注意: 1) test.txt 文件和相应目录具有完全权限。 2)开发环境: <---->Apache/2.4.47 (Win64) OpenSSL/1.1.1k PHP/8.1.2 <---->数据库客户端版本:libmysql - mysqlnd 8.1.2 <---->PHP版本:8.1.2 <---->CodeIgniter 4

Product.php(索引方法)
<?php

namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;

class Product extends ResourceController
{
    use \CodeIgniter\API\ResponseTrait;

    public function index()
    {
        helper("filesystem");
        ini_set('max_execution_time', 300);

        $data['msg'] = "Product Index wizard";
        $data['status'] = 200;
        $file_path = base_url() . '/assets/data/test.txt';   // Read JSON
        $json = file_get_contents($file_path, true);
        $json_data = json_decode($json, true);

        return $this->respond($data);
    }
}

解释:

记住“http://localhost:8085/”很可能指向项目的文档根目录,即通常是 /public 路径。因此,除非“assets”文件夹位于 /public 路径中,否则 file_get_contents("http://localhost:8085/assets/data/test.txt"); 将无法找到请求的服务器资源。

解决方案:

由于您的文件资源 (test.txt) 在本地文件系统上,

而不是:

file_get_contents("http://localhost:8085/assets/data/test.txt");

使用这个:
constant ROOTPATH

The path to the project root directory. Just above APPPATH.

file_get_contents(ROOTPATH . "assets/data/test.txt");

附录:

我相信您也忘记了将 $json_data 输出添加到 Product::index 资源控制器方法中返回的 $data 变量。