Search code examples
phpbitmapbase64encode

Decode Base-64 image string to bitmap - php


I have this php file : UploadToServer.php that decode base 64 an image string and save it as a bitmap image, when I test it with Postman and give it a string, this error popups, I am not very familiar with php. This is the UploadToServer.php :

<?php
if (isset($_POST('image_encoded'))) {
    $data = $_POST('image_encoded');
    $file_path = "C:/wamp/www/android_api/Uploads/test.jpg";
    // create a new empty file
    $myfile = fopen($filePath, "wb") or die("Unable to open file!");
        // add data to that file
    file_put_contents($filePath, base64_decode($data));
}

?>

And this is the error :

Fatal error: Cannot use isset() on the result of a function call (you can use "null !== func()" instead) 
in C:\wamp\www\android_api\UploadToServer.php on line 

Solution

  • You should use $_POST['image_encoded']. The $_POST identifier is actually an array, so the brackets should be square brackets. To test this yourself you could output print_r($_POST); once, as you'll never forget it again then.

    The code would then become:

    <?php
    if (isset($_POST['image_encoded'])) {
        $data = $_POST['image_encoded'];
        $file_path = "C:/wamp/www/android_api/Uploads/test.jpg";
        // create a new empty file
        $myfile = fopen($filePath, "wb") or die("Unable to open file!");
            // add data to that file
        file_put_contents($filePath, base64_decode($data));
    }
    
    ?>