Heim  >  Artikel  >  Backend-Entwicklung  >  php检测远端文件是否存在的方法

php检测远端文件是否存在的方法

WBOY
WBOYOriginal
2016-07-25 09:07:281205Durchsuche
  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. ?>
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn