Upload Image To Remote Server With PHP cURL & Handle File in Remote Server

Read {count} times since 2020

If you want to upload images to an external server which is uploaded to your site by a client, you are at the right tutorial.
For this submission we will use 2 files :

  1. form.php – The Page Where we will show the client the form. This file also sends the uploaded data to the external server.
  2. handle.php – The Page on the external server which receives the uploaded data from form.php using cURL.

We won’t copy the uploaded file by the client to our server, instead we will directly send the file to the external server. For sending we will encrypt the file with base64.
OK. Lets’ Start. First, Let’s create the FORM page :

<form enctype="multipart/form-data" encoding='multipart/form-data' method='post' action="form.php">
  <input name="uploadedfile" type="file" value="choose">
  <input type="submit" value="Upload">
if ( isset($_FILES['uploadedfile']) ) {
 $filename  = $_FILES['uploadedfile']['tmp_name'];
 $handle    = fopen($filename, "r");
 $data      = fread($handle, filesize($filename));
 $POST_DATA = array(
   'file' => base64_encode($data)
 $curl = curl_init();
 curl_setopt($curl, CURLOPT_URL, '<span style="color: red;">http://extserver.com/handle.php</span>');
 curl_setopt($curl, CURLOPT_TIMEOUT, 30);
 curl_setopt($curl, CURLOPT_POST, 1);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($curl, CURLOPT_POSTFIELDS, $POST_DATA);
 $response = curl_exec($curl);
 curl_close ($curl);
 echo "<h2>File Uploaded</h2>";

Now the code of the handle.php in external server where we sent the data using cURL :

$encoded_file = $_POST['file'];
$decoded_file = base64_decode($encoded_file);
/* Now you can copy the uploaded file to your server. */
file_put_contents('<span style="color: red;">subins</span>', $decoded_file);

The above code will receive the base64 encoded file and it will decode and put the image to its server folder. This might come in handy when you want to have your own user file storage system. This trick is used by ImgUr and other file hosting services like Google.

Show Comments