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
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
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;
No comments:
Post a Comment