Home>Article>Backend Development> How to determine whether the URL is valid in php

How to determine whether the URL is valid in php

怪我咯
怪我咯 Original
2017-07-07 09:37:36 3586browse

Determine whether a url can be accessed normally to avoid the problem of terminating the program because the url cannot be accessed and a fatal error occurs when usingfile_get_contents

The code is as follows:

$url = ‘http://www.baidu.com'; $ch = curl_init(); $timeout = 10; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $contents = curl_exec($ch); if(false == $contents) { echo ‘Curl error: ‘ . curl_error($ch); } else { …. }

In addition, you can use

The code is as follows:

curl_getinfo($ch, CURLINFO_HTTP_CODE);

Get the code returned by the HTTP header file. If it is 200, the url can be accessed normally, but thisfunctionMust be used after curl_exec(), which seems a bit redundant.

The above is the detailed content of How to determine whether the URL is valid in php. 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