Reputation: 35
I'm passing image as a base64 string from a form. Then I would like to decode it, rename it and upload it to my server folder. I can't get this to work so obviously I'm doing something wrong here. Any help would be appreciated.
My code:
$image = $_POST['image-data'];//base64 string of a .jpg image passed from form:
$image = str_replace('data:image/png;base64,', '', $image);//Getting rid of the start of the string:
$image = str_replace(' ', '+', $image);
$image = base64_decode($image);
$ext = strtolower(substr(strrchr($image, '.'), 1)); //Get extension of image
$lenght = 10;
$image_name = substr(str_shuffle("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ"), 0, $lenght);
$image_name = $image_name . '.' . $ext; //New image name
$uploaddir = '/var/www/vhosts/mydomain.com/httpdocs/img/'; //Upload image to server
$uploadfile = $uploaddir . $image_name;
move_uploaded_file('$image', $uploadfile);
Upvotes: 0
Views: 3312
Reputation: 1574
Using file put content you can move files to folder
$file = $_POST['image-data'];
$pos = strpos($file, ';');
$type = explode(':', substr($file, 0, $pos))[1];
$mime = explode('/', $type);
$pathImage = "path to move file/".time().$mime[1];
$file = substr($file, strpos($file, ',') + 1, strlen($file));
$dataBase64 = base64_decode($file);
file_put_contents($pathImage, $dataBase64);
Upvotes: 1