衡量成功
验证代码改进是否有效的唯一途径是:先确立基准数据,再对比实施优化后的结果。若不清楚特定方案能带来多少收益,便无法判定其是否为真正的解决方案。
主要关注两个核心指标:CPU 使用率和内存使用率。前者反映进程运行速度,后者显示脚本执行时的内存峰值。这两者往往呈反比关系,即可以通过增加 CPU 开销来降低内存消耗,反之亦然。
在采用多进程或多线程等异步模型的 PHP 应用中,CPU 和内存均为关键考量因素。在传统架构下,一旦触及服务器资源上限,这些指标通常会成为性能瓶颈。
精确测量 PHP 内部的 CPU 使用率较为困难。若需监控此项,建议在 Ubuntu 或 macOS 上使用 top 命令;Windows 用户可借助 Linux 子系统(WSL)以运行该命令。
本教程重点监测内存使用情况。我们将分析“传统”脚本的内存消耗,实施若干优化策略并记录数据,最终协助读者做出合理的技术选型。
以下工具用于查看内存使用量:
// formatBytes 方法取材于 php.net 文档
memory_get_peak_usage();
function formatBytes($bytes, $precision = 2) {
$units = array("b", "kb", "mb", "gb", "tb");
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . " " . $units[$pow];
}
我们将在脚本末尾调用这些方法,以便直观对比各脚本的内存峰值差异。
我们有什么选择?
高效读取文件有多种途径,主要适用于两类场景:一是需同时读取并处理全部数据,随后输出或执行后续操作;二是仅需对数据流进行转换备份,无需访问具体内容。
针对第一种场景,例如将每 10,000 行数据送入队列处理,必须先将这 10,000 行数据加载至内存,再交由队列管理器处理。
对于第二种场景,假设需压缩一个体积庞大的 API 响应内容。尽管不关心具体数据,但需确保其以压缩格式安全存储。
两者均涉及大文件读取,区别在于前者需知晓数据内容,后者则忽略数据细节。接下来深入探讨这两种处理方式。
逐行读取文件
PHP 提供了丰富的文件处理函数,结合部分函数可实现基础的文件阅读器。
// from memory.php
function formatBytes($bytes, $precision = 2) {
$units = array("b", "kb", "mb", "gb", "tb");
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . " " . $units[$pow];
}
print formatBytes(memory_get_peak_usage());
// from reading-files-line-by-line-1.php
function readTheFile($path) {
$lines = [];
$handle = fopen($path, "r");
while(!feof($handle)) {
$lines[] = trim(fgets($handle));
}
fclose($handle);
return $lines;
}
readTheFile("shakespeare.txt");
require "memory.php";
测试对象为包含莎士比亚全集的文本文件,大小约 5.5 MB。传统方式下,内存峰值达到 12.8 MB。现改用生成器逐行读取:
// from reading-files-line-by-line-2.php
function readTheFile($path) {
$handle = fopen($path, "r");
while(!feof($handle)) {
yield trim(fgets($handle));
}
fclose($handle);
}
readTheFile("shakespeare.txt");
require "memory.php";
文件大小不变,但内存峰值降至 393 KB。这一数据的意义在于结合数据处理逻辑。例如,当遇到两个空白行时将文档拆分为多个块:
// from reading-files-line-by-line-3.php
$iterator = readTheFile("shakespeare.txt");
$buffer = "";
foreach ($iterator as $iteration) {
preg_match("/\n{3}/", $buffer, $matches);
if (count($matches)) {
print ".";
$buffer = "";
} else {
$buffer .= $iteration . PHP_EOL;
}
}
require "memory.php";
即使将文档划分为 126 个块,内存使用仅为 459 KB。受生成器特性影响,最大内存占用取决于迭代中存储的最大文本块。此处最大块含 101985 个字符。
生成器虽有其他用途,但在读取大型文件方面表现优异。若需对数据进行实时处理,生成器通常是最佳选择。
文件之间的管道
当无需处理数据内容时,可将文件数据直接传递至另一文件,此过程称为管道传输。由于中间过程不可见,通常通过流(stream)实现。首先编写脚本实现文件复制以测量内存:
// from piping-files-1.php
file_put_contents(
"piping-files-1.txt", file_get_contents("shakespeare.txt")
);
require "memory.php";
结果符合预期:该脚本运行时的内存消耗高于被复制的文件本身。因为脚本需将整个文件读入内存后再写入新文件。小文件操作可行,但大文件会导致严重问题。
尝试从一个文件流式传输至另一个文件:
// from piping-files-2.php
$handle1 = fopen("shakespeare.txt", "r");
$handle2 = fopen("piping-files-2.txt", "w");
stream_copy_to_stream($handle1, $handle2);
fclose($handle1);
fclose($handle2);
require "memory.php";
代码逻辑稍显特殊:打开两个文件句柄,分别设为读写模式,然后执行复制并关闭。当得知内存使用仅为 393 KB 时可能感到惊讶,这与生成器逐行读取时的内存一致。原因是 fgets 的第二个参数定义每行读取字节数(默认为-1或至换行符长度),stream_copy_to_stream 的第三个参数同理。该函数每次从源流读取一行并写入目标流,因无需处理值,故跳过生成器产生值的步骤。
单纯传输文本实用性有限,考虑其他示例。假设需从 CDN 输出图像,代码如下:
// from piping-files-3.php
file_put_contents(
"piping-files-3.jpeg", file_get_contents(
"https://github.com/assertchris/uploads/raw/master/rick.jpg"
)
);
// ...or write this straight to stdout, if we don't need the memory info
require "memory.php";
模拟应用执行至此步骤。此次不从本地文件系统获取图像,而是从 CDN 获取。使用 file_get_contents 替代更优雅的方式(如 Guzzle),实际效果相同。
内存使用情况为 581KB。现在尝试进行流传输:
// from piping-files-4.php
$handle1 = fopen(
"https://github.com/assertchris/uploads/raw/master/rick.jpg", "r"
);
$handle2 = fopen(
"piping-files-4.jpeg", "w"
);
// ...or write this straight to stdout, if we don't need the memory info
stream_copy_to_stream($handle1, $handle2);
fclose($handle1);
fclose($handle2);
require "memory.php";
内存使用略低于此前(400 KB),结果一致。若无需内存信息,可直接打印至标准输出。PHP 提供简便方法:
$handle1 = fopen(
"https://github.com/assertchris/uploads/raw/master/rick.jpg", "r"
);
$handle2 = fopen(
"php://stdout", "w"
);
stream_copy_to_stream($handle1, $handle2);
fclose($handle1);
fclose($handle2);
// require "memory.php";
其他流
还存在一些可通过管道读写流的内置流。
- php://stdin 只读
- php://stderr 只写,功能类似 php://stdout
- php://input 只读,允许访问原始请求内容
- php://output 只写,允许写入输出缓冲区
- php://memory 与 php://temp(均可读写)用于临时存储数据。区别在于数据量大时,php://temp 会将数据转存至文件系统,而 php://memory 则继续驻留内存直至耗尽。
过滤器
可对流应用另一种技巧:过滤器。它在内外层之间提供控制,使数据不直接暴露给外部。假设需压缩 shakespeare.txt 文件,可使用 Zip 扩展:
// from filters-1.php
$zip = new ZipArchive();
$filename = "filters-1.zip";
$zip->open($filename, ZipArchive::CREATE);
$zip->addFromString("shakespeare.txt", file_get_contents("shakespeare.txt"));
$zip->close();
require "memory.php";
代码整洁,但总内存消耗约 10.75 MB。可通过过滤器优化:
// from filters-2.php
$handle1 = fopen(
"php://filter/zlib.deflate/resource=shakespeare.txt", "r"
);
$handle2 = fopen(
"filters-2.deflated", "w"
);
stream_copy_to_stream($handle1, $handle2);
fclose($handle1);
fclose($handle2);
require "memory.php";
此处使用 php:///filter/zlib.deflate 过滤器,读取并压缩资源内容。随后将压缩数据管道传输至另一文件,仅消耗 896KB 内存。
尽管格式不同且 Zip 有其他优势,但需权衡:若选择其他格式可节省 12 倍内存,是否值得考虑?
解压数据只需通过另一个 zlib 过滤器:
// from filters-2.php
file_get_contents(
"php://filter/zlib.inflate/resource=filters-2.deflated"
);
自定义流
fopen 和 file_get_contents 拥有默认选项集,但完全可定制。定义它们需创建新的流上下文。
// from creating-contexts-1.php
$data = join("&", [
"twitter=assertchris",
]);
$headers = join("\r\n", [
"Content-type: application/x-www-form-urlencoded",
"Content-length: " . strlen($data),
]);
$options = [
"http" => [
"method" => "POST",
"header"=> $headers,
"content" => $data,
],
];
$context = stream_content_create($options);
$handle = fopen("https://example.com/register", "r", false, $context);
$response = stream_get_contents($handle);
fclose($handle);
本例向 API 发送 POST 请求。端点安全,但仍使用 http 上下文属性(适用于 http/https)。设置头部后打开 API 文件句柄,以只读方式打开,由上下文负责编写。
创建自定义协议和过滤器
总结前,先讨论创建自定义协议。
Protocol {
public resource $context;
public __construct ( void )
public __destruct ( void )
public bool dir_closedir ( void )
public bool dir_opendir ( string $path , int $options )
public string dir_readdir ( void )
public bool dir_rewinddir ( void )
public bool mkdir ( string $path , int $mode , int $options )
public bool rename ( string $path_from , string $path_to )
public bool rmdir ( string $path , int $options )
public resource stream_cast ( int $cast_as )
public void stream_close ( void )
public bool stream_eof ( void )
public bool stream_flush ( void )
public bool stream_lock ( int $operation )
public bool stream_metadata ( string $path , int $option , mixed $value )
public bool stream_open ( string $path , string $mode , int $options ,
string &$opened_path )
public string stream_read ( int $count )
public bool stream_seek ( int $offset , int $whence = SEEK_SET )
public bool stream_set_option ( int $option , int $arg1 , int $arg2 )
public array stream_stat ( void )
public int stream_tell ( void )
public bool stream_truncate ( int $new_size )
public int stream_write ( string $data )
public bool unlink ( string $path )
public array url_stat ( string $path , int $flags )
}
不打算实现其中一个,因其值得单独成篇。工作量大,但完成后即可轻松注册流包装器:
if (in_array("highlight-names", stream_get_wrappers())) {
stream_wrapper_unregister("highlight-names");
}
stream_wrapper_register("highlight-names", "HighlightNamesProtocol");
$highlighted = file_get_contents("highlight-names://story.txt");
同样,也可创建自定义流过滤器。
Filter {
public $filtername;
public $params
public int filter ( resource $in , resource $out , int &$consumed ,
bool $closing )
public void onClose ( void )
public bool onCreate ( void )
}
可被轻松注册
$handle = fopen("story.txt", "w+");
stream_filter_append($handle, "highlight-names", STREAM_FILTER_READ);
highlight-names 需与新过滤器类的 filtername 属性匹配。亦可在 php:///filter/highligh-names/resource=story.txt 字符串中使用自定义过滤器。定义过滤器比协议简单,因协议需处理目录操作,而过滤器仅处理数据块。
强烈建议尝试创建自定义协议和过滤器。若将过滤器应用于 stream_copy_to_stream 操作,即使处理棘手的大文件,应用程序也几乎不消耗内存。想象编写调整大小图像过滤器或加密应用过滤器。
如果你愿意,我强烈建议你尝试创建自定义协议和过滤器。如果你可以将过滤器应用于 stream_copy_to_stream 操作,即使处理烦人的大文件,你的应用程序也几乎不使用任何内存。想象下编写 resize-image 过滤器和 encrypt-for-application 过滤器吧。
总结
虽非常见问题,但处理大文件时极易出错。在异步应用中,若不留意内存使用,极易导致服务器崩溃。
希望本教程带来新思路或更新固有认知,促使更多考虑如何高效读写大文件。熟悉并使用流和生成器,停止依赖 file_get_contents 等函数,此类错误将从应用中消失,这无疑是好事。
以上就是详解PHP如何读取大文件的详细内容,更多关于PHP如何读取大文件的资料请关注本站其它相关文章!