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

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

PHP中文网
Release: 2016-05-23 16:40:35
Original
1861 people have browsed it

<?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;;
Copy after login

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template