PHP中的If语句帮助


If-Statement Help in PHP

所以出于某种原因,这对我来说没有意义。

我想做的是显示两件事中的一件:

  1. 如果文件夹中只有一个图像的文件大小太大,请显示上面的错误消息
  2. 如果所有文件大小都正常,则显示一些HTML代码

此外,如果我希望限制为5MB,我的阈值是否正确?

<?php
$threshold = 5368709120;
$path = 'dir/'.$username;
foreach (glob($path."/{*.gif,*.jpg,*.jpeg,*.png}",GLOB_BRACE|GLOB_NOSORT) as $filename)  
{
    $size = filesize($filename);
    if ($size > $threshold) {
        exit('One or more of your photos are larger than 5MB. Resize your photos and try again.');
    }
}
?>

不,您的文件限制实际上是5GB:

5 -> bytes = 5
5 * 1024 -> kilobytes = 5,120
5 * 1024 * 1024 -> megabytes = 5,242,880
5 * 1024 * 1024 * 1024 -> gigabytes => 5,368,709,120

为了方便用户,您应该告诉用户哪个文件太大,并在退出前检查所有文件。假设用户不知道有5 meg的限制,并上传了50个文件。49太大了。你只是告诉用户有问题,而不是问题的原因。现在他们必须重新上传一个文件,然后再上传一次。现在有48个文件太大了,到处都是。

像这样的东西更适合

$limit = 5 * 1024 * 1024; // 5 meg
$errors = array();
foreach (glob($path."/{*.gif,*.jpg,*.jpeg,*.png}",GLOB_BRACE|GLOB_NOSORT) as $filename)  
   if (filesize($filename) > $limit) {
      $errors[] = $filename
   }
}
if (count($errors) > 0) {
   echo "The following files are too large: <ul>";
   echo implode("</li><li>", $errors);
   echo "</ul>";
} else {
   echo "Everything A-OK!";
}

我会使用以下内容,以便代码的意图始终清晰:

$threshold = 5 * 1024 * 1024; // 5MB

您的问题是,您没有在文件的完整路径上调用filesize(),只是在文件名上调用。这意味着,如果文件位于当前工作目录之外(看起来是这样),它将无法工作显然这与glob()不符。

关于is my threshold correct if I want the limit to be 5MB,确保它正确的简单方法是计算它,而不是硬编码:

$threshold = 1024 * 1024 * 5;

事实上,您正在寻找超过5 GB的文件。

<?php
$threshold = 5 * 1024 * 1024; // 5MB
$path = 'dir/'.$username;
foreach (glob($path."/{*.gif,*.jpg,*.jpeg,*.png}",GLOB_BRACE|GLOB_NOSORT) as $filename)  
{
    $size = filesize($filename);
    if ($size > $threshold) {
        exit('One or more of your photos are larger than 5MB. Resize your photos and try      
again.');
    }
}
?>
//display html code here

只需在foreach循环之后的任何位置添加html代码,因为它已经传递了if//$size>$threshold检查(并且已经检查了for循环中的所有图像

您的代码是正确的,尽管您的阈值不是。5368709120是5GiB,您需要5000000

mega只是百万的另一个词