Reputation:
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>');
}
?>
Upvotes: 1
Views: 109
Reputation: 46728
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)){ ... }
Upvotes: 2