Get the Youtube Video Thumbnail from Youtube video Url using PHP - php

Lets say I have a youtube video url www.youtube.com/watch?v=B4CRkpBGQzU&feature=youtube_gdata&par1=1&par2=2
I want to get the video thumbnail -> i3.ytimg.com/vi/B4CRkpBGQzU/default.jpg
I just need a simple php script that I will input the $url and get the $img
If posible I would like to strip all other parameters and be left with just the
www.youtube.com/watch?v=B4CRkpBGQzU as the $url

To extract the identifier from the following URL :
$url = 'www.youtube.com/watch?v=B4CRkpBGQzU&feature=youtube_gdata&par1=1&par2=2';
You can first use parse_url() to get the query string :
$queryString = parse_url($url, PHP_URL_QUERY);
var_dump($queryString);
Which, here, would give you :
string 'v=B4CRkpBGQzU&feature=youtube_gdata&par1=1&par2=2' (length=49)
And, then, use parse_str() to extract the parameters from that query string :
parse_str($queryString, $params);
var_dump($params);
Which would get you the following array :
array
'v' => string 'B4CRkpBGQzU' (length=11)
'feature' => string 'youtube_gdata' (length=13)
'par1' => string '1' (length=1)
'par2' => string '2' (length=1)
And, now, it's just a matter of using the v item from that array, injecting it into the thumbnail URL :
if (isset($params['v'])) {
echo "i3.ytimg.com/vi/{$params['v']}/default.jpg";
}
Which gives :
i3.ytimg.com/vi/B4CRkpBGQzU/default.jpg

<?php
function getYoutubeImage($e){
//GET THE URL
$url = $e;
$queryString = parse_url($url, PHP_URL_QUERY);
parse_str($queryString, $params);
$v = $params['v'];
//DISPLAY THE IMAGE
if(strlen($v)>0){
echo "<img src='http://i3.ytimg.com/vi/$v/default.jpg' width='150' />";
}
}
?>
<?php
getYoutubeImage("http://www.youtube.com/watch?v=CXWSlho1mMY&feature=plcp");
?>

$url = "http://youtube.com/watch?v=B4CRkpBGQzU";
$url = explode("&", $url);
$vidID = preg_match("|?v=(.*)|", $url);
$thumb_default = file_get_contents("http://img.youtube.com/vi/$vidID/default.jpg");
$thumb1 = file_get_contents("http://img.youtube.com/vi/$vidID/0.jpg");
$thumb2 = file_get_contents("http://img.youtube.com/vi/$vidID/1.jpg");
$thumb3 = file_get_contents("http://img.youtube.com/vi/$vidID/2.jpg");
$thumb4 = file_get_contents("http://img.youtube.com/vi/$vidID/3.jpg");

Assuming youtube doesn't change their format:
$thumb = preg_match('/watch\?v=(.*)&feature/',$url, $matches);
This will get you the 'B4CRkpBGQzU' part in $matches[1];

Getting the video ID from the URL
$url = "http://www.youtube.com/watch?v=oHg5SJYRHA0&feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ) );
echo $vidID;//this is video id
Getting the images
$thumb1 = file_get_contents("http://img.youtube.com/vi/$vidID/0.jpg");
$thumb2 = file_get_contents("http://img.youtube.com/vi/$vidID/1.jpg");
$thumb3 = file_get_contents("http://img.youtube.com/vi/$vidID/2.jpg");
$thumb4 = file_get_contents("http://img.youtube.com/vi/$vidID/3.jpg");

Related

Php parse url and remove parametr issue

I have url like this :
/leads/set_attributes.html?lead_id=3793&name=TEST
I need remove 'name' and return url.
I try do it like this:
$vars = [];
parse_str(html_entity_decode($sAddQuery), $vars);
unset($vars['name']);
$sAddQuery = http_build_query($vars);
But i always get
%3Flead_id=3793
as result. I tried use html_entity_decode for array elements but it did not help. How can i solve this? Thanks
Modify your code to :
<?php
$url = parse_url('/leads/set_attributes.html?lead_id=3793&name=TEST');
$str = $url['query'];
parse_str($str, $params); //parse URL
unset($params['name']); //unset name parameter
$string = http_build_query($params); //again built the URL string
var_dump($string);
?>
Hope it works!

