Save a PNG image from a base64 data string with PHP

We can extract the base64 image data from that string, decode it and save it to disk, don't need GD since it already is a png.

<?php
    // requires php5
    define('UPLOAD_DIR', 'images/');
    $img = $_POST['img'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.png';
    $success = file_put_contents($file, $data);
    print $success ? $file : 'Unable to save the file.';
?>
0.00 avg. rating (0% score) - 0 votes