我想使用 PHP 检测损坏的 PDF。我已经能够确定在未损坏的 pdf 文件末尾有标签“%%EOF”。我还检查了这个标签是否已损坏,但它没有出现。
我想到了在将 PDF 文件上传到我的服务器之前自动检查其有效性的想法。
<?php
$file = file('good.pdf');
$endfile= $file[count($file) - 1];
echo gettype($endfile),"\n";
echo $endfile,"\n";
?>
我得到了这个结果
string %%EOF
目前,一切似乎都很好,但我在比较结果时遇到了问题。
我测试了这段代码
<?php
$file = file('good.pdf');
$endfile= $file[count($file) - 1];
$n="%%EOF";
echo $endfile;
echo $n;
if ($endfile === $n) {
echo "good";
} else {
echo "corrupted";
}
?>
我得到了这个结果
%%EOF %%EOF corrupted
我知道 $endfile 和 $n 是字符串,但是当我想比较它时,我从来没有得到相等/匹配。我也试过 == 但结果是一样的。
我也这样试过:
<?php
$file = file('good.pdf');
$endfile= $file[count($file) - 1];
$var1val = $endfile;
$var2val = "%%EOF";
echo $var2val;
echo $var1val;
$n = strcmp($var1val,$var2val); // 0 mean that they are the same
echo $n;
if ($n == 0) {
echo "good";
} else {
echo "corrupted";
}
?>
但我得到了这个结果:
%%EOF %%EOF 1 corrupted
它给了我与 === 相同的结果。
我只测试了一个有效且未损坏的 pdf。你知道为什么这不起作用吗?也许您有其他方法使用 php 来检查 pdf 是否在我自动上传到我的服务器之前没有损坏?
最佳答案
阅读 http://php.net/manual/en/function.file.php :
Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. You need to remove the newlines to compare properly.
你需要做类似的事情:
<?php
$file = file('good.pdf');
$endfile= trim($file[count($file) - 1]);
$n="%%EOF";
if ($endfile === $n) {
echo "good";
} else {
echo "corrupted";
}
关于php - 使用 PHP 验证损坏的 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42163605/