Extract particular point of URL in PHP

I'm trying to get a very specific part of a URL using PHP so that I can use it as a variable later on.
The URL I have is:
https://forums.mydomain.com/index.php?/clubs/11-Default-Club
The particular part I am trying to extract is the 11 part between the /clubs/ and -Default-Club bits.
I was wondering what the best way to do this was. I've seen examples on here that use a regex-esque parser but I can't wrap my head around it for this particular instance.
Thanks
Edit; this is what I've tried so far using an explode query, but it seems to give me all sorts of elements which are not present in the URL above:
$url = $_SERVER['REQUEST_URI'];
$url = explode('/', $url);
$url = array_filter($url);
$url = array_merge($url, array());
Which returns:
Array ( [0] => index.php?app=core&module=system&controller=widgets&do=getBlock&blockID=plugin_9_bimBlankWidget_dqtr03ssz&pageApp=core&pageModule=clubs&pageController=view&pageArea=header&orientation=horizontal&csrfKey=8e19769b95c733b05439755827a98ac8 )
If you expect that the string with dashes (11-Default-Club) will be always at the end you can try this:
$url = $_SERVER['REQUEST_URI'];
$urlParts = explode('/', $url);
$string = end($urlParts);
$stringParts = explode('-', $string);
$theNumber = $stringParts[0]; // this will be 11
I'd rather be explicit:
<?php
$url = 'https://forums.mydomain.com/index.php?/clubs/11-Default-Club';
$query = parse_url($url, PHP_URL_QUERY);
$pattern = '#^/clubs/(\d+)[a-zA-Z-]+$#';
$digits = preg_match($pattern, $query, $matches)
? $matches[1]
: null;
var_dump($digits);
Output:
string(2) "11"
If this URL structure is fix for all URLs in your site and you only want to get the integer/number/digit part of the URL:
<?php
$url = 'https://forums.mydomain.com/index.php?/clubs/11-Default-Club';
$int = (int) filter_var($url, FILTER_SANITIZE_NUMBER_INT);
echo $int;
If this url structure is fix for all URLs in your site then below is best way to get your value.
<?php
$url = "https://forums.mydomain.com/index.php?/clubs/11-Default-Club";
$url = explode('/', $url);
$url = array_filter($url);
$end = end($url);
$end_parts = explode('-',$end);
echo $end_parts[0];
Output:
11

Remove "http://" from URL string

I am using a bit.ly shortener for my custom domain. It outputs http://shrt.dmn/abc123; however, I'd like it to just output shrt.dmn/abc123.
Here is my code.
//automatically create bit.ly url for wordpress widgets
function bitly()
{
//login information
$url = get_permalink(); //for wordpress permalink
$login = 'UserName'; //your bit.ly login
$apikey = 'API_KEY'; //add your bit.ly APIkey
$format = 'json'; //choose between json or xml
$version = '2.0.1';
//generate the URL
$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;
//fetch url
$response = file_get_contents($bitly);
//for json formating
if(strtolower($format) == 'json')
{
$json = #json_decode($response,true);
echo $json['results'][$url]['shortUrl'];
}
else //for xml formatting
{
$xml = simplexml_load_string($response);
echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
}
}
As long as it is supposed to be url and if there is http:// - then this solution is the simplest possible:
$url = str_replace('http://', '', $url);
Change your following line:
echo $json['results'][$url]['shortUrl'];
for this one:
echo substr( $json['results'][$url]['shortUrl'], 7);
You want to do a preg_replace.
$variable = preg_replace( '/http:\/\//', '', $variable ); (this is untested, so you might also need to escape the : character ).
you can also achieve the same effect with $variable = str_replace('http://', '', $variable )

How to remove a specific parameter from the URL in PHP?

Example:
$url = http://example.com/?arg=val&arg2=test&arv3=testing&arv2=val2
remove_url_arg($url, "arg2")
echo($url); // http://example.com/?arg=val&arv3=testing
The above remove_url_arg() function removes all occurrence of arg2 argument from the URL
unset($_GET['arg2']);
$query_string = http_build_query($_GET);
if it's not on request but to parse whole url
$parsed = parse_url($url);
$qs_arr = parse_str($parsed['query'],1);
unset($qs_arr['arg2']);
$parsed['query'] = http_build_query($qs_arr);
and then assemble the url back.
or one-liner regexp

