PHP function to verify that the URL is legitimate

Source: Internet
Author: User
Tags curl

There are two kinds of authentication URL is the use of regular expressions to verify that the URL is not the appropriate URL rules, the other is to use the function to access the specified URL to see whether the normal access, if the normal access to natural is the legitimate URL address.

Example 1

The code is as follows

<?php
function Isvalidurl ($url) {

$patern = '/^http[s]?:\/\/'.
' ([0-9]{1,3}\.] {3} [0-9] {1,3} '. URL-199.194.52.184 in IP form
'|'. IP and domain (domain name) allowed
' ([0-9a-z_!~*\ ' ()-]+\.) *'. Level three domain validation-www.
' ([0-9a-z][0-9a-z-]{0,61}]? [0-9a-z]\.] Second-level domain validation
' [a-z]{2,6}] '. Top-level domain authentication. com or. Museum
' (: [0-9]{1,4}]? '. Port-: 80
' ((\/\?) | '. If you have a file that verifies the file part
' (\/[0-9a-za-z_!~\*\ ' (\) \.; \?:@&=\+\$,%#-\/]*)? $/';

if (!preg_match ($patern, $url)) {
Die (' The URL format you entered has a problem, please check! ');
}
}

Example 2

The above example just verifies that the URL is not normal and does not mean that it can be accessed, and we can use the method such as the Curl function

The code is as follows

$url = "Http://www.45it.net";
$curl = Curl_init ($url);
curl_setopt ($curl, Curlopt_nobody, true);
$result = curl_exec ($curl);
if ($result!== false)
{
$statusCode = Curl_getinfo ($curl, Curlinfo_http_code);
if ($statusCode = = 404)
{
echo "URL not Exists"
}
Else
{
echo "URL Exists";
}
}
Else
{
echo "URL not Exists";
}

In addition to this function can also use PHP's many functions such as file, file_get_contents (), fopen function to detect.

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.