Cas
Cas

Reputation: 356

How to send base64 image to server - PHP

I'm sending a base64 string from an Android app to a server through a PHP file.
I got this from a tutorial video:

<?php
    require 'Init.php';
    header('Content-type : bitmap; charset=utf8');

    if(isset($_POST['encoded_string'])){

        $encoded_string = $_POST['encoded_string'];
        $image_name = $_POST['image_name'];

        $decoded_string = base64_decode($encoded_string);

        $path = 'ProfileIcons/' .$image_name;

        $file = fopen($path, 'wb');

        $is_written = fwrite($file, $decoded_string);
        fclose($file);
    }
?>

It's storing the image in the directory but when you open, it has no image. It's a blank png. Is there something wrong with the code? If so, what should I use? Thanks.

Upvotes: 1

Views: 741

Answers (1)

free6om
free6om

Reputation: 448

There are several points you should check:

1.Make sure the server has received the base64 string

$encoded_string = $_POST['encoded_string'];

Check the length of $encoded_string, it should have the same length as the android client says.

  1. Make sure the decoding works

    $decoded_string = base64_decode($encoded_string);

Check the length of $decoded_string, it should NOT be zero or something odd.

  1. Make sure the file written works

    $is_written = fwrite($file, $decoded_string);

$is_written should be the length of the data that has been written to the file, if it is a false, then something is wrong.

Upvotes: 2

Related Questions