Get keyword from a (search engine) referrer url using PHP

I am trying to get the search keyword from a referrer url. Currently, I am using the following code for Google urls. But sometimes it is not working...
$query_get = "(q|p)";
$referrer = "http://www.google.com/search?hl=en&q=learn+php+2&client=firefox";
preg_match('/[?&]'.$query_get.'=(.*?)[&]/',$referrer,$search_keyword);
Is there another/clean/working way to do this?
Thank you,
Prasad
If you're using PHP5 take a look at http://php.net/parse_url and http://php.net/parse_str
Example:
// The referrer
$referrer = 'http://www.google.com/search?hl=en&q=learn+php+2&client=firefox';
// Parse the URL into an array
$parsed = parse_url( $referrer, PHP_URL_QUERY );
// Parse the query string into an array
parse_str( $parsed, $query );
// Output the result
echo $query['q'];
There are different query strings on different search engines. After trying Wiliam's method, I have figured out my own method. (Because, Yahoo's is using 'p', but sometimes 'q')
$referrer = "http://search.yahoo.com/search?p=www.stack+overflow%2Ccom&ei=utf-8&fr=slv8-msgr&xargs=0&pstart=1&b=61&xa=nSFc5KjbV2gQCZejYJqWdQ--,1259335755";
$referrer_query = parse_url($referrer);
$referrer_query = $referrer_query['query'];
$q = "[q|p]"; //Yahoo uses both query strings, I am using switch() for each search engine
preg_match('/'.$q.'=(.*?)&/',$referrer,$keyword);
$keyword = urldecode($keyword[1]);
echo $keyword; //Outputs "www.stack overflow,com"
Thank you,
Prasad
To supplement the other answers, note that the query string parameter that contains the search terms varies by search provider. This snippet of PHP shows the correct parameter to use:
$search_engines = array(
'q' => 'alltheweb|aol|ask|ask|bing|google',
'p' => 'yahoo',
'wd' => 'baidu',
'text' => 'yandex'
);
Source: http://betterwp.net/wordpress-tips/get-search-keywords-from-referrer/
<?php
class GET_HOST_KEYWORD
{
public function get_host_and_keyword($_url) {
$p = $q = "";
$chunk_url = parse_url($_url);
$_data["host"] = ($chunk_url['host'])?$chunk_url['host']:'';
parse_str($chunk_url['query']);
$_data["keyword"] = ($p)?$p:(($q)?$q:'');
return $_data;
}
}
// Sample Example
$obj = new GET_HOST_KEYWORD();
print_r($obj->get_host_and_keyword('http://www.google.co.in/search?sourceid=chrome&ie=UTF-&q=hire php php programmer'));
// sample output
//Array
//(
// [host] => www.google.co.in
// [keyword] => hire php php programmer
//)
// $search_engines = array(
// 'q' => 'alltheweb|aol|ask|ask|bing|google',
// 'p' => 'yahoo',
// 'wd' => 'baidu',
// 'text' => 'yandex'
//);
?>
$query = parse_url($request, PHP_URL_QUERY);
This one should work For Google, Bing and sometimes, Yahoo Search:
if( isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']) {
$query = getSeQuery($_SERVER['HTTP_REFERER']);
echo $query;
} else {
echo "I think they spelled REFERER wrong? Anyways, your browser says you don't have one.";
}
function getSeQuery($url = false) {
$segments = parse_url($url);
$keywords = null;
if($query = isset($segments['query']) ? $segments['query'] : (isset($segments['fragment']) ? $segments['fragment'] : null)) {
parse_str($query, $segments);
$keywords = isset($segments['q']) ? $segments['q'] : (isset($segments['p']) ? $segments['p'] : null);
}
return $keywords;
}
I believe google and yahoo had updated their algorithm to exclude search keywords and other params in the url which cannot be received using http_referrer method.
Please let me know if above recommendations will still provide the search keywords.
What I am receiving now are below when using http referrer at my website end.
from google: https://www.google.co.in/
from yahoo: https://in.yahoo.com/
Ref: https://webmasters.googleblog.com/2012/03/upcoming-changes-in-googles-http.html

Categories