How to upload an image by using php curl request

php

Posted on 15 Dec 15 by Vickey
  1940



If you are facing problem to upload an image by using curl request you can use this code. In this code I convert an image in base64 string and pass it to a different server in a curl request and there I decode it and create an image file from this string.

here is my html form

<form method="post" id="SampleForm" action="">
	<input type="file" onchange="covertImageInBase64();" id="imageFile"/>
	<input type="text" name="image" id="image">
	<input type="submit" value="Submit">
</form>

and now convert the image in base64 string

function covertImageInBase64()
{
    var imageFile = document.getElementById("imageFile").files;
    if (imageFile.length > 0)
    {
        var imageFileUpload = imageFile[0];
        var readFile = new FileReader();
        readFile.onload = function(fileLoadedEvent) 
        {
            var base64image = document.getElementById("image");
            base64image.value = fileLoadedEvent.target.result;
        };
        readFile.readAsDataURL(imageFileUpload);
    }
}

now on submit the form send it in a curl request

if(isset($_POST['image'])){
	$curlUrl='localhost/curlfile.php';	
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL, $curlUrl);
	curl_setopt($ch,CURLOPT_POST, 1);
	curl_setopt($ch,CURLOPT_POSTFIELDS, 'image='.$_POST['image']);
	$result = curl_exec($ch);
	curl_close($ch);
}

In curlfile.php file change it into image

$base64Image=$_POST['image'];
$newImageName= time();
$getImageMimeType=substr($base64Image, 5, strpos($base64Image, ';')-5);
$imageTypeArray=array('image/png'=>'png','image/jpeg'=>'jpg','image/gif');
$imgExt=$imageTypeArray[$getImageMimeType];
$newImageName=$newImageName.'.'.$imgExt;
list($type, $base64Image) = explode(';', $base64Image);
list(, $base64Image)      = explode(',', $base64Image);
$base64Image = base64_decode($base64Image);
file_put_contents('path to your directory'.$newImageName, $base64Image);
echo $avatar=$newImageName;

 


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com