Retrieve YouTube video details, including description from video URL using PHP? - php

After searching stackoverflow, I've found: How can I retrieve YouTube video details from video URL using PHP?
using the following code (I have changed to https instead of http and also added $_GET['v'] for getting video code from browser URL):
function get_youtube($url) {
$youtube = "https://www.youtube.com/oembed?url=". $url ."&format=json";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
return json_decode($return, true);
}
$url = 'https://www.youtube.com/watch?v=' . $_GET['v'];
// Display Data
echo '<pre>';
print_r(get_youtube($url));
echo '</pre>';
I was able to get the following result:
Array
(
[thumbnail_url] => https://i.ytimg.com/vi/AhN5MbTJ0pk/hqdefault.jpg
[version] => 1.0
[type] => video
[html] => <iframe width="480" height="270" src="https://www.youtube.com/embed/AhN5MbTJ0pk?feature=oembed" frameborder="0" allowfullscreen></iframe>
[provider_url] => https://www.youtube.com/
[thumbnail_width] => 480
[width] => 480
[thumbnail_height] => 360
[author_url] => https://www.youtube.com/user/AndreasChoice
[author_name] => AndreasChoice
[title] => GROSS SMOOTHIE CHALLENGE! ft. Tealaxx2
[height] => 270
[provider_name] => YouTube
)
Which is great, but I also need to retrieve the full 'description' of the video that is missing. How can I achieve this? Thank you.

In order to receive the description of a video you have 2 options.
Use an API.
Crawl the website.
The API that you need is under googleapis.com domain.
The url that you need to use is:
https://www.googleapis.com/youtube/v3/videos?id=VIDEO_ID&key=YOUR_API_KEY&fields=items(id,snippet(description))&part=snippet
Notice that you have to change the VIDEO_ID and YOUR_API_KEY.
To get an API key follow these instructions: link.
Building a web crawler is more complex.
Try following this tutorial to build your own web crawler here

Related

Uploading Videos to Twitter using API

I'm using the library tmhOAuth to post to Twitter in an app and I've already implemented uploading pictures but am having trouble implementing video upload.
This is the call I use to upload pictures and works perfectly with images.
$temp = '#upload/'.$name.';type='.$_FILES['img']['type'].';filename='.$name;
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json', array('media' => $temp), true, true);
So I thought it might be the same for videos but I got the error
stdClass Object ( [request] => /1.1/media/upload.json [error] => media type unrecognized. )
I believe I have to make 3 separate calls, as per the Twitter API, so I tried this
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json?command=INIT&media_type=video/mp4&total_bytes='.$_FILES['img']['size'], array('media' => $temp), true, true);
$media_id = json_decode($tmhOAuth->response['response'])->media_id_string;
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json?command=APPEND&media_id='.$media_id.'&segment_index=0', array('media' => $temp), true, true);
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json?command=FINALIZE&media_id='.$media_id, array('media' => $temp), true, true);
but I kept getting the same error for all 3 calls
stdClass Object ( [request] => /1.1/media/upload.json [error] => media type unrecognized. )
Can anyone provide an example as to how to upload videos to twitter? I could find no examples online and it might just not be possible.
I had the same problem. Here's how I managed to solve it.
First you set up a var containing the filesystem full path to the media you want to upload.
$media_path = '/PATH/TO/THE/file.mp4';
Then instantiate $tmhOAuth and do the 3 steps :
$tmhOAuthUpload = new tmhOAuth();
INIT:
$code = $tmhOAuthUpload->request(
'POST',
$tmhOAuthUpload->url('/1.1/media/upload.json'),
array(
"command" => "INIT",
"total_bytes" => (int)filesize($media_path),
'media_type' => 'video/mp4',
)
);
Retrieve media id returned by Twitter
$results = json_decode($tmhOAuthUpload->response['response']);
$media_id = $results->media_id_string;
APPEND: Handle video/media upload with the Append loop
$fp = fopen($media_path, 'r');
$segment_id = 0;
while (! feof($fp)) {
$chunk = fread($fp, 1048576); // 1MB per chunk for this sample
$tmhOAuthUpload->request(
'POST',
$tmhOAuthUpload->url('/1.1/media/upload.json'),
array(
"command" => "APPEND",
"media_id" => $media_id,
'media_data' => base64_encode($chunk),
"segment_index" => $segment_id
)
);
$segment_id++;
}
FINALIZE:
$tmhOAuthUpload->request(
'POST',
$tmhOAuthUpload->url('/1.1/media/upload.json'),
array(
"command" => "FINALIZE",
"media_id" => $media_id,
)
);
By then I was able to to send my tweet:
$code = $tmhOAuth->request(
'POST',
$tmhOAuthUpload->url('1.1/statuses/update'),
array(
'media_ids' => $media_id,
'status' => $text,
),
true // use auth
);
Hope that helps
I've only been able to get video uploading working with CodeBird - a different PHP library.
The Twitter API calls for video are quite different from uploading images, as you've discovered.
Uploading videos to Twitter (≤ 15MB, MP4) requires you to send them in chunks. You need to perform at least 3 calls to obtain your media_id for the video:
Send an INIT event to get a media_id draft.
Upload your chunks with APPEND events, each one up to 5MB in size.
Send a FINALIZE event to convert the draft to a ready-to-tweet media_id.
Post your tweet with video attached.
Remember, each APPEND must be 5MB or under.
If you are consistently getting "Media Type Unrecognised" errors, it might be that the video you are using is incompatible with Twitter. Can you test uploading the video via another service?
Thank you very much for that answer Pierre! I was however getting a “Not valid video” error if I tried to create the tweet too soon. The video wasn't done being processed by Twitter. In addition to Pierre's code, I needed something like this to check STATUS, after FINALIZE:
$videoCount = 0;
do
{
$tmhOAuth->request(
'GET',
$tmhOAuth->url('/1.1/media/upload.json'),
array(
"command" => "STATUS",
"media_id" => $mediaID,
)
);
$twitterResult = json_decode($tmhOAuth->response['response']);
if ($twitterResult->processing_info->state != 'succeeded')
{ sleep(5); }
$videoCount++;
}
while ($twitterResult->processing_info->state != 'succeeded' && $videoCount < 5);
Note: my variable names are different

