Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file_get_contents with Lumen

I have this code into a function (php class) :

$theFile = '/test/test.xml'; // these are in the public folder
dd(file_get_contents($theFile));

If I go to mydomain.local/test/test.xml, I get the working xml code.

But with file_get_contents, I get this error :

file_get_contents(/test/test.xml): failed to open stream: No such file or directory

How to solve this ?

like image 588
w3spi Avatar asked Dec 10 '15 00:12

w3spi


2 Answers

Lumen doesn't have the public_path() that you might be familiar with in Laravel to easily grab the path to a public file.

The simplest method for re-implementing it would be to add a package called irazasyed/larasupport to your project which adds various missing helpers (including public_path()) as well as adding the vendor publish command that is missing from Lumen.

Alternatively if you do not wish to add a third party package simply create a file in your app directory called helpers.php and then within your composer.json file add the following within the "autoload" part and run composer dump-autoload to refresh the autoloader cache:

"files": [
    "app/helpers.php"
],

Then within helpers.php add the following content:

<?php
if (!function_exists('public_path')) {
   /**
    * Get the path to the public folder.
    *
    * @param  string $path
    * @return string
    */
    function public_path($path = '')
    {
        return env('PUBLIC_PATH', base_path('public')) . ($path ? '/' . $path : $path);
    }
}
like image 121
carbontwelve Avatar answered Oct 24 '22 03:10

carbontwelve


You are passing an absolute path to the function that is relative to the server's base directory. This is not necessary the same base directory for the URL. Try passing a path relative to the current executing script.

like image 2
Alvaro Flaño Larrondo Avatar answered Oct 24 '22 03:10

Alvaro Flaño Larrondo