首頁  >  文章  >  後端開發  >  php檢測遠端檔案是否存在的方法

php檢測遠端檔案是否存在的方法

WBOY
WBOY原創
2016-07-25 09:07:281205瀏覽
  1. function get_http_response_code($theURL) {
  2. $headers = get_headers($theURL);
  3. return substr($headers[0], 9, 3);
  4. }
  5. ?>
复制代码

get_headers的作用就是访问一个远程地址,把服务器发送的HTTP头以数组形式返回。而$header[0]则是服务器返回的状态码(如果不出意外的话状态码应该都是第一个返回的)。

排除重定向的例子:

  1. /**

  2. * Fetches all the real headers sent by the server in response to a HTTP request without redirects
  3. * 获取不包含重定向的报头
  4. */
  5. function get_real_headers($url,$format=0,$follow_redirect=0) {
  6. if (!$follow_redirect) {
  7. //set new default options
  8. $opts = array('http' =>
  9. array('max_redirects'=>1,'ignore_errors'=>1)
  10. );
  11. stream_context_get_default($opts);
  12. }

  13. //get headers

  14. $headers=get_headers($url,$format);
  15. //restore default options
  16. if (isset($opts)) {
  17. $opts = array('http' =>
  18. array('max_redirects'=>20,'ignore_errors'=>0)
  19. );

  20. stream_context_get_default($opts);

  21. }

  22. //return

  23. return $headers;
  24. }
  25. ?>

复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn