23

I'm not asking about uploading a file from a browser to a php script, there's plenty of tutorials about that already. I'm asking about this:

I have a php script that has accepted a file from the user, and the file is currently on the hard disk of server 1. I want to upload the file from server 1 to a php script on server 2, using the regular Http post protocol, so the php script on server 2 can be written as a standard file-upload handler.

I cannot find any tutorial on the internet, because they all talk about browser->server1. The tutorials about php upload all talk about ftp, but I don't want to use that protocol.

Please help?

3 Answers 3

30

You can use CURL for this. Something like this should do it.

$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '@/path/to/file.txt'));
curl_setopt($ch, CURLOPT_URL, 'http://server2/upload.php');
curl_exec($ch);
curl_close($ch);

You can then handle the the server2 part as a regular file upload. See curl_setopt() for more information on those options.

Sign up to request clarification or add additional context in comments.

1 Comment

I just needed this again for another project, and I made an error in my new code that was so subtle I had to post it here: it is very important that the CURLOPT_POST,true is BEFORE the POSTFIELDS when that is set to an array!
9

You could use SOAP to send the file from one server to the other.

Receiving server:

<?php
$server = new Soap_Server( null, array('uri'=>'somerui') );
$server->addFunction( 'receiveFile' );
function receiveFile( $file ) {
   file_put_contents( 'somepath', base64_decode( $file ) );
}
?>

Sending server:

<?php
$client = new Soap_Client( null, array('uri'=>'somerui') );
$client->receiveFile( base64_encode( file_get_contents( 'somepath' ) );
?>

3 Comments

Hehe, a plus one for originality :-)
I wrote this years ago, I was still pretty new. Now I shudder in horror that I suggested this. Use the accepted answer.
No worries, I didn't use it, but it was original as I said :-)
2

You need two Scripts.

First script that will in way emulate browser behavior, it will take a file and send it to seconds script, that will handles it just like regular file upload script.

My guess you have to use "http_post_fields" for the first script, it seems to handle files. https://www.php.net/manual/en/function.http-post-fields.php

Good Luck.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.