与文本文件不同,二进制文件以原始字节序列形式存储数据,不依赖字符编码(如UTF-8),常见类型包括:
php读取二进制文件时,必须明确指定文件打开模式为二进制(如`"rb"`或`"rb+"`),否则在Windows系统下可能因自动转换换行符(`\r\n`↔`\n`)导致数据错位。
| 函数 | 用途 | 返回类型 | 关键参数说明 |
|---|---|---|---|
fopen($file, "rb") | 打开二进制文件 | 资源/False | 必须使用"rb"模式,避免Windows自动转换 |
feof($fp) | 检测文件指针是否结束 | Bool | 仅用于循环条件,不可用于预判大小 |
fread($fp, $length) | 读取指定长度字节 | String/False | 返回原始字节字符串,非文本 |
unpack($format, $data) | 按格式解包字节 | Array | 格式字符串决定字节→标量映射 |
pack($format, ...$values) | 按格式打包数据为字节 | String | 与unpack互逆,常用于写入 |
ftell($fp) | 获取当前文件指针位置 | Int/False | 单位:字节,从0开始计数 |
fseek($fp, $offset, $whence) | 移动文件指针 | Int | whence:SEEK_SET(0), SEEK_CUR(1), SEEK_END(2) |
多字节数据(如int16、float32)在二进制文件中存在字节序问题:
php读取二进制文件时必须明确字节序!unpack使用格式符区分:
| 格式符 | 含义 | 字节序 | 示例(4字节) |
|---|---|---|---|
v | unsigned short (16-bit, little-endian) | 小端 | 0x12345678 → 0x5678, 0x1234 |
V | unsigned long (32-bit, little-endian) | 小端 | 0x12345678 → 0x78563412 |
n | unsigned short (16-bit, big-endian) | 大端 | 0x12345678 → 0x1234, 0x5678 |
N | unsigned long (32-bit, big-endian) | 大端 | 0x12345678 → 0x12345678 |
S | unsigned short (16-bit, machine byte order) | 依赖主机 | 不可移植,慎用 |
实际案例:PNG文件头标识为0x89504E470D0A1A0A,前4字节固定为大端序的`0x89504E47`(即`"‰PNG"`),php读取二进制文件时必须按大端序解析该标识。
理解文件头(Magic Number)是php读取二进制文件的关键:
php读取二进制文件时,可通过读取前N字节匹配Magic Number快速验证文件类型,避免处理损坏文件。
php读取二进制文件的标准流程如下:
错误示例(常见陷阱):
// ❌ 错误:未指定"b"模式,在Windows会自动转换\r\n
$fp = fopen("image.png", "r");
// ❌ 错误:fread未指定长度(读取整个文件),大文件易内存溢出
$data = fread($fp, filesize($file)); // 小文件可用,大文件危险
正确示例(安全读取1KB):
$file = "example.bin";
$fp = fopen($file, "rb");
if (!$fp) die("无法打开文件:" . $file);
fseek($fp, 0, SEEK_SET); // 确保从头开始
$chunk = fread($fp, 1024); // 读取1KB
if ($chunk === false) {
echo "读取失败,可能已到文件末尾";
} else {
echo "成功读取" . strlen($chunk) . "字节";
}
fclose($fp);
unpack是php读取二进制文件的核心,其格式字符串决定如何解释字节序列:
典型php读取二进制文件解包示例:
// 读取32位小端整数
$fp = fopen("data.bin", "rb");
fseek($fp, 100, SEEK_SET); // 跳过100字节
$bytes = fread($fp, 4); // 读取4字节
$int32 = unpack("Vnum", $bytes)["num"];
echo "值:" . $int32; // 输出:20230101(假设字节为0x9186F101)
// 读取JPEG文件头中的DQT表长度
fseek($fp, 0, SEEK_SET);
$header = fread($fp, 10);
$marker = unpack("Cmarker", substr($header,0,1))["marker"];
if ($marker === 0xDB) { // DQT标记
$len = unpack("nlength", substr($header,1,2))["length"];
echo "DQT长度:" . ($len - 2) . "字节";
}
当unpack无法直接支持时,php读取二进制文件需手动位运算:
($byte & 0x0F) 取低4位;($byte >> 4) 取高4位$val = ($byte1 << 8) | $byte2(大端)$rev = implode("", array_reverse(str_split($bytes, 1)))案例:解析PNG IHDR块
PNG IHDR块结构(13字节):
php读取二进制文件提取宽高:
$fp = fopen("image.png", "rb");
fseek($fp, 16, SEEK_SET); // 跳过8字节PNG签名 + 4字节长度 + 4字节类型("IHDR")
$chunk = fread($fp, 13);
$width = unpack("Nwidth", substr($chunk,0,4))["width"];
$height = unpack("Nheight", substr($chunk,4,4))["height"];
echo "PNG尺寸:{$width}×{$height}";
JPEG由段(Segment)组成,每段以`0xFF`开始,后跟标记(Marker)和可选数据:
php读取二进制文件提取JPEG尺寸:
function getJpegSize($file) {
$fp = fopen($file, "rb");
fseek($fp, 2, SEEK_SET); // 跳过SOI
while (!feof($fp)) {
$byte = fread($fp, 1);
if (ord($byte) !== 0xFF) continue;
$marker = ord(fread($fp, 1));
if ($marker === 0xC0) { // SOF0
fread($fp, 3); // 跳过P、Y、X
$height = unpack("n", fread($fp, 2))[1];
$width = unpack("n", fread($fp, 2))[1];
fclose($fp);
return ["width"=>$width, "height"=>$height];
}
$len = unpack("n", fread($fp, 2))[1];
fseek($fp, $len - 2, SEEK_CUR); // 跳过数据段
}
fclose($fp);
return false;
}
PNG由多个块(Chunk)组成,每块包含:
php读取二进制文件提取PNG元数据:
function getPngMeta($file) {
$fp = fopen($file, "rb");
$sig = fread($fp, 8);
if ($sig !== "\x89PNG\x0D\x0A\x1A\x0A") {
fclose($fp);
return "非PNG文件";
}
$ihdr = getChunk($fp);
if ($ihdr["type"] !== "IHDR") {
fclose($fp);
return "缺少IHDR块";
}
$width = unpack("N", substr($ihdr["data"],0,4))[1];
$height = unpack("N", substr($ihdr["data"],4,4))[1];
$bitDepth = ord(substr($ihdr["data"],8,1));
fclose($fp);
return ["width"=>$width,"height"=>$height,"bitDepth"=>$bitDepth];
}
function getChunk($fp) {
$len = unpack("N", fread($fp, 4))[1];
$type = fread($fp, 4);
$data = fread($fp, $len);
fread($fp, 4); // 跳过CRC
return ["type"=>$type, "data"=>$data];
}
GIF由逻辑屏幕描述符(Logical Screen Descriptor)开始,含全局颜色表:
php读取二进制文件提取GIF尺寸:
function getGifSize($file) {
$fp = fopen($file, "rb");
$sig = fread($fp, 6);
if (!in_array($sig, ["GIF87a", "GIF89a"])) {
fclose($fp);
return "非GIF文件";
}
$width = unpack("v", fread($fp, 2))[1];
$height = unpack("v", fread($fp, 2))[1];
fclose($fp);
return ["width"=>$width, "height"=>$height];
}
MP3文件通常以ID3v2标签开头(可选),结构为:
php读取二进制文件提取ID3标题:
function getMp3Title($file) {
$fp = fopen($file, "rb");
$head = fread($fp, 10);
if (substr($head, 0, 3) !== "ID3") {
fclose($fp);
return "无ID3v2标签";
}
$version = unpack("Cmajor/Cminor", substr($head,3,2));
$flag = ord(substr($head,5,1));
$sizeBytes = substr($head,6,4);
$size = 0;
for ($i=0; $i<4; $i++) {
$size = ($size << 7) | (ord($sizeBytes[$i]) & 0x7F);
}
$data = fread($fp, $size);
fclose($fp);
// 解析TIT2帧
if (strpos($data, "TIT2") !== false) {
$pos = strpos($data, "TIT2");
$len = unpack("N", substr($data, $pos+4, 4))[1];
$flags = unpack("v", substr($data, $pos+8, 2))[1];
$text = substr($data, $pos+10, $len);
if ($flags & 0x00FF) { // 编码标识
$enc = ord($text[0]);
$text = substr($text, 1);
if ($enc === 0) return utf8_encode($text); // ISO-8859-1
if ($enc === 1) return $text; // UTF-16 with BOM
if ($enc === 2) return $text; // UTF-16 BE
if ($enc === 3) return $text; // UTF-8
}
}
return "未找到标题帧";
}
WAV文件(RIFF格式)结构:
php读取二进制文件提取WAV参数:
function getWavInfo($file) {
$fp = fopen($file, "rb");
$riff = fread($fp, 12);
if (substr($riff,0,4) !== "RIFF" || substr($riff,8,4) !== "WAVE") {
fclose($fp);
return "非WAV文件";
}
// 查找"fmt "块
while (!feof($fp)) {
$chunkId = fread($fp, 4);
if ($chunkId === "data") break;
$chunkSize = unpack("V", fread($fp, 4))[1];
if ($chunkId === "fmt ") {
$format = unpack("v", fread($fp, 2))[1];
$channels = unpack("v", fread($fp, 2))[1];
$sampleRate = unpack("V", fread($fp, 4))[1];
$byteRate = unpack("V", fread($fp, 4))[1];
$blockAlign = unpack("v", fread($fp, 2))[1];
$bitsPerSample = unpack("v", fread($fp, 2))[1];
fclose($fp);
return [
"channels"=>$channels,
"sampleRate"=>$sampleRate,
"bitsPerSample"=>$bitsPerSample,
"format"=>$format
];
} else {
fseek($fp, $chunkSize, SEEK_CUR);
}
}
fclose($fp);
return "未找到fmt块";
}
MySQL支持4种BLOB类型:
| 类型 | 最大长度 | 适用场景 |
|---|---|---|
| TINYBLOB | 255字节 | 小图标、短文本 |
| BLOB | 65KB | 图片缩略图 |
| MEDIUMBLOB | 16MB | 高清图片 |
| LONGBLOB | 4GB | 视频、大文件 |
php读取二进制文件写入BLOB(预处理):
$pdo = new PDO("mysql:host=localhost;dbname=test", "user", "pass");
$stmt = $pdo->prepare("INSERT INTO files (name, data) VALUES (:name, :data)");
$fp = fopen("document.pdf", "rb");
$data = fread($fp, filesize("document.pdf"));
fclose($fp);
$stmt->bindParam(":name", "document.pdf");
$stmt->bindParam(":data", $data, PDO::PARAM_LOB);
$stmt->execute();
php读取二进制文件从BLOB读取:
$stmt = $pdo->prepare("SELECT data FROM files WHERE id = :id");
$stmt->execute(["id" => 1]);
$data = $stmt->fetchColumn();
file_put_contents("output.pdf", $data); // 写入文件
PostgreSQL的BYTEA类型需转义/解转义:
php读取二进制文件安全写入BYTEA:
$conn = pg_connect("host=localhost dbname=test user=user");
$fp = fopen("image.png", "rb");
$data = fread($fp, filesize("image.png"));
fclose($fp);
$escaped = pg_escape_bytea($conn, $data);
pg_query($conn, "INSERT INTO images (data) VALUES ('$escaped')");
SQLite直接支持BLOB,无需特殊转义:
$pdo = new PDO("sqlite:database.db");
$stmt = $pdo->prepare("INSERT INTO files (data) VALUES (:data)");
$fp = fopen("archive.zip", "rb");
$data = fread($fp, filesize("archive.zip"));
fclose($fp);
$stmt->bindParam(":data", $data, PDO::PARAM_LOB);
$stmt->execute();
大文件(>100MB)不能一次性加载到内存,需分块读取:
function streamBinaryFile($file, $chunkSize = 8192) {
$fp = fopen($file, "rb");
if (!$fp) return;
while (!feof($fp)) {
$chunk = fread($fp, $chunkSize);
if ($chunk === false) break;
// 处理当前块
processChunk($chunk);
}
fclose($fp);
}
function processChunk($chunk) {
static $offset = 0;
// 示例:每块统计0字节数
$zeroCount = substr_count($chunk, "\x00");
echo "偏移 {$offset}: 0字节数 = {$zeroCount}\n";
$offset += strlen($chunk);
}
在大文件中定位特定字节序列(如PDF的`%EOF`):
function findMarker($file, $marker, $chunkSize = 1024*1024) {
$fp = fopen($file, "rb");
$buffer = "";
$markerLen = strlen($marker);
$offset = 0;
while (!feof($fp)) {
$chunk = fread($fp, $chunkSize);
$buffer .= $chunk;
$pos = strpos($buffer, $marker);
if ($pos !== false) {
fclose($fp);
return $offset + $pos;
}
// 保留最后(markerLen-1)字节用于跨块匹配
$buffer = substr($buffer, -$markerLen+1);
$offset += strlen($chunk);
}
fclose($fp);
return false;
}
$eofPos = findMarker("large.pdf", "%EOF\n");
echo "EOF位置:" . $eofPos;
对于超大文件,可使用`mmap`避免系统调用开销(需启用`php_mmap`扩展):
$fp = fopen("huge.bin", "rb");
$size = filesize("huge.bin");
$mapped = mmap_map($fp, 0, $size, PROT_READ);
// 直接像字符串一样操作
for ($i = 0; $i < $size - 4; $i++) {
if (substr($mapped, $i, 4) === "DATA") {
echo "找到DATA在偏移{$i}";
break;
}
}
mmap_unmap($mapped);
fclose($fp);
php读取二进制文件时,用`bin2hex`或`unpack`查看原始字节:
function hexDump($data, $length = 16) {
$result = "";
for ($i = 0; $i < strlen($data); $i += $length) {
$chunk = substr($data, $i, $length);
$hex = bin2hex($chunk);
$hex = str_pad($hex, $length * 2, " ");
$ascii = preg_replace('/[^[:print:]]/', '.', $chunk);
$result .= sprintf("%08X | %-48s | %s\n", $i, $hex, $ascii);
}
return $result;
}
$fp = fopen("test.bin", "rb");
echo hexDump(fread($fp, 32));
fclose($fp);
输出示例:
00000000 | 89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 52 | .PNG........IHDR 00000010 | 00 00 01 00 00 00 01 00 08 02 00 00 00 90 77 53 | ..............wS
使用Magic Number比扩展名更可靠:
function detectFileType($file) {
$fp = fopen($file, "rb");
$head = fread($fp, 16);
fclose($fp);
$magic = [
["JPEG", "\xFF\xD8\xFF"],
["PNG", "\x89PNG\x0D\x0A\x1A\x0A"],
["GIF", "GIF87a", "GIF89a"],
["PDF", "%PDF"],
["ZIP", "PK\x03\x04"],
["MP3", "ID3", "\xFF\xFB", "\xFF\xFA"]
];
foreach ($magic as $type => $patterns) {
if (is_array($patterns)) {
foreach ($patterns as $pat) {
if (strpos($head, $pat) === 0) return $type;
}
} else {
if (strpos($head, $patterns) === 0) return $type;
}
}
return "Unknown";
}
常见原因与解决方案: