Home > front end >  How to resolve issue :: file_get_contents(http://localhost:8085/assets/data/test.txt): Failed to ope
How to resolve issue :: file_get_contents(http://localhost:8085/assets/data/test.txt): Failed to ope

Time:03-11

By using CodeIgniter 4 framework, I've developed RESTful api and there I need to access file (.json and .txt) to get content. But not able to access php inbuilt function file_get_contents(). For more details, pls check attached screenshot API_curl_file_get_content_error.PNG enter image description here

And test.txt file is also accessible with same file path. For more details pls check screenshot Input-txt-file-content.png enter image description here

NOTE : 1) test.txt file and respective directories have full permission. 2) Development environment : <---->Apache/2.4.47 (Win64) OpenSSL/1.1.1k PHP/8.1.2 <---->Database client version: libmysql - mysqlnd 8.1.2 <---->PHP version: 8.1.2 <---->CodeIgniter 4

Product.php (index method)
<?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);
    }
}

CodePudding user response:

Explanation:

Remember that "http://localhost:8085/" most likely points to the document root of the project, which is usually the /public path. So, unless the "assets" folder resides in the /public path, file_get_contents("http://localhost:8085/assets/data/test.txt"); will fail to find the requested server resource.

Solution:

Since your file resource (test.txt) is on the local filesystem,

Instead of:

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

Use this:
constant ROOTPATH

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

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

Addendum:

I believe you also forgot to add the $json_data output to the returned $data variable in the Product::index resource controller method.

  • Related