Home >php教程 >PHP源码 >PHP读写大“二进制”文件,不必申请很大内存(fopen、fread、fwrite、fclose)

PHP读写大“二进制”文件,不必申请很大内存(fopen、fread、fwrite、fclose)

PHP中文网
PHP中文网Original
2016-05-23 16:40:351847browse

<?php
/**
 * 读写大二进制文件,不必申请很大内存
 * 只有读取到内容才创建文件
 * 保证目录可写
 *
 * @param string $srcPath 源文件路径
 * @param string $dstPath 目标文件路径
 * @return bool
 */
function fetch_big_file($srcPath, $dstPath)
{
    set_time_limit(0); // 设置脚本执行时间无限长
 
    if (!$fpSrc = fopen($srcPath, "rb"))
    {
        return false;
    }
 
    $isWriteFileOpen = false; // 写文件 是否已打开?
    do
    {
        $data = fread($fpSrc, 8192); // 每次读取 8*1024个字节
        if (!$data)
        {
            break;
        }
        else if (!$isWriteFileOpen)
        {
            // 第一次读取文件,并且有内容,才创建文件
            $fpDst = fopen($dstPath, "wb");
            $isWriteFileOpen = true;
            fwrite($fpDst, $data);
        }
        else
        {
            // 写入
            fwrite($fpDst, $data);
        }
    } while (true);
 
    fclose($fpSrc);
    fclose($fpDst);
 
    return true;
}
 
$srcPath = &#39;d:/PHP/data/eclipse-jee-kepler-R-win32-x86_64.pdf&#39;;
$dstPath = &#39;Z:/reslibCovertingfiles/eclipse-jee-kepler-R-win32-x86_64.pdf&#39;;
 
fetch_big_file($srcPath, $dstPath);
 
echo &#39;success&#39;;

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:redis vs ssdb, hmset效率对比Next article:php投票小程序