Validate YouTube video URL format in PHP using parse_url() function

By Faruque Ahamed Mollick

We can check if a URL is a valid YouTube video link or not easily in PHP using the parse_url() function. The parse_url is the inbuilt function of PHP that is supported by PHP 4 and all the higher version of PHP.

Now in this tutorial, we are going to validate if a link or URL is a valid YouTube video URL or not. Here we are going to check the format of the URL using the PHP parse_url() function.

Value To Visual Star Rating in PHP Using Font Awesome Star icons

After we pass a URL to the parse_url function as a parameter, it will return the components as an array of that URL. Now see what it returns after we pass a YouTube video URL:

<?php
   $yt_url = "https://www.youtube.com/watch?v=cCO2tPGa-dM";
   $url_parsed_arr = parse_url($yt_url);
?>

In the above code, we have taken the YouTube URL in a variable and pass it as the parameter in the parse_url function. If we print it, then it will return the array we can see below:



Array
(
    [scheme] => https
    [host] => www.youtube.com
    [path] => /watch
    [query] => v=cCO2tPGa-dM&t=49s
)

The above array shows the scheme, host, path and the query of the URL. We are going to check the host, the path, the query and check the existence of URL query value to validate YouTube video URL.

Now below is our complete code which is able to check if a URL is a valid video link or not:

<?php
   $yt_url = "https://www.youtube.com/watch?v=cCO2tPGa-dM";
   $url_parsed_arr = parse_url($yt_url);

   if ($url_parsed_arr['host'] == "www.youtube.com" && $url_parsed_arr['path'] == "/watch" && substr($url_parsed_arr['query'], 0, 2) == "v=" && substr($url_parsed_arr['query'], 2) != "") {
        echo "The URL is a valid YouTube link";
   } else {
     	echo "Not a valid YouTube link";
   }

?>

If the URL is a valid YouTube video page link, it will show “The URL is a valid YouTube link” on the web page, otherwise it will show “Not a valid YouTube link” on the page.

How to validate phone number in PHP?

Email validation in PHP using FILTER_VALIDATE_EMAIL

So we have successfully able to validate YouTube video URL format in PHP using the parse_url() PHP function. You can put your own code depending upon your requirement.

Leave a Reply

Your email address will not be published. Required fields are marked *