一个PHP程序员的个人博客-司空如风

PHP base64 转成对应格式的图片

// 匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
    $type = $result[2];
    $ban_ext = array(
        'php',
        'asp',
        'asp',
        'html',
        'htm',
        'js',
        'shtml',
        'aspx'
    );
    if (in_array($type, $ban_ext)) {
        $this->returnMsg(0, "非法文件格式");
    }
    $new_file = "." . __ROOT__ . '/upload/';
    if (! file_exists($new_file)) {
        // 检查是否有该文件夹,如果没有就创建,并给予最高权限
        mkdir($new_file, 0700);
    }
    $filename = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT) . ".{$type}";

    $new_file = $new_file . $filename;
    if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {                  
       $this->returnMsg(1, "", array(
            "url" => $new_file
        ));
    } else {
        $this->returnMsg(0, "上传失败");
    }
}

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »