PHP 透過 URL 下載檔案至本地伺服器


#PHP#fopen#fwrite#file_get_contents#file_put_contents#copy

使用情境


實現方式


  • fopen - 最原始的方法,code 醜不好維護。
  • file_get_contents/file_put_contents - 一行解決。
  • copy - 一個 function 解決。

注意事項


  • php.ini 中的 allow_url_fopen 需開啟。
  • 因為 PHP 是直譯語言,所以輸出的資料夾必須禁止執行 PHP,避免遭 webshell 攻擊。

範例


fopen

<?php
    $inputUrl = '下載的檔案網址';
    $outputPath = '輸出絕對路徑';
    if (false === ($inputFile = fopen($inputUrl, 'rb'))) {
        throw new Exception('open input file fail');
    }
    if (false === ($outputFile = fopen($outputPath, 'wb'))) {
        throw new Exception('open output file fail');
    }
    while (!feof($inputFile)) {
        fwrite($outputFile, fread($inputFile, 2048), 2048);
    }
    fclose($outputFile);
    fclose($inputFile);
    // success

file_get_contents

<?php
    $inputUrl = '下載的檔案網址';
    $outputPath = '輸出絕對路徑';
    if (false === file_put_contents($outputPath, file_get_contents($inputUrl))) {
        throw new Exception('download file fail');
    }
    // success

copy

<?php
    $inputUrl = '下載的檔案網址';
    $outputPath = '輸出絕對路徑';
    if (false === copy($inputUrl, $outputPath)) {
        throw new Exception('download file fail');
    } 
    // success

參考:
https://stackoverflow.com/questions/3488425/php-ini-file-get-contents-external-url
https://www.php.net/manual/zh/filesystem.configuration.php#ini.allow-url-fopen
https://www.php.net/manual/en/function.fopen.php
https://www.php.net/manual/en/function.copy.php
https://www.php.net/manual/zh/function.file-get-contents.php