1

I have put together php code that will notify if a YT video is valid or invalid. Since I only want URLs from the YT domain I have set an array to catch any other URL case and return an error. The problem is that when I type a URL in a format like: www.youtube.com/v/NLqAF9hrVbY i get the last echo error but when I add the http in front of that URL it works find. I am checking the $url with PHP_URL_HOST .

Why is it not accepting URLs of the allowed domain without the http?

PHP

if ($_POST) {
    $url = $_POST['name'];

    if (!empty($url['name'])) {
        $allowed_domains = array(
            'www.youtube.com',
            'gdata.youtube.com',
            'youtu.be',
            'youtube.com',
            'm.youtube.com'
        );

        if (in_array(parse_url($url, PHP_URL_HOST), $allowed_domains)) {

            $formatted_url = getYoutubeVideoID($url);
            $parsed_url = parse_url($formatted_url);
            parse_str($parsed_url['query'], $parsed_query_string);
            $videoID = $parsed_query_string['v'];

            $headers = get_headers('http://gdata.youtube.com/feeds/api/videos/' . $videoID);

            if ($videoID != null) {

                if (strpos($headers[0], '200')) {
                    echo('<div id="special"><span id="resultval">That is a valid youtube video</span></div>');

                }
                else {

                    echo('<div id="special"><span id="resultval">The YouTube video does not exist.</span></div>');
                    return false;
                }

            }
            {

                echo('<div id="special"><span id="resultval">The YouTube video does not exist.</span></div>');
                return false;
            }
        }
        else {

            echo ('<div id="special"><span id="resultval">Please include a video URL from Youtube.</span></div>');

        }
        ?>

1 Answer 1

2

parse_url() needs to be given valid URLs with protocol identifier (scheme - e.g. http) present. This is why the comparison fails.

You can fix this as follows.

if(substr($url, 0, 4) != 'http')
$url = "http://".$url;

Use the above before performing

if(in_array(parse_url($url, PHP_URL_HOST), $allowed_domains)){ ... }
Sign up to request clarification or add additional context in comments.

3 Comments

if you don't have the protocol, you could use pathinfo() instead.
@Spudley, if the protocol isn't specified at all, how can pathinfo() be used instead?
@DarkXphenomenon - if the protocol isn't specified, then it's effectively the same format a directory path, so pathinfo() can be used on it. But you're right; even with that, you'd need to extract the root dir which would be the domain, so on second thoughts it wouldn't be that useful. May just as well use explode(), I guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.