PHP为我上传的文件添加了2个额外字节

时间:2011-02-01 04:11:34

标签: php upload

我有一个通过PHP上传文件的进程,但生成的文件最终比源文件大2个字节。我不确定这两个字节来自哪里。 (实际的过程是一个分块上传,我切片文件并上传切片,每个切片最终比它开始的时间长2个字节,但我已经测试了一个小文件,它也比2个字节大了源)。

我正在附加我的PHP ...这是PHP的正常功能吗?我正在想象某种类型的null终止符(在每个文件的末尾看起来确实有一个\ n最初不存在)。在重新组装原始文件之前,是否需要将文件读入缓冲区并删除最后两个字节?我不得不想象我做错了什么,但我对它会是什么感到困惑。

如果我确实需要手动剥离最后两个字节,那么正确的方法是什么(它是二进制文件),然后将其余部分附加到我正在重建的整个文件中?


修改


当PHP将其保存到服务器时,每个上传的文件都会添加一个0D0A字。所以...我想问题是如何防止这种情况发生。

<?PHP
$target_path = $_REQUEST[ 'path' ];
$originalFileName = $_REQUEST['original_file_name'];
$target_path = $target_path . basename( $_FILES[ 'Filedata' ][ 'name' ] );

if ( move_uploaded_file( $_FILES[ 'Filedata' ][ 'tmp_name' ], $target_path ) )
{

        $newFilePath = $originalFileName; //this is the overall file being re-assembled
        $fh = fopen($newFilePath, 'ab') or die("can't open file");

        $nextSlice = file_get_contents($target_path); //this is the slice that's 2 bytes too big each time

        fputs($fh, $nextSlice);
        fclose($fh);

//      unlink($target_path); //normally I'd delete the slice at this point, but I'm hanging on to it while I figure out where the heck the 2 extra bytes are coming from.

        fclose($fh);

        echo "SUCCESS";

}
else
{
     echo "FAIL:There was an error uploading the file, please try again!";
}
?>

2 个答案:

答案 0 :(得分:1)

文件是二进制文件吗?我认为file_get_contents导致问题,因为它将它视为一个字符串。也许你应该试试fread

答案 1 :(得分:0)

解决方案原来是这样的:

fwrite($ fh,$ GLOBALS [“HTTP_RAW_POST_DATA”]);

我可能在我的请求中做错了,当我使用我在问题中描述的方法时,文件最后用额外的0D0A写入,但上面提取数据的方法使它完好无损地到达合适的长度。