[英]How does the function get_config_bytes() works?
I am using an extension regarding image uploading which use the function mentioned below and it is a common function which is normally used to get max_upload_size in bytes but I wonder how does it work? 我正在使用有关图像上传的扩展程序,该扩展程序使用下面提到的功能,它是一个常用功能,通常用于获取以字节为单位的max_upload_size,但我想知道它是如何工作的?
For example if $val = 20M then how does it multiply 20M * 1024 and get the correct output in bytes. 例如,如果$ val = 20M,那么它将如何乘以20M * 1024并获得正确的字节输出。
function get_config_bytes($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $this->fix_integer_overflow($val);
}
I am very curious about this because a while ago when I was using this function it was generating a Notice that non integer is multiply by an integer but now it is working fine. 我对此感到很好奇,因为前一段时间,当我使用此函数时,它正在生成一个非整数乘以整数但现在可以正常工作的通知。 I have no idea what happened.
我不知道发生了什么事。 Thanks
谢谢
There are two parts to this question. 这个问题有两个部分。
If you pass in 20M
, the switch/case
would match case 'm':
. 如果输入
20M
,则switch/case
将匹配case 'm':
Since the case
-blocks are missing the break;
由于
case
blocks缺少break;
in them, the matched case
-block will be executed and all other case
-blocks that comes after. 在它们中,将执行匹配的
case
-block以及之后的所有其他case
-block。 That would result in 20 * 1024 (from the m block) * 1024 (from the k-block)
这将导致
20 * 1024 (from the m block) * 1024 (from the k-block)
Here's a demo showing how the switch/case works in this context 这是一个演示,展示了在这种情况下开关/外壳如何工作
The above function will throw a notice on PHP7.1+. 上面的函数将在PHP7.1 +上引发通知。 Before, if you had a string like
20M
and you used it as a number (performing a mathematical operation on it), it would silently be converted to the number 20
. 以前,如果您有一个类似
20M
的字符串并将其用作数字(对其执行数学运算),它将被无提示地转换为数字20
。
From PHP 7.1, it would still work but would throw the notice "A non well formed numeric value encountered" unless you've turned off error reporting for notices. 从PHP 7.1开始,它仍然可以工作,但是会抛出“遇到一个格式不正确的数值”的通知,除非您已关闭通知的错误报告。
Here's an updated version that won't throw any notices: 这是不会引起任何通知的更新版本:
function get_config_bytes($val) {
$val = trim($val);
$last = substr($val, -1); // Get the last character
$val = rtrim($val, $last); // Trim away the last character which isn't a number
switch(strtolower($last)) {
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $this->fix_integer_overflow($val);
}
I'm sure that there are more efficient ways to do this, but this solves the issue either way. 我敢肯定有更有效的方法可以做到这一点,但这可以通过任何一种方式解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.