codeigniter 如何解决问题:文件获取内容():无法打开流:HTTP请求失败

8e2ybdfx  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(113)

通过使用CodeIgniter 4框架,我开发了RESTful api,我需要访问文件(.json和.txt)来获取内容。但是无法访问php内置函数file_get_contents()。要了解更多详细信息,请查看所附的截图API_curl_file_get_content_error.PNG x1c 0d1x
test.txt文件也可以通过相同的文件路径访问。有关更多详细信息,请查看屏幕截图Input-txt-file-content.png

**注意:1)test.txt文件和相应的目录具有完全权限。2) 开发环境: <---->Apache/2.4.47(Win 64)OpenSSL/1.1.1k PHP/8.1.2<---->数据库客户端版本:php版本号:2016 <---->8.1.2 <---->代码触发器4

产品. 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);
    }
}
ttp71kqs

ttp71kqs1#

解释:

请记住,“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");

使用此选项:
常数ROOTPATH
项目根目录的路径。就在APPPATH之上。

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

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

相关问题