php验证post提交的base64图片大小

PHP 投稿 74700 0 评论

php验证post提交的base64图片大小

客户端直接提交过来的图片base64字符串,需要在php中进行大小限制,那我们在PHP中怎么得到原图片的大小并对其进行大小验证呢?

下面这个方法将会帮你解决这个问题。

/**
 * base64大小验证
 * @param string $base64
 * @param int    $maxSize
 * @return bool
 */
public function base64sizeValidation(string $base64, int $maxSize)
{
    $base64 = str_replace('data:image/jpeg;base64,', '', $base64);
    $base64 = str_replace('=', '', $base64);
    $imgLen = strlen($base64);
    $fileSize = $imgLen - ($imgLen / 8) * 2;
    $fileSize = number_format(($fileSize / 1024), 2);
    if ($fileSize > $maxSize) {
        return false;
    }
    return true;
}

编程笔记 » php验证post提交的base64图片大小

赞同 (79) or 分享 (0)
游客 发表我的评论   换个身份
取消评论

表情
(0)个小伙伴在吐槽