How to upload an image by using php curl request


Posted on 15 Dec 15 by Vickey

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">

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 =;

now on submit the form send it in a curl request

	$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);

In curlfile.php file change it into image

$newImageName= time();
$getImageMimeType=substr($base64Image, 5, strpos($base64Image, ';')-5);
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 :)