How to generate download link from any Youtube videos in PHP? - php

I'm working on a web application that allow users to post any Youtube videos to their profile or pages they manages. This is the code that I use to post Youtube video to my profile
$videoUpload = $fb->post('/me/videos', ['description' => 'example description', 'file_url' => 'https://r2---sn-npoeene7.googlevideo.com/videoplayback?pl=24&lmt=1513082002389285&id=o-AIPnl4v8svvYBTFPYwJOsRanE_5O8YSK0F3bMkTqN6QR&itag=22&signature=8051FCC4C243296224CD1D7ADB4E5C0A90125C57.66FF9FF2063C3A8F00F143FB51BB3E98F7AEBB7B&requiressl=yes&ip=203.189.156.104&sparams=dur,ei,expire,id,initcwndbps,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,pl,ratebypass,requiressl,source&key=cms1&mime=video%2Fmp4&dur=301.952&fvip=2&ipbits=0&c=WEB&expire=1519648901&ratebypass=yes&ei=JayTWtSaDcWqoQORionoCg&source=youtube&redirect_counter=1&cm2rm=sn-jvbxuxavoapox-2oil7e&fexp=23712580&req_id=21384f45d53ba3ee&cms_redirect=yes&mm=29&mn=sn-npoeene7&ms=rdu&mt=1519627218&mv=m'], $access_token);
$videoUpload = $videoUpload->getGraphNode()->asArray();
The problem is that Facebook not allow to post Youtube link directly, so I need to generate a downloadable link from that video in order to post to Facebook.
Here is the PHP code that use to generate a download link from a Youtube video
<?php
$id = 'RllJtOw0USI';
if (isset($_GET["id"]))
$id = $_GET["id"];
parse_str(file_get_contents('http://www.youtube.com/get_video_info?video_id='.$id), $video_data);
$streams = $video_data['url_encoded_fmt_stream_map'];
$streams = explode(',',$streams);
$counter = 1;
foreach ($streams as $streamdata) {
printf("Stream %d:<br/>----------------<br/><br/>", $counter);
parse_str($streamdata,$streamdata);
foreach ($streamdata as $key => $value) {
if ($key == "url") {
$value = urldecode($value);
printf("<strong>%s:</strong> <a href='%s'>video link</a><br/>", $key, $value);
} else {
printf("<strong>%s:</strong> %s<br/>", $key, $value);
}
}
$counter = $counter+1;
printf("<br/><br/>");
}
?>
It's only work with RllJtOw0USI if I change the $id to dMK_npDG12Q it's not working anymore, and I got the errors as follow:
status=fail&errorcode=150&errordetail=0&reason=This+video+contains+content+from+Vevo.+It+is+restricted+from+playback+on+certain+sites+or+applications.%0A%3Ca+href%3D%27http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdMK_npDG12Q%26feature%3Dplayer_embedded%27+target%3D%27_blank%27%3EWatch+on+YouTube%3C%2Fa%3E
How can I get the link from this kind of video?

If you look at reason in json, you can see that
This video contains content from Vevo. It is restricted from playback on certain sites or applications
So you should obey their restrictions, or find any other link which is not restricted yet.

Related

How to fetch Media Assets of a Product from Akeneo 5

