我将如何使用 Laravel 加载 JSON 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27307491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:31:14  来源:igfitidea点击:

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

jsonlaravel

提问by rotaercz

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.

我有一个 JSON 文件,我想使用 Laravel 加载它。我正在学习 Laravel 并想知道正确的方法来做到这一点。我在公共文件夹中名为 json 的文件夹中有 JSON 文件。

In my routes.php I have the following:

在我的 routes.php 中,我有以下内容:

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

In JSONController I have:

在 JSONController 我有:

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?

我的命名约定是否还可以,或者您有更好的建议吗?

回答by TheDPQ

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.

在允许用户输入数据来决定读取和写入哪些文件时,请务必小心。这是一个简单的代码,它将接收文件名并在 apps/storage/json 文件夹中查找。我不太熟悉 Illuminate 为防止系统注入所做的工作,但您可能至少希望通过验证器确保“文件名”不包含除字母数字字符之外的任何内容。

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.

除非 JSON(或任何文件)需要公开,否则不应将其保存在公用文件夹中。这样他们必须通过您的应用程序(和权限)才能查看它。您还可以在公用文件夹之外拥有更多限制性权限。

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

}