Twitter API - how to check if user A follows user B

My problem is quite strange (at least to me) as I have a request URL that works in the console but throws the Sorry, that page does not exist error in my php script, even though the connection is up and running.
So this
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_secret']);
$user = $connection->get('account/verify_credentials');
print_r($user);
works great, the $user data is printed out on the screen.
However, I am unable to check a friendship status as:
$x = $connection->get('https://api.twitter.com/1.1/friendships/show.json?source_id=707482092&target_id=755811768&target_screen_name=assetspersonifi');
As I get the error.
When I put this request into the Twitter API console, it gives back the json that I don't receive in my php code.
I'm using Abraham's twitteroauth library but this does not work either:
$follows_faelazo = $connection->get('friendships/exists', array('user_a' => 'blfarago', 'user_b' => 'faelazo'));
if(!$follows_faelazo){
echo 'You are NOT following #faelazo!';
$connection->post('friendships/create', array('screen_name' => 'faelazo'));
} else {
print_r($follows_faelazo);
}
stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [message] => Sorry, that page does not exist [code] => 34 ) ) )
I read that friendships/exists API is no longer supported by the Twitter API and I should use friendships/show but how if it's not working as you see above?
To prove that everything else is working, I can follow others with
$connection->post('friendships/create', array('screen_name' => 'faelazo'));
Why?
I found a way. Here's the documentation
$following = $connection->get('friendships/show', array(
'source_screen_name' => $_SESSION['username'],
'target_screen_name' => $screen_name_to_follow,
));
An alternative would be
$following = $connection->get('friendships/lookup', array('screen_name' => $screen_name_to_follow));
Look it up in Twitter doc.

Getting user country Facebook API PHP SDK

Currently having a few issues accessing the country from a given user on facebook. I have requested the user_location permission and my graph API call also requests location however I am only ever returned the city and an ID for the location - never an actual country.
My requests etc are below. I am using the standard PHP SDK docs
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me?fields=birthday,name,statuses,photos,location' );
$response = $request->execute();
// get response
$response = $response->getGraphObject();
$data_we_need = array();
$data_we_need['name'] = $response->getProperty('name');
$data_we_need['birthday'] = $response->getProperty('birthday');
$data_we_need['location'] = $response->getProperty('location');
$statuses = $response->getProperty('statuses');
$data_we_need['statuses'] = $statuses->asArray();
$photos = $response->getProperty('photos');
$data_we_need['photos'] = $photos->asArray();
I am returned an results like:
[name] => xxxxxx
[birthday] => 05/14/1990
[location] => __PHP_Incomplete_Class Object
(
[__PHP_Incomplete_Class_Name] => Facebook\GraphObject
[backingData:protected] => Array
(
[id] => 112087812151796
[name] => Gloucester, Gloucestershire
)
)
I need to be able to get country from the location data provided.
Any help would be massively appreciated.
As far as I know the location & hometown fields are user inputs (community pages), hence you won't get stable results using the facebook API. You might rather want to try detecting the country yourself with the IP.

