PHP to determine whether a remote URL is effective in several ways

Source: Internet
Author: User

Premise

Need to determine whether remote URLs are valid, remote URLs include remote pictures, web pages, videos, etc.

Solution:

Using PHP to resolve

Use the File_get_contents function, but the pros and cons if the URL is not accessible, a terminating program problem occurs

Use curl to return, and then determine if the correct execution

Use the Get_headers function to see if 200 is available based on the HTTP return value

Use JS to resolve:

Using the native JS function ActiveXObject, only browsers that support IE kernel

Using the JQ extension

This article mainly introduces the third of the PHP solution, this method is rarely used, but it feels good again,

Get_headers need support

Php_openssl Support View Phpinfo see if Open

Allow_url_fopen=on Modify php.ini, run using remote open

Function Description:

Array get_headers (string $url [, int $format])

Get_headers () returns an array that contains the headers that the server responds to when an HTTP request is sent. Returns False if it fails and emits an error message at the e_warning level.

If you set the optional format parameter to 1, Get_headers () parses the appropriate information and sets the key name of the array. For example:

A simple example:

$url = "Http://cn.php.net/images/php.gif";

$array = Get_headers ($url, 1);

if (Preg_match ('/200/', $array [0])) {

echo "

";

Print_r ($array);

}else{

echo "Invalid URL resource!";

}

Explanation: To determine whether the remote picture of your valid, based on the return value HTTP has 200 information, determine if it is a valid URL resource

Test results:

You can see the correct return-----------------------test OK

Advantages and Disadvantages:

Requires Allow_url_fopen=on to be turned on, somewhat similar to the file_get_contents function, but with fewer return values, you can use the

Function_exists determine if the method can be used

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.