把图片的base64编码转成文件并保存到本地

<?php
/**
 * 把图片的base64编码转成文件并保存到本地
 *
 * @param string $base64 图片的base64编码
 * @return mixed 成功保存图片文件则返回文件路径,否则返回false
 */
function base64_to_img($base64)
{
    // 按照逗号分隔base64编码
    $explode = explode(',', $base64);
    if (count($explode) !== 2) {
        return false;
    }

    // 获取文件类型
    preg_match_all('/data:image\/(.*)?;base64/s', $explode[0], $matches);
    if (!isset($matches[1][0]) || $matches[1][0] === '') {
        return false;
    }
    $ext = $matches[1][0];

    // 检查数据部分的合法性
    $data = $explode[1];
    if ($data !== base64_encode(base64_decode($data, true))) {
        return false;
    }

    //再次检查数据部分的合法性
    $pattern = '~^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$~';
    if (preg_match($pattern, $data) !== 1) {
        return false;
    }

    // 保存图片到本地
    $file = __DIR__ . "/base64.{$ext}";
    $result = file_put_contents($file, base64_decode($data)); // 重点:需要对base64编码的『数据部分』进行decode处理
    return $result === false ? false : $file;
}

$base64 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAABICAMAAAAJWw0gAAABC1BMVEVYN58+FJf///8lAIpXNp9ZOZ83DZVcO6E/FJg+FJU8EZYpAIwiAIY+Epg6D5c6D5VEH5QjAIkcAIQ1CJMXAILDt959YrZePqEdAIbg2e3HvOBMKJtKJ5ZvVKxZN55UMZ0fAIa7r9mNdr51WLMxBZGxotPu6vTs6PSWgMNLKJhBGZhAG5I8F5AvA402D4zQx+RyUqxlRqpePKZcOKZPLJ1GIZk4DZc2DJH39vrUzOedicd8ZbRpS61jQqhmSadTLqJJJJXx7/fo5PHY0OfJv+G2qNemlc5tUK47E5P9/f708/jAst2rm8+Re8GCZrl4X7I6D5M6E48UAH/7+vza0+qEbLoPAH0/GZEAAHPVDB5hAAAD80lEQVRo3u2WZ3faMBSGdYUnZhjbKSRQRhkBymiYDSMhu212Ov//L6kkMLETY5xzY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