简体   繁体   中英

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

I was looking for a way to perform a number of tasks in PHP

  1. Get a file from another server
  2. Change the file name and extention
  3. Download the new file to the end user

I would prefer a method that acts as a proxy server type thing, but a file download would be fine

Thanks in advance

Try this

<?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);
?>

After you save rename the file with whatever name you need

Refer this

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

See the example at http://www.php.net/manual/en/function.curl-init.php

This grabs the data and outputs it straight to the browser, headers and all.

If you have allow_url_fopen set to true:

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

Else use 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);

I use something like this:

<?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);
    }
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM