PHP實現的一個儲存遠程檔案到本地的函數分享_ruby專題

來源:互聯網
上載者:User

最近遇到了PHP遠程圖片本地話的問題,查了查手冊發現file_get_contents()和file_put_contents()可以解決這個問題。思路很簡單,將遠程檔案讀入字串中,然後按照規則寫入指定目錄,經測試此法可採集圖片、文本、音頻檔案等,只要你可以想辦法得到它們的地址。

先上代碼:

複製代碼 代碼如下:

/**
 * 儲存檔案到本地
 * @param 檔案路徑 $url
 * @param 儲存本地路徑 $savePath
 * @return string
 */
function downloadFile($url,$savePath='')
{
    $fileName = getUrlFileExt($url);
        $fileName = rand(0,1000).$fileName;
    $file = file_get_contents($url);
    file_put_contents($savePath.'/'.$fileName,$file);
        return $fileName;
}
 
/**
 * 擷取副檔名
 * @param 網頁URL $url
 * @return string
 */
function getUrlFileExt($url)
{
    $ary = parse_url($url);
    $file = basename($ary['path']);
    $ext = explode('.',$file);
    return $ext[1];
}

樣本:

複製代碼 代碼如下:

downloadFile("yun_qi_img/mei.png","/upload/2012/01/")

file_get_contents(path) 函數和 file() 一樣,不同的是 file_get_contents() 把檔案讀入一個字串。path是必須的參數,規定要讀取的檔案。

file_put_contents(file,data) 函數是把一個字串寫入檔案中。與依次調用 fopen(),fwrite() 以及 fclose() 功能一樣。file是必需參數,規定要寫入資料的檔案。如果檔案不存在,則建立一個新檔案。data是要寫入的資料,可以是字串、數組或資料流。

parse_url()則可以抓取分析url的資訊,我們這裡用它來擷取檔案的名稱

官方給的樣本:

複製代碼 代碼如下:

$ php -r 'print_r(parse_url("http://invalid_host..name/"));'
Array
(
    [scheme] => http
    [host] => invalid_host..name
    [path] => /
)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.