php 8.6可以通过proc_open()以参数数组调用tesseract,把图片识别结果保存为utf-8文本,再检查进程退出状态。中文识别还需要chi_sim语言数据,不能只安装英文引擎。下面以linux、gnu timeout和tesseract命令行程序为前提,不要求安装某个同名php扩展。

官方文档:Command Line Usage
先验证命令和语言数据
在实际运行PHP的环境检查程序位置及已安装语言。下面代码约定程序在/usr/bin/tesseract、timeout在/usr/bin/timeout;若安装位置不同,应由管理员修改固定配置,不接受请求参数指定命令。
command -v tesseract command -v timeout tesseract --version tesseract --list-langs
语言列表至少包含chi_sim和eng。使用与引擎匹配的官方traineddata,把TESSDATA_PREFIX或--tessdata-dir配置到实际安装位置;不要把“找不到语言数据”当成图片内容为空。

官方文档:Introduction
固定输入路径并隔离输出
准备private/input.png和仅应用可写的private目录。保存ocr.php,参数数组避免经过shell拼接;标准输出及错误输出分别写文件,避免两个管道互相等待。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
<?php
$input = __DIR__.'/private/input.png';
if (!is_file($input) || !is_readable($input) || filesize($input)>10*1024*1024) {
throw new RuntimeException('Invalid image');
}
$type = (new finfo(FILEINFO_MIME_TYPE))->file($input);
if (!in_array($type, ['image/png','image/jpeg'], true)) throw new RuntimeException('Unsupported type');
$dir = __DIR__.'/private/ocr-'.bin2hex(random_bytes(8));
if (!mkdir($dir, 0700)) throw new RuntimeException('Cannot create work directory');
$output = $dir.'/output.txt'; $error = $dir.'/error.txt';
$command = ['/usr/bin/timeout','30s','/usr/bin/tesseract',
$input,'stdout','-l','chi_sim+eng','--psm','6'];
$process = proc_open($command, [
0=>['pipe','r'], 1=>['file',$output,'w'], 2=>['file',$error,'w']
], $pipes);
if (!is_resource($process)) throw new RuntimeException('Cannot start OCR');
fclose($pipes[0]);
$status = proc_close($process);
if ($status !== 0) {
throw new RuntimeException($status === 124 ? 'OCR timed out' : 'OCR failed; inspect private error file');
}
$text = file_get_contents($output, false, null, 0, 4*1024*1024+1);
if ($text === false || strlen($text)>4*1024*1024) throw new RuntimeException('Output too large');
header('Content-Type: text/plain; charset=utf-8');
echo $text;按版面选择识别模式
--psm 6适合单个相对规整的文本块,并不适合所有票据、表格或多栏页面。先用实际图片检查语言、方向和版面;改变-l语言顺序也可能影响输出。文本为空、乱码或漏字时,应同时检查图像清晰度、语言数据和错误文件,而不是保证加一个参数就能识别准确。
立即学习“PHP免费学习笔记(深入)”;
限制进程资源和敏感文件
timeout限制运行时长,不能替代容器或系统的内存、CPU和磁盘配额。OCR工作应放在受限进程中,输入与输出按业务保留周期清理;错误文件留在私有目录,不能把含个人信息的图片或识别结果写进公开日志。


















