读取时文件被截断

时间:2019-02-16 16:59:01

标签: php file

我正在共享托管(fwrite)上的PHP文件中写入一些json结果。

然后,我读取这些文件以提取json结果(file_get_contents)。

有时候(可能是一千个中的一个),当我读取此文件时,它似乎被截断了:我只能读取文件前32768个字节的倍数。

我添加了一些代码来复制/粘贴我正在读取的文件,以防json字符串无效,然后得到2个不同的文件:原始文件正确编写,因为它包含有效的json字符串,并且复制了一个仅包含原始行的开头,大小为x * 32768字节。

您对可能是什么问题以及如何解决这个问题有任何想法吗? (我不知道如何进一步调查)

谢谢

2 个答案:

答案 0 :(得分:0)

没有示例代码,就不可能给出“修复我的代码”的答案,但是在进行文件写/读类型的编程时,您应该遵循一个简单的过程(从描述中,它缺少一个相当关键的步骤! )

首先,写入TEMP文件(您正在写入文件,但是在这里写入TEMP文件很重要-否则,您可能会遇到争用条件....... ;;);

在php中实现此目的的简单方法

$yourData = "whateverYourDataIs....";
$goodfilename = 'whateverYourGoodFileNameIsForYourData.json';
$tempfilename = 'tempfile' . time(); // MANY ways to do this (lots of SO posts on it - just get a unique name every time you write ('unique' may not be needed if you only occasionally do a write, but it is a good safety measure to avoid collisions and time() works for many programs.)
// Now, use $tempfilename in your fwrite.
$fwrite = fwrite($tempfilename,$yourData);
if ($fwrite === false) { 
    // the write failed, so do whatever 'error' function you may need
    // since it failed, there should be no file, but not a bad idea to attempt to delete it
    unlink ($tempfile);
}
else {
    // the write succeeded, so let's do a 'sanity check' on the file to make sure it is good JSON (this is a 'paranoid' check, but "better safe than sorry", right?)
    if(json_decode($tempfile)){
        // we know the file is good JSON, so now RENAME (this is really fast, so collisions are almost impossible)  NOTE: see http://php.net/manual/en/function.rename.php comments for some potential challenges and workarounds if you have trouble with rename.
        rename($tempfilename,$goodfilename);
    }
    // Now, the GOOD file will contain your new data - and those read issues are gone! (though never say 'never' - it may be possible, but very unlikely!)  
}

这可能直接/不是您直接遇到的问题,您必须对此进行调整以适合您的代码,但出于安全考虑,这是避免冲突的一种好方法,它应该使您获得〜100%的读取成功,我相信是你的追求!)

如果这没有帮助,则需要一些直接代码来提供更完整的答案。

答案 1 :(得分:0)

正如@UlrichEckhardt评论所建议的,这是由于读/写并发问题。我试图读取正在写入的文件。我通过等待再尝试读取文件来解决了这个问题