Home  >  Article  >  Backend Development  >  PHP method to detect whether a given url is a 404 page

PHP method to detect whether a given url is a 404 page

王林
王林Original
2019-11-08 10:15:253301browse

PHP method to detect whether a given url is a 404 page

Requirement description:

Detect whether the given url is a 404 page.

Method 1:

Use the file_get_contents function to read web pages or files in the web. If a 404 page is encountered, false will be returned, otherwise the corresponding web page content will be returned.

There are two points to note when using this function:

1. file_get_contentsWhen reading a page that does not exist, a warning will be reported. So it's best to block the warnings here.

2, file_get_contentsBy default, all the contents of the page will be read and then returned. In order to improve the read speed, we can limit the read to only 10 bytes before returning.

PHP method to detect whether a given url is a 404 page

<?php
$res = @file_get_contents("http://www.baidu.com",null,null,0,10);
if($res){
  echo $res;
}else{
  echo "404";
}

Method 2:

We need to determine whether the page is a 404 page. This can be determined by the status code returned by the web page. judge.

Using this method will not report a warning when page 404 occurs. Because we only need the status code, we do not need to read the content of the web page. We can shorten the running time of the program by setting the CURLOPT_NOBODY parameter and not reading the content of the web page.

<?php
$ch = curl_init("http://www.baidu.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
$res = curl_exec($ch);
$code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($code == 404){
  echo "404";
}else{
  echo $code;
}

Recommended tutorial: PHP video tutorial

The above is the detailed content of PHP method to detect whether a given url is a 404 page. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn