如何从另一台服务器获取文件并用PHP重命名


How to get a file from another server and rename it in PHP

我正在寻找一种在PHP 中执行许多任务的方法

  1. 从其他服务器获取文件
  2. 更改文件名和扩展名
  3. 将新文件下载给最终用户

我更喜欢一种充当代理服务器类型的方法,但下载文件也可以

提前感谢

试试这个

<?php
    $url  = 'http://www.example.com/a-large-file.zip';
    $path = '/path-to-file/a-large-file.zip';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    curl_close($ch);
    file_put_contents($path, $data);
?>

保存后,用您需要的任何名称重命名文件

参考本

http://www.php.net/manual/en/ref.curl.php

请参阅http://www.php.net/manual/en/function.curl-init.php

这将获取数据并将其直接输出到浏览器、头文件和所有文件。

如果将allow_url_fopen设置为true:

 $url = 'http://example.com/image.php';
 $img = '/my/folder/flower.gif';
 file_put_contents($img, file_get_contents($url));

否则使用cURL:

 $ch = curl_init('http://example.com/image.php');
 $fp = fopen('/my/folder/flower.gif', 'wb');
 curl_setopt($ch, CURLOPT_FILE, $fp);
 curl_setopt($ch, CURLOPT_HEADER, 0);
 curl_exec($ch);
 curl_close($ch);
 fclose($fp);

我使用这样的东西:

<?php
$url  = 'http://www.some_url.com/some_file.zip';
$path = '/path-to-your-file/your_filename.your_ext';
function get_some_file($url, $path){
    if(!file_exists ( $path )){
        $fp = fopen($path, 'w+');
        fwrite($fp, file_get_contents($url));
        fclose($fp);
    }
}
?>