Upload Image File To Remote Server With PHP cURL

How to upload image file to remote server with PHP cURL

In this example we learn how to upload static files to remote server using PHP cURL library.

We must know following functionality before we continue this example

Files and Folders

Download Example

For this example we use three files

  • uploader.php -that receives the files on to the remote server.
  • handler.php -is used to web based client to upload the file.
  • curl_handler.php -PHP cURL uploading client to upload file.

Since we use same host to both local and remote server ,we create separate directories

  • local_files/ - these files will be uploaded to the remote server ,means to uploaded_files directory.
  • uploaded_files/ – these files are from the uploading client from both web based and PHP cURL based.

uploader.php

 
$upload_directory=dirname(__FILE__).'/uploaded_files/';
//check if form submitted
if (isset($_POST['upload'])) {  
    if (!empty($_FILES['my_file'])) { 
			//check for image submitted
    		if ($_FILES['my_file']['error'] > 0) { 
			// check for error re file
            echo "Error: " . $_FILES["my_file"]["error"] ;
        } else {
			//move temp file to our server            
			move_uploaded_file($_FILES['my_file']['tmp_name'], 
			$upload_directory . $_FILES['my_file']['name']);	
			echo 'Uploaded File.';
        }
    } else {
	        die('File not uploaded.'); 
			// exit script
    }
}

handler.php

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form action="uploader.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
  <input type="file" name="my_file" id="my_file" />
  <input type="submit" name="upload" id="upload" value="Upload" />
</form>
</body>
</html>

curl_handler.php

$local_directory=dirname(__FILE__).'/local_files/';
 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
    curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_URL, 'http://localhost/curl_image/uploader.php' );
	//most importent curl assues @filed as file field
    $post_array = array(
        "my_file"=>"@".$local_directory.'shreya.jpg',
        "upload"=>"Upload"
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array); 
    $response = curl_exec($ch);
	echo $response;

Download Example

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">