【问题标题】:php Segmentation fault: 11 when writing or reading/loading a filephp Segmentation fault: 11 写入或读取/加载文件时
【发布时间】:2019-03-25 22:22:05
【问题描述】:

上述问题只是偶尔出现。我不知道为什么,但我认为我的用于在 JSON 文件中保存和加载 JSON 对象的 php 脚本没有完美完成。

writeLanguage.php

<?php
$myFile = "languages.json";

$cmsData = $_POST['data'];
$obj = json_decode($cmsData, true);

$myFile = "language.json";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh,json_encode($obj));

fclose($fh);

readLanguage.php

$cmsData = $_GET['data'];

$myFile = "language.json";
$fhh = fopen($myFile, 'r') or die("can't open file");

$jsondata = file_get_contents($myFile);
fclose($fhh);
$json = json_decode($jsondata, true);
echo $jsondata;

这里是我的 javascript 代码:

DataService.prototype.loadLanguagePromise = function () {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: "php/services/readLanguage.php",
            type: "GET",
            async: true,
            dataTyp: 'json',
            success: function (data) {
                resolve("stuff worked");
            },
            error: function (xhr, desc, err) {
                reject(Error("It broke"));
            }
        })
    })
};

DataService.prototype.saveLanguage = function (cmsObject) {
    return new Promise(function (resolve, reject) {
        $.ajax({
            url: "php/services/writeLanguage.php",
            type: "POST",
            data: {data: JSON.stringify(cmsObject)},
            dataTyp: 'json',
            success: function (data) {

                resolve(data);
            },
            error: function (xhr, desc, err) {
                reject(xhr, desc, err);
            }
        })
    })
};

我查找了 Segmentation fault 的定义,但无法真正得到“啊啊啊……当然,这就是原因”。

【问题讨论】:

    标签: php json segmentation-fault


    【解决方案1】:

    尝试删除 fopen、fwrite 和 fclose。在第一种情况下,您只需要 file_put_contents(),在第二种情况下 - 只有 file_get_contents。

    <?php
    $myFile = "languages.json";
    $cmsData = $_POST['data'];
    $obj = json_decode($cmsData, true);
    $fh = file_put_contants($myFile, $cmsData,LOCK_EX) or die("can't open file");
    
    $cmsData = $_GET['data'];
    $myFile = "language.json";
    $jsondata = file_get_contents($myFile);
    $json = json_decode($jsondata, true);
    echo $jsondata;
    

    【讨论】:

    • 您还应该考虑使用LOCK_EX-标志file_put_contents() 在写入文件时获得对文件的独占锁定。
    【解决方案2】:

    您可以使用https://stackoverflow.com/a/7752606/4625150的答案对Segmentation fault进行系统分析

    上述问题您需要一些时间才能弄清楚,但是您会找到正确的根本原因然后解决它。

    查看您的代码,您正在读取 JSON,然后将 JSON 写入文件系统。那是一个故障区域,很多时候是由于内存不足。解决内存问题

    • 找到正确的 php.ini
    • 然后通过更改 php.ini 中的 memory_limit 来增加内存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多