dongyi9298 2017-02-10 16:00
浏览 190
已采纳

使用PHP验证损坏的PDF

I would like to detect corrupted PDF using PHP. I have been able to determine that on not corrupted pdf I have the tag "%%EOF" at the end of the file. I also checked for this tag on corrupted and it not appear.

I had the idea to automatically checked the validty of my PDF file before uploading it to my server.

<?php
$file = file('good.pdf');

$endfile= $file[count($file) - 1];

echo gettype($endfile),"
";
echo $endfile,"
";

?>

I get this result

string %%EOF 

For now, everything seems to be fine, but I have an issue when comparing the results.

I tested this code

<?php
$file = file('good.pdf');
$endfile= $file[count($file) - 1];
$n="%%EOF";

echo $endfile;
echo $n;

if ($endfile === $n) {
    echo "good";

} else {
    echo "corrupted";
}

?>

I get this result

%%EOF %%EOF corrupted

I know that $endfile and $n are string but when i want to compare it, I never get the equality/match. I also tried with == but the result is the same.

I also tried it like that :

<?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";
}

?>

but I get this result :

%%EOF %%EOF 1 corrupted

It gave me the same result with === .

I only tested with a working and not corrupted pdf. Do you know why this is not working ? Maybe you have other methods using php to check if the pdf is not corrupted before I automatically upload it to my server ?

</div>
  • 写回答

2条回答 默认 最新

  • dplece1882 2017-02-10 16:17
    关注

    Reading 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.

    You need to do something like:

    <?php
    $file = file('good.pdf');
    $endfile= trim($file[count($file) - 1]);
    $n="%%EOF";
    
    
    if ($endfile === $n) {
        echo "good";
    
    } else {
        echo "corrupted";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法