I try to fetch the media assets from products in
I am using https://github.com/akeneo/api-php-client-ee (v6) and know about https://api.akeneo.com/api-reference-50.html
This is what I came up so far:
$searchBuilder = new \Akeneo\Pim\ApiClient\Search\SearchBuilder();
$searchBuilder->addFilter('enabled', '=', true);
$searchFilters = $searchBuilder->getFilters();
$products = $client->getProductApi()->all(100, ['search' => $searchFilters]);
foreach ($products as $product) {
foreach($product['values']['assets'] as $assetData) {
foreach($assetData['data'] as $code) {
echo $code;
$asset = $client->getProductMediaFileApi()->all();
var_dump($asset);
}
}
What I have tried / Questions:
I get a code like 1234_00 (if 1234 is the product number), but I do not know how to fetch the specific file from the product media file api. Do I have to filter here? How?
I tried to $client->getAssetMediaFileApi()->download($code) but the $code I have does not seem to be the full asset code (I get a 404 not found error)
How can I find out which assets are related to a specific product to download them or get the download URL?
This works - "bilder" is the Asset Family code in our case.
foreach ($products as $product) {
foreach($product['values']['assets'] as $assetData) {
foreach($assetData['data'] as $code) {
echo $code;
$assets = $client->getAssetManagerApi()->get('bilder', $code);
foreach($assets['values']['media'] as $dataLine) {
$download = $client->getAssetMediaFileApi()->download($dataLine['data']);
file_put_contents('/tmp/' . basename($dataLine['data']), $download->getBody());
}
foreach($assets['values']['variation_image'] as $dataLine) {
$download = $client->getAssetMediaFileApi()->download($dataLine['data']);
file_put_contents('/tmp/' . basename($dataLine['data']), $download->getBody());
}
}
I found the main clue, by looking at the Akeneo Admin Panel and which requests it does :-)

How to determine whether my content has a instagram embed?

The posts in my site has video(single) from anyone of the following embeds.
Youtube
Facebook
Instagram
My question is while fetching them on front end I want to findo out whether my content has an embed, if so which of the following is embedded. (iframe presence checking is one (dirty)way still it own work for instagram)
PHPCODE:
$video_start = strpos($singlePost->post_content, "<iframe");//Get to the start of the iframe(video)
$video_stop = strpos($singlePost->post_content, "</iframe>");//Get to the end of the iframe(video)
$iframe_content = substr($singlePost->post_content, $video_start, $video_stop);
$xpath = new DOMXPath(#DOMDocument::loadHTML($iframe_content));
$iframe_src = $xpath->evaluate("string(//iframe/#src)");
$parsed_url = parse_url($iframe_src);
$host = $parsed_url['host'];
if(strpos($host, "youtube") !== false) { // If it is a youtube video append this
$iframe_src = $iframe_src."?rel=0";// This option has to be appended of youtube URL's
$related_social_icon = "youtube";
$related_social_media = "youtube";
}
<iframe class="<?php echo $iframe_class; ?>" src="<?php echo $iframe_src; ?>" style="background-size: cover;" allowfullscreen></iframe>
Above code works fine for youtube, but does not work for instagram coz when inserting instagram comes as blockquote tags,but if you echo them it will be straight away become iframe tags due to the script in it.
I would go for something like this:
add_filter('the_content', function($content) {
$identifier = '<embed';
if (strpos($content, $identifier) !== false) {
// identifier found
$content = '<h1>This page includes an embed</h1>'.$content;
}
return $content;
});
I'm not sure how your embeds look like, you are talking about iframes to. So you need to find some identifiers that you can check.
Your post probably got downvoted because it could have some more information?

Get YouTube video thumbnail and use it with PHP

How can I access thumbnail collection of a YouTube video using the link of the video from the YouTube API.
I want thumbnails to be displayed on website using PHP using the video id stored in a variable for example $link
YouTube stores many different types of thumbnails on its server for different devices. You can access it by using the video id which
every YouTube video has. You can display the images on your website using a variable $link which holds the id of the video and substituting it
in the place for video_ID in the link.
Low quality thumbnail:
http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/sddefault.jpg
Medium quality thumbnail:
http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/mqdefault.jpg
High quality thumbnail:
http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/hqdefault.jpg
Maximum quality thumbnail:
http://img.youtube.com/vi/<YouTube_Video_ID_HERE>/maxresdefault.jpg
Example:
If you want to access the thumbnail of the following video:
https://www.youtube.com/watch?v=Q-GYwhqDo6o
Video ID : Q-GYwhqDo6o
So, this is how video thumbnail link looks like:
http://img.youtube.com/vi/Q-GYwhqDo6o/mqdefault.jpg
Hope it helps. Enjoy coding.
To get high-quality image you can use the following URL which is fetched from youtube API
$video_id = explode("?v=", $link);
$video_id = $video_id[1];
$thumbnail="http://img.youtube.com/vi/".$video_id."/maxresdefault.jpg";
You can use the below code. It is work for me. Choose the image quality as per your requirement.
<?php
$youtubeID = getYouTubeVideoId('youtube video url');
$thumbURL = 'https://img.youtube.com/vi/' . $youtubeID . '/mqdefault.jpg';
print_r($thumbURL);
function getYouTubeVideoId($pageVideUrl) {
$link = $pageVideUrl;
$video_id = explode("?v=", $link);
if (!isset($video_id[1])) {
$video_id = explode("youtu.be/", $link);
}
$youtubeID = $video_id[1];
if (empty($video_id[1])) $video_id = explode("/v/", $link);
$video_id = explode("&", $video_id[1]);
$youtubeVideoID = $video_id[0];
if ($youtubeVideoID) {
return $youtubeVideoID;
} else {
return false;
}
}
?>
here is my handy function to download the Youtube thumbnail image
function downloadYouTubeThubnailImage($youTubeLink='',$thumbNamilQuality='',$fileNameWithExt='',$fileDownLoadPath='')
{
$videoIdExploded = explode('?v=', $youTubeLink);
if ( sizeof($videoIdExploded) == 1)
{
$videoIdExploded = explode('&v=', $youTubeLink);
$videoIdEnd = end($videoIdExploded);
$removeOtherInVideoIdExploded = explode('&',$videoIdEnd);
$youTubeVideoId = current($removeOtherInVideoIdExploded);
}else{
$videoIdExploded = explode('?v=', $youTubeLink);
$videoIdEnd = end($videoIdExploded);
$removeOtherInVideoIdExploded = explode('&',$videoIdEnd);
$youTubeVideoId = current($removeOtherInVideoIdExploded);
}
switch ($thumbNamilQuality)
{
case 'LOW':
$imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/sddefault.jpg';
break;
case 'MEDIUM':
$imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/mqdefault.jpg';
break;
case 'HIGH':
$imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/hqdefault.jpg';
break;
case 'MAXIMUM':
$imageUrl = 'http://img.youtube.com/vi/'.$youTubeVideoId.'/maxresdefault.jpg';
break;
default:
return 'Choose The Quality Between [ LOW (or) MEDIUM (or) HIGH (or) MAXIMUM]';
break;
}
if( empty($fileNameWithExt) || is_null($fileNameWithExt) || $fileNameWithExt === '')
{
$toArray = explode('/',$imageUrl);
$fileNameWithExt = md5( time().mt_rand( 1,10 ) ).'.'.substr(strrchr(end($toArray),'.'),1);
}
if (! is_dir($fileDownLoadPath))
{
mkdir($fileDownLoadPath,0777,true);
}
file_put_contents($fileDownLoadPath.$fileNameWithExt, file_get_contents($imageUrl));
return $fileNameWithExt;
}
Function Description
Argumemts
$youTubeLink Youtube url for example https://www.youtube.com/watch?v=a3ICNMQW7Ok
$thumbNamilQuality It has Many Quality Such as LOW ,MEDIUM, HIGH, MAXIMUM
Thumbnail Quality list Taken from
https://stackoverflow.com/a/32346348/8487424
&&
https://stackoverflow.com/a/47546113/8487424
$fileNameWithExt File Name with Extension**for example** myfavouriteimage.png
NOTE $fileNameWithExt is not mandatory it will generate the uuid based file name
for Example 91b2a30d0682058ebda8d71606f5e327.jpg
if you want to put the file to the custom directory use this argument
NOTE $fileDownLoadPath is not mandatory it will generate the image file where the script is executing
Some of the sample examples
$folderpath = 'c:'.DIRECTORY_SEPARATOR.'xampp'.DIRECTORY_SEPARATOR.'htdocs'.DIRECTORY_SEPARATOR.'youtube'.DIRECTORY_SEPARATOR;
$imageName = 'mybeautfulpic.jpg';
downloadYouTubeThubnailImage('https://www.youtube.com/watch?v=a3ICNMQW7Ok','MAXIMUM',null,$folderpath );
downloadYouTubeThubnailImage('https://www.youtube.com/watch?v=a3ICNMQW7Ok','LOW',$imageName ,null);
Hope it is answered already but this function has some exta features
Google changed API on v.3 and those code from Python work exactly! You can use for PHP.
def get_small_image_url(self):
return 'http://img.youtube.com/vi/%s/%s.jpg' % (self.video_id, random.randint(1, 3))
def get_hqdefault(self):
return 'http://i1.ytimg.com/vi/%s/hqdefault.jpg' % self.video_id
def get_mqdefault(self):
return 'http://i1.ytimg.com/vi/%s/mqdefault.jpg' % self.video_id
def get_sddefault(self):
return 'http://i1.ytimg.com/vi/%s/sddefault.jpg' % self.video_id
def get_video_id(self, url):
link = urlparse.urlparse(url)
if link.hostname == 'youtu.be':
return link.path[1:]
if link.hostname in ('www.youtube.com', 'youtube.com'):
if link.path == '/watch':
state = urlparse.parse_qs(link.query)
return state['v'][0]
if link.path[:7] == '/embed/':
return link.path.split('/')[2]
if link.path[:3] == '/v/':
return link.path.split('/')[2]
return False
def get_meta(self, video_id):
api_token = **'here your API_Token'**
url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet&id=%s&key=%s' % (video_id, api_token)
response = json.load(urllib.urlopen(url))
print response
context = {
'title': response['items'][0]['snippet']['localized']['title'],
'desc': response['items'][0]['snippet']['localized']['description']
}
return context
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
video_id = self.get_video_id(self.url)
meta = self.get_meta(video_id)
self.video_id = video_id
self.title = meta['title']
self.description = meta['desc']
super(Videos, self).save(
force_insert=force_insert,
force_update=force_update,
using=using,
update_fields=update_fields
)
the simplest and easiest way to get youtube-video-id from a youtube link using str_replace.
$youtube_ids = str_replace("https://www.youtube.com/watch?v=", "", "https://www.youtube.com/watch?v=QBKdaUv5YaI");
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/maxresdefault.jpg';
Low-quality thumbnail:
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/sddefault.jpg';
Medium quality thumbnail:
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/mqdefault.jpg';
High quality thumbnail:
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/hqdefault.jpg';
Maximum quality thumbnail:
echo 'http://img.youtube.com/vi/'.$youtube_ids.'/maxresdefault.jpg';

Different results google indexed pages with php

I have this script to get google indexed pages of a url :
function getGoogleCount($domain) {
$content = file_get_contents('http://ajax.googleapis.com/ajax/services/' .
'search/web?v=1.0&filter=0&q=site:' . urlencode($domain));
$data = json_decode($content);
return intval($data->responseData->cursor->estimatedResultCount);
}
echo getGoogleCount('http://stackoverflow.com/');
But it not let me to get data for more urls. Then i used some online tools and result is different from mine. Is there other way to get these data without restrictions ?
Thanks.
What about calling getGoogleCount in a loop?
$domains = array('domain 1', 'domain 2');
foreach ($domains as $domain) {
echo getGoogleCount($domain);
}

PHP: check $msg for containing yt link

In the messages users write with eachother, I wish to turn Youtube links into the youtube thumbnail of it+title.
So how can I check if $msg contains a youtube video link, and if it does, it should take the video id (?v=) of it, and run this:
$.getScript( 'http://gdata.youtube.com/feeds/api/videos/$videoid?v=2&alt=json-in-script&callback=youtubeFetchDataCallback' );
How can this be done?
Already resolved partially here: parse youtube video id using preg_match
EDIT alternatively you could use parse_url() in PHP check the host is youtube and if it is read the query string and split into key/value pairs and read the "v" value
EDIT 2
<?php
$url = "http://www.youtube.com/watch?v=QDe6MZQjpho";
$url = parse_url($url);
if($url['host'] == "www.youtube.com") {
parse_str($url['query'], $output);
$videoID = $output['v'];
} else {
echo "not youtube.com";
}
?>
EDIT 3 Another way
<?php
$url = "http://www.youtube.com/watch?v=QDe6MZQjpho";
if(preg_match("#http://(.*)\.youtube\.com/watch\?v=(.*)(&(.*))?#", $url, $matches)){
$videoID = $matches[2];
} else {
echo "not youtube.com";
}
?>

Categories