如何通過php判斷本地及遠程檔案是否存在

來源:互聯網
上載者:User

本文介紹使用php判斷檔案是否存在的方法,支援本地及遠程檔案判斷,提供完整調用代碼及示範。

1.判斷本地檔案是否存在

判斷本地檔案是否存在,可以使用file_exists方法判斷。

<?php$file = 'test.jpg';var_dump(file_exists($file));?>

2.判斷遠程檔案是否存在

判斷遠程檔案是否存在,不能使用file_exists方法,而是擷取遠程檔案的header來判斷是否存在,如存在返回的HTTP_CODE是200或304。

<?php// 屏蔽網域名稱不存在等訪問問題的警告error_reporting(E_ALL ^ (E_WARNING|E_NOTICE));$remote_file = 'http://www.csdn.net/css/logo.png';$header = get_headers($remote_file, true);var_dump(isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304')));?>

3.完整代碼

<?php/** * 判斷檔案是否存在,支援本地及遠程檔案 * @param  String  $file 檔案路徑 * @return Boolean */function check_file_exists($file){    // 遠程檔案    if(strtolower(substr($file, 0, 4))=='http'){        $header = get_headers($file, true);        return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));    // 本地檔案    }else{        return file_exists($file);    }}// 屏蔽網域名稱不存在等訪問問題的警告error_reporting(E_ALL ^ (E_WARNING|E_NOTICE));$file1 = 'test.jpg';$file2 = 'http://www.csdn.net/css/logo.png';var_dump(check_file_exists($file1)); // falsevar_dump(check_file_exists($file2)); // true?>

本篇講解了通過php判斷本地及遠程檔案是否存在 ,更多相關內容請關注php中文網。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.