Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

php - http transfer file from server to server

with html forms we can upload a file from a client to a server with enctype="multipart/form-data", input type="file" and so on.

Is there a way to have a file already ON the server and transfer it to another server the same way?

Thanks for hints.

// WoW! This is the fastest question answering page i have ever seen!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When the browser is uploading a file to the server, it sends an HTTP POST request, that contains the file's content.

You'll have to replicate that.


With PHP, the simplest (or, at least, most used) solution is probably to work with curl.

If you take a look at the list of options you can set with curl_setopt, you'll see this one : CURLOPT_POSTFIELDS (quoting) :

The full data to post in a HTTP "POST" operation.
To post a file, prepend a filename with @ and use the full path.
This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.
If value is an array, the Content-Type header will be set to multipart/form-data.


Not tested,but I suppose that something like this should do the trick -- or at least
help you get started :

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/your-destination-script.php");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        'file' => '@/..../file.jpg',
         // you'll have to change the name, here, I suppose
         // some other fields ?
));
$result = curl_exec($ch);
curl_close($ch);

Basically, you :

  • are using curl
  • have to set the destination URL
  • indicate you want curl_exec to return the result, and not output it
  • are using POST, and not GET
  • are posting some data, including a file -- note the @ before the file's path.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...