如何告知FFmpeg /tmp/phpFm6H79是安全文件名?
解决FFmpeg concat协议的“不安全文件名”问题
问题场景
执行以下FFmpeg命令时:
ffmpeg -y -f concat -i '/tmp/phpFm6H79' -c:v libx264 -vsync vfr '/home/hans/projects/test/output2.mp4'
出现关键错误:
[concat @ 0x55b070e9ff40] Unsafe file name '/tmp/phpbshsmF' /tmp/phpFm6H79: Operation not permitted
临时文件由PHP的tmpfile()生成,代码如下:
$ffmpegInputTxtFileHandle = tmpfile(); $ffmpegInputTxtFilePath = stream_get_meta_data($ffmpegInputTxtFileHandle)['uri'];
需求说明:需保证线程安全,且依赖tmpfile()在脚本退出(甚至PHP崩溃)时自动删除文件的特性,不想更换临时文件方案,希望让FFmpeg认可该文件为安全文件。
尝试过给文件名添加.txt后缀的方案,但仍报错,代码如下:
$ffmpegInputTxtFileHandle = tmpfile(); $ffmpegInputTxtFilePath = stream_get_meta_data($ffmpegInputTxtFileHandle)['uri'] . ".txt"; fclose($ffmpegInputTxtFileHandle); $ffmpegInputTxtFileHandle = fopen($ffmpegInputTxtFilePath, 'w+b'); register_shutdown_function(function () use ($ffmpegInputTxtFileHandle, $ffmpegInputTxtFilePath) { @fclose($ffmpegInputTxtFileHandle); @unlink($ffmpegInputTxtFilePath); });
解决方案
1. 给FFmpeg添加-safe 0参数(优先推荐)
直接修改FFmpeg命令,在-f concat之后添加-safe 0,禁用concat协议的安全检查:
ffmpeg -y -f concat -safe 0 -i '/tmp/phpFm6H79' -c:v libx264 -vsync vfr '/home/hans/projects/test/output2.mp4'
这个参数会允许FFmpeg读取任意路径、任意命名的文件,完全保留tmpfile()的线程安全和自动删除特性,不需要改动PHP代码,是最直接有效的解决办法。
2. 验证临时文件权限(辅助排查)
如果添加参数后仍有问题,可检查临时文件的权限是否正确:
var_dump(decoct(fileperms($ffmpegInputTxtFilePath)));
正常输出应为0100600,表示文件所有者拥有读写权限,确保FFmpeg进程能读取该文件。
内容的提问来源于stack exchange,提问作者hanshenrik
相关产品推荐
相关产品推荐

