youeye
youeye

Reputation: 727

File uploading with php to two different servers?

I want to upload two different files to two different servers located in two different locations.

I have one image file which I want to upload onto my server where the PHP script is hosted and the other video file which I want to upload to some other server not on the same server.

Is there any possibility of doing this? Can anyone explain me how to achieve this if possible?

Upvotes: 0

Views: 656

Answers (2)

Nathan Osman
Nathan Osman

Reputation: 73165

This is impossible with an HTML form - the action attribute only allows for a single URL to be specified.

You have a couple of choices here:

  • Use JavaScript to create two <iframe>s, fill them with the data you want to submit in a <form>, and then call .submit() on each of the forms. Since you mentioned that the two locations are on different servers, I'll assume they are on different domains as well - and therefore you will run into trouble with the same-origin policy on at least one of the forms. For that reason, and the fact that quite a few users have JavaScript turned off in their browser, I recommend avoiding this option if possible.

  • Have the PHP script on your server take the $_POST data and send a POST request with that information to the other server. This can easily be done with PHP's cURL extension, for example. This can be done as follows:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://...');
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
    curl_exec($ch);
    curl_close($ch);
    

Upvotes: 1

Hernan Velasquez
Hernan Velasquez

Reputation: 2820

There are many ways to solve this issue. For example you can have 2 forms, one per server like:

<form action="http://server1/upload_server1.php" method=post ...>
</form>

And

<form action="http://server2/upload_server2.php" method=post ...>
</form>

But this will not be user friendly.

You can also upload all the files to one of the servers, and transfer the files you want to the second server using for example the php ftp library:

http://php.net/manual/en/book.ftp.php

But there may be an overhead on the time used to transfer the files between the servers.

For sure you will find more answers here. Pick the one you like most :)

Upvotes: 1

Related Questions