Howard
Howard

Reputation: 3758

How would I go about loading a JSON file using Laravel?

I have a JSON file that I'd like to load using Laravel. I'm learning Laravel and would like to know the right way to do this. I have the JSON files in a folder called json in the public folder.

In my routes.php I have the following:

Route::get('/json/{jsonfile}', array(
    'as' => 'load-json',
    'uses' => 'JSONController@loadJSON'
));

In JSONController I have:

public function loadJSON($jsonfile) {
    // not sure what to do here

    return View::make('json.display')
                ->with('jsonfile', $jsonfile);
}

Also is my naming convention ok or do you have better suggestions?

Upvotes: 2

Views: 13596

Answers (1)

TheDPQ
TheDPQ

Reputation: 486

Always be careful when allowing a user inputed data to decide what files to read and write. Here is simple code that will take in the filename and look in the apps/storage/json folder. I'm less familiar with what Illuminate does to protect against system injections but you might want at the very least to make sure that 'filename' doesn't contain anything but alphanumeric characters with a validator.

Unless the JSON (or any file) needs to be public you shouldn't keep it in the public folder. This way they must go through your app (and permissions) to view it. Also you can have more restrictive permissions outside the public folder.

public function loadJSON($filename) {
    $path = storage_path() . "/json/${filename}.json"; // ie: /var/www/laravel/app/storage/json/filename.json
    if (!File::exists($path)) {
        throw new Exception("Invalid File");
    }

    $file = File::get($path); // string

    // Verify Validate JSON?

    // Your other Stuff

}

Upvotes: 10

Related Questions