PHP Upload Image to Remote Server with Curl

Php upload image to remote server with cURL

Here's a possible solution;

  • Handle the upload on your web server and move the uploaded file to a local temp location
  • Then make a curl POST request to remote server and tell it what the uploaded file name & data is; as base64_encoded string
  • Remote server script receives the upload as a standard http post
  • All it now has to do is decode the file data, save it as the specified file name

So, this is how the solution looks like:

Sorry, i did not test this, but it should work.

index.php

<?php

// Handle upload
if(isset($_POST["submit"]))
{
// Move uploaded file to a temp location
$uploadDir = '/var/www/uploads/';
$uploadFile = $uploadDir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadFile))
{
// Prepare remote upload data
$uploadRequest = array(
'fileName' => basename($uploadFile),
'fileData' => base64_encode(file_get_contents($uploadFile))
);

// Execute remote upload
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://1.1.1.1/receiver.php');
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $uploadRequest);
$response = curl_exec($curl);
curl_close($curl);
echo $response;

// Now delete local temp file
unlink($uploadFile);
}
else
{
echo "Possible file upload attack!\n";
}
}

?>

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="index.php" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>

Then, on the receiver.php, you can do the following:

// Handle remote upload
if (isset($_POST['fileName']) && $_POST['fileData'])
{
// Save uploaded file
$uploadDir = '/path/to/save/';
file_put_contents(
$uploadDir. $_POST['fileName'],
base64_decode($_POST['fileData'])
);

// Done
echo "Success";
}

Uploading url file to remote server using curl

Well do it in this way.

  1. First download that file from url provided by user.
  2. Upload that image on http://1234.4321.67.11/upload.php
  3. And delete that file after successfully uploaded on server.

This might help you for uploading image on server using cURL : https://stackoverflow.com/a/15177543/1817160

And this might help you in understanding how to download image from url :
Copy Image from Remote Server Over HTTP

PHP - Upload an image file to other domain with CURL

No code in this answer, just a work flow example that will bypass curl:

  1. User posts a form with the uploaded file to "site 1", as per normal.
  2. "site 1" processes the form and the uploaded file. The file is placed in a temp directory which is web accessible.
  3. On "site 1", once the uploaded file has been checked, make a file_get_contents('http://site2.loc/pullfile.php?f=filename&sec=checkcode') call. The contents of pullfile.php will do just that, pull the file from "site 1" to "site 2".
  4. The return from file_get_contents() can be checked for an error return from the "site 2" pullfile.php and on error, deal with it. No error, remove the temp file.
  5. The &sec=checkcode could be used to confirm the file has been uploaded successfully to "site 2". It could be an MD5 of the file or something else you come up with.

Just an idea.

Edit: Some sample code to help make things clearer, maybe :]

// ---- Site 1, formprocess.php ----

// Your form processing goes here, including
// saving the uploaded file to a temp dir.

// Once the uploaded file is checked for errors,
// you need move it to a known temp folder called
// 'tmp'.

// this is the uploaded file name (which you would
// have got from the processed form data in $_FILES
// For this sample code, it is simple hard-coded.
$site1File = 'test.jpg';

$site1FileMd5 = md5_file('./tmp/'.$site1File);

// now make a remote request to "site 2"
$site2Result = file_get_contents('http://'.SITE_2_URL.'/pullfile.php?f='.$site1File.'&md5='.$site1FileMd5);

if ($site2Result == 'done') {
unlink('./tmp/'.$site1File);
} else {
echo '<p>
Uploaded file failed to transfer to '.SITE_2_URL.'
- but will be dealt with later.
</p>';
}

And this will be the 'pullfile.php' on site 2

// ----- Site 2, pullfile.php -----

// This script will pull a file from site 1 and
// place it in '/uploaded'

// used to cross-check the uploaded file
$fileMd5 = $_GET['md5'];
$fileName = basename($_GET['f']);

// we need to pull the file from the './tmp/' dir on site 1
$pulledFile = file_get_contents('http://'.SITE_1_URL.'/tmp/'.$fileName);