getting 200 ok code but image not uploaded on twitter using codebird

i am using codebird-php to post images on twitter, when i do that i get 200 ok http code but the image is not uploaded. Here is my code:
<?php
session_start();
require_once ('./src/codebird.php');
\Codebird\Codebird::setConsumerKey('74AFitlDilqB2HlFQ8Cjszz6I', 'tDlVndY7iJG8loFGG1sq3gJaj59CwNx6UV5o6wEtV0LJebNJ0y'); // static, see 'Using multiple Codebird instances'
$cb = \Codebird\Codebird::getInstance();
$access_token = $_SESSION['access_token'];
$cb->setToken($access_token['oauth_token'], $access_token['oauth_token_secret']);
//$reply = $cb->statuses_update('status=Whohoo, I just again tweeted!');
// send tweet with these medias
$reply = $cb->media_upload(array(
'media' => 'http://www.bing.com/az/hprichbg/rb/BilbaoGuggenheim_EN-US11232447099_1366x768.jpg'
));
print_r($reply);
?>
This is what i am getting on running it in my browser:
stdClass Object ( [media_id] => 540134777223790592 [media_id_string] => 540134777223790592 [size] => 179801 [image] => stdClass Object ( [w] => 1366 [h] => 768 [image_type] => image/jpeg ) [httpstatus] => 200 [rate] => )
PS: I am running it on localhost, tweeting text works but not image and i am using Abrahams oAuth for getting oAuth token.
i fixed it by changing
$reply = $cb->media_upload(array(
'media' => 'http://www.bing.com/az/hprichbg/rb/BilbaoGuggenheim_EN-US11232447099_1366x768.jpg'
));
to
$params = array(
'status' => 'Auto Post on Twitter with PHP http://goo.gl/OZHaQD #php #twitter',
'media[]' => 'http://www.bing.com/az/hprichbg/rb/BilbaoGuggenheim_EN-US11232447099_1366x768.jpg'
);
// send tweet with these medias
/*$reply = $cb->media_upload(array(
'media[]' => "#http://www.bing.com/az/hprichbg/rb/BilbaoGuggenheim_EN-US11232447099_1366x768.jpg"
));*/
$reply = $cb->statuses_updateWithMedia($params);

PHP redirect based on IP location

I have a multilingual site with an 'index.php' sitting on example.com domain. This index.php should have this redirection code so when users go to 'example.com' they get redirected to either the French or English version of the site.
In its simplest form I'd like the conditional statement to read:
If IP is based in France redirect to example.com/fr else if anywhere else in the world redirect to example.com/en
How might I set this up using PHP?
Have a look at http://www.geoplugin.com/webservices/php and use a cache to store the IP address as not to make the request every time.
<?php
error_reporting(-1);
ini_set("display_errors", "On");
$ch = curl_init('http://www.geoplugin.net/php.gp?ip={the IP address, used mine for example}');
if (!$ch) {
die('Failed CURL');
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$serverResponse = curl_exec($ch);
if (!$serverResponse) {
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
throw new Exception('HTTP error: ' . $code);
}
die(print_r($serverResponse));
Will result in:
Array
(
[geoplugin_request] => My IP
[geoplugin_status] => 206
[geoplugin_credit] => Some of the returned data includes GeoLite data created by MaxMind, available from <a href=\'http://www.maxmind.com\'>http://www.maxmind.com</a>.
[geoplugin_city] =>
[geoplugin_region] =>
[geoplugin_areaCode] => 0
[geoplugin_dmaCode] => 0
[geoplugin_countryCode] => GB
[geoplugin_countryName] => United Kingdom
[geoplugin_continentCode] => EU
[geoplugin_latitude] => 51.5
[geoplugin_longitude] => -0.13
[geoplugin_regionCode] =>
[geoplugin_regionName] =>
[geoplugin_currencyCode] => GBP
[geoplugin_currencySymbol] => £
[geoplugin_currencySymbol_UTF8] => £
[geoplugin_currencyConverter] => 0.6003
)
So use the country code.

Categories