[英]If-Statement Help in PHP
因此出于某种原因,这对我来说毫无意义。
我想做的是显示2件事情之一:
另外,如果我希望限制为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.');
}
}
?>
不,您的文件限制实际上是5 GB:
5 -> bytes = 5
5 * 1024 -> kilobytes = 5,120
5 * 1024 * 1024 -> megabytes = 5,242,880
5 * 1024 * 1024 * 1024 -> gigabytes => 5,368,709,120
为了方便用户使用,您应该告诉用户WHICH文件太大,并在退出前检查所有文件。 假设用户不知道限制为5兆,并上传了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
,确保该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循环中的所有图像
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.