如何使用 PHP 安全地将 JSON 数据写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6187052/
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-08-25 23:36:33  来源:igfitidea点击:

How to safely write JSON data to file using PHP

phpjsonfilesecuritycode-injection

提问by Max Barnas

I've got HTML form for editing images. All data is stored in JSON. When I change current image, I want to save changes, through PHP script, to a text file. If I return to previous image, this configuration will be send again from this file to the form.

我有用于编辑图像的 HTML 表单。所有数据都存储在 JSON 中。当我更改当前图像时,我想通过 PHP 脚本将更改保存到文本文件。如果我返回上一个图像,这个配置将再次从这个文件发送到表单。

My question is:

我的问题是:

How to write/read this kind of data safely. Where and how effectively check data to prevent some JS/PHP code injections?

如何安全地写入/读取此类数据。在哪里以及如何有效地检查数据以防止某些 JS/PHP 代码注入?

I have attached some concept code below:

我在下面附上了一些概念代码:

JavaScript (using jQuery):

JavaScript(使用 jQuery):

// Writing
$.ajax({
    global: false,
    type: "POST",
    cache: false,
    dataType: "json",
    data: ({
        action: 'write',
        config: JavaScriptJSON_Obj
    }),
    url: 'read-write.php'
});

// Reading
$.ajax({
    global: false,
    type: "POST",
    cache: false,
    dataType: "json",
    data: ({
        action: 'read'
    }),
    url: 'read-write.php',
    success: function(data){
        JavaScriptJSON_Obj = data;
    }
});

PHP example (read-write.php):

PHP 示例(读写.php):

switch ($_REQUEST['action']) {
    case 'write':
        file_put_contents('config.txt', $_REQUEST['config']);
        break;
    case 'read':
        $s = file_get_contents('config.txt');
        echo json_encode($s);
        break;
}

采纳答案by Gumbo

First of all: JSON is not JavaScript and vice versa. And JSON is even not a proper subset of JavaScript.

首先:JSON 不是 JavaScript,反之亦然。JSON 甚至不是 JavaScript 的正确子集。

Besides that, since you neither interpret some user input as PHP nor some output as JavaScript, there is no need to worry. But don't forget to specify your output properly:

除此之外,由于您既不将某些用户输入解释为 PHP,也不将某些输出解释为 JavaScript,因此无需担心。但不要忘记正确指定您的输出:

header('Content-Type: application/json;charset=utf-8');
$s = file_get_contents('config.txt');
echo json_encode($s);

回答by Jakob Egger

The problem with your code is that it won't work, security issues aside. You must either serialize the data, or encode it to json BEFORE storing it in a file, ie. like this:

你的代码的问题是它不起作用,除了安全问题。您必须序列化数据,或者在将其存储在文件中之前将其编码为 json,即。像这样:

switch ($_REQUEST['action']) {
    case 'write':
        file_put_contents('config.txt', json_encode($_REQUEST['config']));
        break;
    case 'read':
        readfile('config.txt');
        break;
}

Serialising works like this:

序列化的工作方式如下:

switch ($_REQUEST['action']) {
    case 'write':
        file_put_contents('config.txt', serialize($_REQUEST['config']));
        break;
    case 'read':
        $data = unserialize(file_get_contents('config.txt'));
        echo json_encode($data);
        break;
}

As long as you make sure that the path you read/write to is correct, there are no code injection problems with this code. The only potential problem is if you can choose what file to use (rather than hardcode "config.txt" into the code). Then you'd have to validate to make sure the file is in a given directory etc.

只要你确保你读/写的路径是正确的,这段代码就没有代码注入问题。唯一的潜在问题是您是否可以选择要使用的文件(而不是将“config.txt”硬编码到代码中)。然后你必须验证以确保文件在给定的目录等中。

回答by inquam

I would always check the data returned to see if it is in a format I expect. Say you are saving an image... Check it using MIME checks etc. to make sure that it is an image. If you just save data as is on the server you could open the door for some potential security issues.

我总是会检查返回的数据,看看它是否是我期望的格式。假设您正在保存一个图像...使用 MIME 检查等检查它以确保它是一个图像。如果您只是将数据按原样保存在服务器上,则可能会为一些潜在的安全问题敞开大门。

If you mean that you just save data about which images was viewed it could still pose a problem depending on how and where that data is accessed and used. So if you except an integer and nothing more, make sure that the data you receive and save is an integer and nothing more.

如果您的意思是您只是保存有关查看过哪些图像的数据,那么根据访问和使用该数据的方式和位置,它仍然可能会带来问题。因此,如果您除了一个整数,仅此而已,请确保您接收和保存的数据是一个整数,仅此而已。