php - 使用 PHP 验证损坏的 PDF

标签 php pdf corrupt

我想使用 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/

相关文章:

android - PdfRenderer 无法访问受密码保护的 pdf

javascript - 使用 pdf.js 显示具有透明背景的 pdf

java - 在java servlet中使用itextpdf生成pdf

php - 如何使用 WHERE = 'all' 编写 SQL 查询?

php - INSERT 和 UPDATE 语句将错误数据传递到数据库

php - 如何更改 XAMPP 中的 PHP 版本?

iphone - 如何检查下载的PNG图像是否损坏?

php - t 语法在第 1 行的 'GROUP BY bids.item' 附近使用

git - 如何破坏 Git 存储库?

java - Hibernate配置文件: Archive for required library persistence. xml无法读取