// save that file to disk
$result = file_put_contents('./uploaded/'.$fileName,$pulledFile);
if (! $result) {
echo 'Error: problem writing file to disk';
exit;
}

$pulledMd5 = md5_file('./uploaded/'.$fileName);
if ($pulledMd5 != $fileMd5) {
echo 'Error: md5 mis-match';
exit;
}

// At this point, everything should be right.
// We pass back 'done' to site 1, so we know
// everything went smooth. This way, a 'blank'
// return can be treated as an error too.
echo 'done';
exit;

php/curl - get extension of image on remote server using headers

solution

$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec ($ch);

$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
echo $content_type;

Thanks to Mario!

How to upload file from local to server using curl in php?

I think you miss important information.

fopen ("user.com/user/fromLocal.txt", 'w+')

this means nothing.
To send a file to the server the server has to be configured to accept a POST request and you have to send the file through that endpoint.

If you have a form, do you send it to: "user.com/user/fromLocal.txt" ??
You have to create the form data with curl and send it to a server ready to accept your request. There are different ways to accomplish that. And the most simple is exactly to send a form using curl and not the HTML. But absolutly you cannot write a file like that in a server.

PHP - Upload image from external server

You must first download the image to your server then use that path. Here's an example of downloading the image to a temporary file:

$temp_name = tempnam(sys_get_temp_dir(), "external");
copy($file, $temp_name);
// ...
$args[basename($file)] = '@' . realpath($temp_name);

PHP: upload file from one server to another server

As a PHP developer, you may already be familiar with PHP's most handy file system function, fopen. The function opens a file stream and returns a resource which can then be passed to fread or fwrite to read or write data. Some people don't realize though that the file resource doesn't necessarily have to point to a location on the local machine.

Here's an example that transfers a file from the local server to an ftp server:

$file = "filename.jpg";
$dest = fopen("ftp://username:password@example.com/" . $file, "wb");
$src = file_get_contents($file);
fwrite($dest, $src, strlen($src));
fclose($dest);

A listing of different protocols that are supported can be found in Appendix M of the PHP manual. You may wish to use a protocol that employs some encryption mechanism such as FTPS or SSH depending on the network setup and the sensitivity of the information you’re moving.

The curl extension makes use of the Client URL Library (libcurl) to transfer files. The logic of implementing a curl solution generally follows as such: first initialize a session, set the desired transfer options, perform the transfer and then close the session.

Initializing the curl session is done with the curl_init function. The function returns a resource you can use with the other curl functions much as how a resource is obtained with fopen in the file system functions.

The upload destination and other aspects of the transfer session are set using curl_setopt which takes the curl resource, a predefined constant representing the setting and the option’s value.

Here's an example that transfers a file from the local host to a remote server using the HTTP protocol's PUT method:

$file = "testfile.txt";

$c = curl_init();
curl_setopt($c, CURLOPT_URL, "http://example.com/putscript");
curl_setopt($c, CURLOPT_USERPWD, "username:password");
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_PUT, true);
curl_setopt($c, CURLOPT_INFILESIZE, filesize($file));

$fp = fopen($file, "r");
curl_setopt($c, CURLOPT_INFILE, $fp);

curl_exec($c);

curl_close($c);
fclose($fp);

A list of valid options for curl can be found in the php documentation.

The ftp extension allows you to implement client access to ftp servers. Using ftp to transfer a file is probably overkill when options like the previous two available... ideally this extension would be best used more advanced functionality is needed.

A connection is made to the ftp server using ftp_connect. You authenticate your session with the ftp server using ftp_login by supplying it a username and password. The file is placed on the remote server using the ftp_put function. It accepts the name of the destination file name, the local source file name, and a predefined constant to specify the transfer mode: FTP_ASCII for plain text transfer or FTP_BINARY for a binary transfer. Once the transfer is complete, ftp_close is used to release the resource and terminate the ftp session.

$ftp = ftp_connect("ftp.example.com");
ftp_login($ftp, "username", "password");
ftp_put($ftp, "destfile.zip", "srcfile.zip", FTP_BINARY);
ftp_close($ftp);


Related Topics



Leave a reply



Submit