如何使用PHP安全地将JSON数据写入文件 [英] How to safely write JSON data to file using PHP

查看:128
本文介绍了如何使用PHP安全地将JSON数据写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我的问题是:

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

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

I have attached some concept code below:

JavaScript(使用jQuery):

JavaScript (using 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示例(read-write.php):

PHP example (read-write.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;
}


推荐答案

首先:JSON是不是JavaScript,反之亦然。 JSON甚至都不是JavaScript的适当子集。

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

此外,由于您既不将某些用户输入解释为PHP,也不将某些输出解释为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:

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

这篇关于如何使用PHP安全地将JSON数据写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