Home > Backend Development > PHP Tutorial > PHP method to determine whether the remote URL is valid

PHP method to determine whether the remote URL is valid

WBOY
Release: 2016-07-25 09:13:01
Original
1677 people have browsed it

It is required to use PHP code to determine whether the remote URL is valid. The remote URL includes remote pictures, web pages, videos and other elements.

1. 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 to check whether there is 200 based on the http return value.

2. Use js to solve: Use the native js function activexobject, which only supports browsers with IE core. Use jq extension. This article mainly introduces the third PHP solution. This method is rarely used, but it feels good. Get_headers needs support. php_openssl support Check phpinfo to see if it is enabled allow_url_fopen=on Modify php.ini and run it using remote opening.

Function introduction: array get_headers ( string $url [, int $format ] ) get_headers() returns an array containing the headers sent by the server in response to an http request. 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 array keys.

For example: PHP method to determine whether the remote URL is valid

Example:

  1. $url = "http://cn.php.net/images/php.gif";
  2. $array = get_headers($url,1);
  3. if(preg_match(' /200/',$array[0])){
  4. echo "
    Copy after login
    ";
  5. print_r($array);
  6. }else{
  7. echo "Invalid url resource!";
  8. }
Copy Code

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 Results: PHP method to determine whether the remote URL is valid2 You can see the correct return ----------------------- test ok Advantages and disadvantages: Allow_url_fopen=on needs to be turned on, which is somewhat similar to the file_get_contents function usage conditions, but the return value is relatively small. You can use function_exists to determine whether the method can be used.



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