使用PHP从远程服务器获取文件并复制到本地服务器的最佳方法

7
假设有一个文件在远程服务器上,可以无限制地下载,即您可以将该文件的直接链接放入浏览器中并下载该文件,例如 http://www.remotesite.com/video.avi 会提示您的浏览器下载该文件。使用php,最好的方法是抓取该文件并将其上传到我的本地服务器,而不必让该文件完全下载到我的电脑上,这就是如果您在文件上传表单中放置url时phpBB发生的情况。也希望提供所需代码的示例。谢谢

http://php.net/manual/en/function.file-get-contents.php - Elavarasan Muthuvalavan - Lee
3个回答

25

只需使用 copy

$source = "http://www.remotesite.com/video.avi";
$dest = "video.avi";
copy($source, $dest);

1
听起来比 file_getfile_put 酷 :) - Elavarasan Muthuvalavan - Lee

4
$remote_file_contents = file_get_contents('http://remote_url/file/with.extension');
//Get the contents

$local_file_path = 'your/local/path/to/the/file/with.extension';

file_put_contents($local_file_path, $remote_file_contents);
//save the contents of the remote file

http://www.php.net/manual/en/function.file-put-contents.php - Elavarasan Muthuvalavan - Lee

2
您可以在不下载浏览器的情况下读写文件。
<?php 

$file = 'http://www.remotesite.com/video.avi';

// read the file from remote location
$current = file_get_contents($file);

// create new file name
$name = "path/to/folder/newname.avi";

// Write the contents back to the file
file_put_contents($file, $current);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接