Summary of several ways to determine whether a remote URL is valid in PHP_PHP Tutorial

WBOY
Release: 2016-07-21 15:24:11
Original
992 people have browsed it

Solution:
Use PHP to solve
Use the file_get_contents function, but the advantages and disadvantages are that if the url cannot be accessed, there will be a problem of terminating the program
Use curl to return, and then determine whether it is executed correctly
Use the get_headers function, according to HTTP Return the value to see if there is 200
Use js to solve:
Use the native js function ActiveXObject, only support browsers with ie core
Use jq extension
This article mainly introduces the third PHP solution , this method is rarely used, but it feels good again.

get_headers needs support

php_openssl support. Check phpinfo to see if it is enabled.
allow_url_fopen=on. Modify php.ini and run Use remote opening

function introduction:
array get_headers ( string $url [, int $format ] )

get_headers() returns an array containing the information sent by the server in response to an HTTP request header. If it fails, it returns FALSE and issues an E_WARNING level error message.

If the optional format parameter is set to 1, get_headers() will parse the corresponding information and set the key name of the array. For example:

wps_clip_image-4948

Simple example:
Copy code The code is as follows:

$url = "/upload/201110/20111008192257383.gif";
$array = get_headers($url,1);
if(preg_match('/200/',$array[0])) {
echo "
"; 
print_r($array);
}else{
echo "Invalid url resource!";
}

Explanation: Determine whether the remote image ur is valid. According to whether there is 200 information in the return value HTTP, determine whether it is a valid url resource

Test result:

wps_clip_image-5529

You can see the correct return-----------------------The test is ok

Advantages and disadvantages:
Requires allow_url_fopen=on to be turned on , somewhat similar to the usage conditions of the file_get_contents function, but the return value is relatively small. You can use
function_exists to determine whether the method can be used

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324381.htmlTechArticleSolution: Use PHP to solve the problem of using the file_get_contents function, but the advantages and disadvantages are that if the url cannot be accessed, there will be a problem of terminating the program. curl returns, and then determines whether it is executed correctly...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!