0

How to save DATA URL like save $_FILES in php?

my code is:

$dataurl = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAB...."

$image_content = base64_decode(str_replace("#^data:image/\w+;base64,#i","", $dataurl)); // remove "data:image/png;base64,"
$tempfile = tmpfile(); // create temporary file
$filesize = fwrite($tempfile, $image_content); // fill data to temporary file
$metaDatas = stream_get_meta_data($tempfile);
$tmpFilename = $metaDatas['uri'];

$file = array(
    'name' => 'MyFile.jpg',
    'type' => 'image/jpeg',
    'tmp_name' => $tmpFilename,
    'error' => 0,
    'size' => $filesize,
);

move_uploaded_file($file['tmp_name'], $location);

The problem maybe in move_uploaded_file($file['tmp_name'], $location);

1 Answers1

0

Read the description in PHP guide for move_uploaded_file before using this function.

The important part is (qoute from the description):

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

The file you created was NOT uploaded via PHP HTTP POST upload mechanism, it was a temporary file you have created yourself, so you can not move it with this function.

If the data arrives as a Base64 encoded string, you can just write the file directly to the desired location. The move_uploaded_file function is ONLY for files uploads, and Base64 strings sent in the body are not files.

Ron Dadon
  • 2,666
  • 1
  • 13
  • 27