what am trying to do is check if the video entered by the users really exists or not , I have searched a lot and found this : ReRetrieving_Video_Entry , but it looks like it deprecated, so how is it possible using Google APIs Client Library for PHP to check if video exists or not?
I have fixed it using this technique, which doesn't require any use of API:
$headers = get_headers('https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=' . $key);
if(is_array($headers) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$headers[0]) : false){
// video exists
} else {
// video does not exist
echo json_encode(array('Error','There is no video with that Id!'));
}
Here's what I'm using, it works pretty well. Youtube API v2. Deprecated
$video = "cK3N2DC3Fds";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://gdata.youtube.com/feeds/api/videos/'.$video);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
if ($content && $content !== "Invalid id" && $content !== "No longer available") {
$xml = new SimpleXMLElement($content);
}else {
//Doesn't exist
}
You can check if a video exists using YouTube Data API (v3). Download/clone the API from here.
And here's a script I made that check if a video exists given a youtube video ID.
require_once dirname(__FILE__).'/../google-api/src/Google/autoload.php'; // or wherever autoload.php is located
$DEVELOPER_KEY = 'yourkey';
$client = new Google_Client();
$client->setDeveloperKey($DEVELOPER_KEY);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
$video = "cK3N2DC3Fds"; //Youtube video ID
$searchResponse = $youtube->search->listSearch('id', array(
'q' => $video, //The search query, can be a name or anything,
'maxResults' => 1, //Query result limit
"type" => "video"
));
$exists = false;
foreach ($searchResponse['items'] as $searchResult) {
//if type is video, this will always be "youtuve#video"
if($searchResult['id']['kind'] == "youtube#video"){
if($video == $searchResult['id']['videoId']){
$exists = true;
}
}
}
if(!$exists){
echo "video not found";
}else echo "video found";
Related
i want detect post id of new post in telegram channel with telegram bot that is admin in channel and forward new post to other channel that I have already specified
i tried to get id of post that bot forwarded to channel with this php code below
function bot($method, $datas = [])
{
$url = "https://api.telegram.org/bot" . API_KEY . "/" . $method;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datas);
$res = curl_exec($ch);
if (curl_error($ch)) {
var_dump(curl_error($ch));
} else {
return json_decode($res);
}
}
$msg_id = bot('ForwardMessage', [
'chat_id' => $channel,
'from_chat_id' => $chat_id,
'message_id' => $message_id
])->result->message_id;
but i need php code that can chek channel if new post send from other admins, robot find post id and forward post to other channel that I have already specified in two channels that robot is admin
i read api bot of telegram there says about how can get post channel in this link: https://core.telegram.org/bots/api#update
in my bot i use setwebhook, which one of $channel_post or $chid is correct?
$update = json_decode(file_get_contents('php://input'));
$channel_post = $update->message->channel_post;
$chid = $update->channel_post->message->message_id;
follow this code :
if( isset($update->channel_post) && $update->channel_post )
{
if(isset($update->channel_post->text) && $update->channel_post->text)
{
$apiToken = "my_bot_api_token";
$data = [
'chat_id' => '#targetChannel',
'text' => $update->channel_post->text
];
file_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" . http_build_query($data) );
}
}
I have a video exist on my server,
I need to post that video on Facebook using Graph API.
Here is the code suggested by Team Facebook.
What I am doing is as below.
1) From an Android device I am getting an access token
2) Recognizing user by passing that access token to Facebook and get email id and through email id recognize user
3) Posting user's video from my server to Facebook through Graph API.
4) Returning a video id to android device as an API response.
I am approaching this route because in Android device it is 2 step process to post video on Facebook.
1) Download the video first
2) Post to Facebook
This is time consuming.
Here is the code that I am trying
define("FB_WEB_APP_ID","********");
define("FB_WEB_SECRET","********");
define("FB_WEB_REDIRECT_URI","<< redirect url >>");
$GLOBALS["all_user_dir_path"]="/var/www/proj/web/video/user_videos/";
define("FB_WEB_SCOPE","user_friends,email,public_profile,user_hometown,user_location,user_photos,user_videos,publish_actions,read_friendlists,publish_stream,offline_access");
define("FB_WEB_RESPONSE_TYPE","code%20token");
$GLOBALS["fb_app_creds"]=array();
$GLOBALS["fb_app_creds"]['appId']= FB_WEB_APP_ID;
$GLOBALS["fb_app_creds"]['secret']=FB_WEB_SECRET;
$GLOBALS["fb_app_creds"]['response_type']=FB_WEB_RESPONSE_TYPE;
$GLOBALS["fb_app_creds"]['redirect_uri']=FB_WEB_REDIRECT_URI;
$GLOBALS["fb_app_creds"]['scope']=FB_WEB_SCOPE;
$GLOBALS["facebook"] = new Facebook($GLOBALS["fb_app_creds"]);
class DefaultController extends Controller
{
// some code....
/**
* #Route("/gk",name="_fb")
* #Template()
*/
public function gkAction(Request $request){
$facebook = $GLOBALS["facebook"];
$access_token=$request->query->get("access_token");
if(!$access_token){
die("give access token in url.......");
}
echo "<pre>";
$facebook->setAccessToken($access_token);
$user = $facebook->getUser();
$me=$facebook->api("/me");
$email=$me['email'];
$all_user_dir_path=$GLOBALS["all_user_dir_path"];
$user_directory = str_replace(array(".","#"), "_",$email);
$user_dir_abs_path=$all_user_dir_path.$user_directory;
print_r($me);
$video_file_path=$user_dir_abs_path."/video.mp4";
if(file_exists($video_file_path))
{
echo "file exists...";
}else{
die("not exist");
}
$video_title="Test";
$video_desc="Test";
$access_token=$request->query->get("access_token");
$file = "#".$video_file_path;
$data = array('name' => 'file', 'file' => $file);
$post_url = "https://graph-video.facebook.com/me/videos?"
. "title=" . $video_title. "&description=" . $video_desc
. "&". $access_token
;
echo "<hr>TRY 1<hr>";
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$res = curl_exec($ch);
$video_id=0;
if( $res === false ) {
}else{
$res=json_decode($res,true);
/* $video_id = $res['id'];*/
echo ":::: ";print_r($res);
}
curl_close($ch);
}catch(\Exception $e){
echo " Exception generated in Try 1 : ".$e->getMessage();
}
echo "<hr>TRY 2<hr>";
$params = array(
"access_token" => $access_token,
"name"=>"file",
"file" => "#".$video_file_path,
"title" => $video_title,
"description" => $video_desc
);
try {
$ret = $facebook->api('/me/videos', 'POST', $params);
print_r($ret);
} catch(\Exception $e) {
echo " Exception generated in Try 2 : ".$e->getMessage();
}
die("</pre>");
}
}
Output I am getting is An active access token must be used to query information about the current user. error and (#353) You must select a video file to upload.
Look at this image
Please tell me how to solve this problem ??
New code tried...................................................
/* code with sdk - object oriented way */
$file=$GLOBALS["all_user_dir_path"].$user_directory."/video.mp4";
$source = array();
$source['name']="video.mp4";
$source['type'] = "video/mp4";
$source['tmp_name'] = $file;
$source['error'] = 0;
$source['size'] = filesize($file);
echo "<br><br>$file<br><br>";
$params = array(
"access_token" => $access_token,
"source" => $source,
"title" => "testvideo",
"description" => "testvideo"
);
try {
$ret = $facebook->api('/me/videos', 'POST', $params);
echo 'Successfully posted to Facebook';
echo "<pre>";print_r($ret);echo "</pre>";
} catch(Exception $e) {
echo $e->getMessage();
}
but this gives (#353) You must select a video file to upload error
Here is the answer
public function shareSocialgrationFB($access_token,& $exception){
$video_id=0;
try{
$config = array();
$config['appId'] = FB_WEB_APP_ID;
$config['secret'] = FB_WEB_SECRET;
$config['fileUpload'] = true;
$config['cookie'] = true;
$facebook = new Facebook($config);
$facebook->setFileUploadSupport(true);
$facebook->setAccessToken($access_token);
$me=$facebook->api("/me");
$email=$me['email'];
$user_directory = str_replace(array(".","#"), "_",$email);
$file = $GLOBALS["all_user_dir_path"].$user_directory."/video.mp4";
$usersFacebookID=$facebook->getUser();
$video_details = array(
'access_token'=> $access_token,
'message'=> 'Testvideo!',
'source'=> '#' .realpath($file),
'title'=>'Test'
);
$post_video = $facebook->api('/'.$usersFacebookID.'/videos', 'post', $video_details);
$video_id=$post_video['id'];
}catch(\Exception $e){
//echo "Exception generated :: ".$e->getMessage();
$exception=$e->getMessage();
// extra code to handle exception
}
return $video_id;
}
Reference : How to POST video to Facebook through Graph API using PHP
I don't know why the info about configurations
$config['fileUpload'] = true;
$config['cookie'] = true;
is not mentioned at below official docs of APIs
https://developers.facebook.com/blog/post/493/
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/videos#publish
However solution given above, worked fine for me.
file is not a valid parameter. Instead of parameter file, use source.
Reference
For FB SDK4+Composer: (see the hardcoded video path, and the encoding).
Doc: https://developers.facebook.com/docs/php/gettingstarted/4.0.0
FB requests the video file to be passed encoded as form-data:
https://developers.facebook.com/docs/graph-api/reference/user/videos/
use Facebook\FacebookSession;
use Facebook\GraphSessionInfo;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;
private function postFBVideo($authResponse, $filePath, $formDataMessage)
{
FacebookSession::setDefaultApplication('yourAppkey', 'yourAppSecret');
$ajaxResponse = '';
try {
$session = new FacebookSession($authResponse->accessToken);
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
$ajaxResponse = 'FB Error ->' . json_encode($ex) ;
} catch (\Exception $ex) {
// When validation fails or other local issues
$ajaxResponse = 'FB Validation Error - ' . json_encode($ex) ;
}
if ($session) {
$response = (new FacebookRequest(
$session, 'POST', '/me/videos', array(
'source' => new CURLFile('videos/81JZrD_IMG_4349.MOV', 'video/MOV'),
'message' => $formDataMessage,
)
))->execute();
$ajaxResponse = $response->getGraphObject();
}
return json_encode($ajaxResponse);
}
I spent my last 5 hours in this issue and finally I came here for the solution.
I am doing log-in using twitter functionality in my site (Zend Framework + PHP) and everything is working fine. But I am facing the following issue in it:
If the user has no tweets (0 tweets) in his account then the
$tweets = json_decode($response->getBody());
echo "<pre>";
print_r($tweets);
exit;
Its showing me blank array. i.e. : Array(); :-(
And if I am adding some tweets there in twitter account then its showing me the complete array along with user information like display name, image, etc...like this:
Array
(
//other data
[0] => stdClass Object
(
[user] => stdClass Object
....
....
so on..
)
)
Following is my code :
public function twitterregisterAction() {
$path = realpath(APPLICATION_PATH . '/../library/');
set_include_path($path);
session_start();
require $path . "/Zend/Oauth/Consumer.php";
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
// fetch a request token
$token = $consumer->getRequestToken();
// persist the token to storage
$_SESSION["TWITTER_REQUEST_TOKEN"] = serialize($token);
// redirect the user
$consumer->redirect();
}
/*
* Ticket id #16
* twittercallbackAction method
*/
public function twittercallbackAction() {
$config = array(
"callbackUrl" => "http://" . $_SERVER['HTTP_HOST'] . "/register/twittercallback",
"siteUrl" => "http://twitter.com/oauth",
"consumerKey" => "xxxxxxxxxxxxxxxxxx",
"consumerSecret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
);
$consumer = new Zend_Oauth_Consumer($config);
if (!$this->_getParam("denied")) {
if (!empty($_GET) && isset($_SESSION['TWITTER_REQUEST_TOKEN'])) {
$token = $consumer->getAccessToken($_GET, unserialize($_SESSION['TWITTER_REQUEST_TOKEN']));
} else {
// Mistaken request? Some malfeasant trying something?
exit('Invalid callback request. Oops. Sorry.');
}
// save token to file
// file_put_contents('token.txt', serialize($token));
$client = $token->getHttpClient($config);
$client->setUri('https://api.twitter.com/1/statuses/user_timeline.json?');
$client->setMethod(Zend_Http_Client::GET);
$client->setParameterGet('name');
$client->setParameterGet('profile_image_url');
$response = $client->request();
$tweets = json_decode($response->getBody());
$session = new Zend_Session_Namespace("userIdentity");
Zend_Session::rememberMe(63072000); //2years
$session->tw_id = $tweets[0]->user->id;
$session->tw_name = $tweets[0]->user->name;
$session->tw_image = $tweets[0]->user->profile_image_url;
if ($session->tw_id != "") {
$tw_id = $session->tw_id;
//Calling the function twitterAuthAction for email authentication
$twAuthArr = $this->twitterAuthAction($tw_id);
if ($twAuthArr['socialId'] == $tw_id) {
$session->userId = $twAuthArr['id'];
$session->email = $twAuthArr['emailId'];
$this->_redirect('/profile/showprofile');
} else {
$user = new UserRegistration();
$firstname = "";
$lastname = "";
$password = "";
$socialtype = "twitter";
$email = "";
$socialid = $session->tw_id;
$result = $user->registerUser($firstname, $lastname, $socialid, $socialtype, $email, $password);
$session->userId = $result;
$this->_redirect('/register');
}
}
$this->_redirect("/register");
} else {
$this->_redirect("/register");
}
}
My Questions are :
1) Why its not providing user array if there is no any tweet in my twitter account (or newly created twitter account)
2) I want user profile details from twitter account. How can I get it?
Need Help. Thanks
I think as per david's answer you need to use users/show url there instead of using statuses/user_timeline. You can use curl for requesting url so you'll get the response which contains the users information.
Try with following code:
$user_id = $client->getToken()->getParam('user_id');
$trends_url = "http://api.twitter.com/1/users/show.json?user_id=".$user_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $trends_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
$session = new Zend_Session_Namespace("userIdentity");
Zend_Session::rememberMe(63072000); //2years
$session->tw_id = $response['id'];
$session->tw_name = $response['name'];
$session->tw_image = $response['profile_image_url'];
Try this. Hope it will help you.
I think you are misreading the Twitter API docs for the statuses/user_timeline endpoint.
The field user that you identify is one of the fields within a returned tweet. If the user id to which you point has no tweets, then there will be no entries in the returned array, hence no user field.
If you need the user information even in the absence of any tweets, then you probably need to hit the users/show endpoint.
In one of my application I need to show a YouTube video. If user submits a video then I have to check if that video is alive in YouTube. If OK then I have to save the video id in my database and generate video in web page.
Is there any method for validating YouTube video ?
Use this class to extract and validate youtube video. This works for YT urls like /embed/ , /v/ , ?v= /, youtu.be
class Youtube {
///// Put together by Sugato
////////// $video_id is the youtube video ID /////////////////////////
public $video_id = null;
///////// the Constructer ////////////////////////////////////////
public function __construct($url)
{
if (preg_match('/youtube\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {
$this->video_id = $id[1];
} else if (preg_match('/youtube\.com\/embed\/([^\&\?\/]+)/', $url, $id)) {
$this->video_id = $id[1];
} else if (preg_match('/youtube\.com\/v\/([^\&\?\/]+)/', $url, $id)) {
$this->video_id = $id[1];
} else if (preg_match('/youtu\.be\/([^\&\?\/]+)/', $url, $id)) {
$this->video_id = $id[1];
} else {
$this->video_id = NULL;
}
}
/////////// validates if a youtube video actually exists //////////////
function validate()
{
if(empty($this->video_id))
{
return false;
}
else {
$curl = curl_init("http://gdata.youtube.com/feeds/api/videos/" . $this->video_id);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_exec($curl);
$request = curl_getinfo($curl);
curl_close($curl);
$result = explode(";", $request["content_type"]);
if($result[0] == "application/atom+xml")
{
return true;
} else {
return false;
}
}
}
}
Call the class like this
$yt = new Youtube($your_video_link_here);
$exist = $yt->validate();
if($exist)
{
echo "Yaaaayyyyyy!";
} else
{
echo "nAAAAyyyy!!!";
}
If the user is flat-out submitting a video, you would have to have something like a database which contains hashes for existing videos to compare it with (ex: the SHA checksum), then check if the hash is already present. As far as I know, Google/YouTube provide no such database for the public to use, but you could start your own for the videos that users submit through your service. There are other more advanced techniques you could use, but they would require access to all of the existing video files for analysis... which is not available.
As far as getting the video URL, when you upload a video to YouTube you can link to it or embed it in a webpage.
Could anyone help me figure out how to post to tumblr using php.
I tried googling for a library or a sample code but couldn't find one. all I can find is this here https://github.com/alexdunae/tumblr-php/blob/master/Tumblr.php and it doesnt seem to work also I looked and tried the code on v1 api at tumblr website that doesnt work either ....
function post($data){
if(function_exists("curl_version")){
$data["email"] = $this->email;
$data["password"] = $this->password;
$data["generator"] = $this->generator;
$request = http_build_query($data);
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c,CURLOPT_POST,true);
curl_setopt($c,CURLOPT_POSTFIELDS,$request);
curl_setopt($c,CURLOPT_RETURNTRANSFER,true);
$return = curl_exec($c);
$status = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if($status == "201"){
return true;
}
elseif($status == "403"){
return false;
}
else{
return "error: $return";
}
}
else{
return "error: cURL not installed";
}
}
Thanks for the help
I just noticed that this is showing up as Featured for Tumblr and I want to say this: As of 2012, you should IGNORE the above answer by Tuga because it DOES NOT work with the newest Tumblr API.
What you need is TumblrOAuth which is built from OAuth Sandbox.
It is only setup to read and write Tumblr posts, so if you want to do more than that, you'll need to alter the code. I used it as my code base for Followr.
Stolen from http://www.tumblr.com/docs/en/api
// Authorization info
$tumblr_email = 'info#davidville.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'regular';
$post_title = 'The post title';
$post_body = 'This is the body of the post.';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'title' => $post_title,
'body' => $post_body,
'generator' => 'API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('http://www.tumblr.com/api/write');
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
?>
$conskey = "CONSUMER KEY";
$conssec = "CONSUMER SECRET";
$tumblr_blog = "myblog.tumblr.com";
$to_be_posted = "This is the text to be posted";
$oauth = new OAuth($conskey,$conssec);
$oauth->fetch("http://api.tumblr.com/v2/blog/".$tumblr_blog."/post", array('type'=>'text', 'body'=>$to_be_posted), OAUTH_HTTP_METHOD_POST);
$result = json_decode($oauth->getLastResponse());
if($result->meta->status == 200){
echo 'Success!';
}
This code will let you post to your tumblr blog using tumblr API.
I hope this code helps.
The api example provided by Tuga is working for me (on Wordpress)...so I think your problem lies elsewhere, and not with the example provided. I would also be very appreciative if you guys got a version 2 api working if you could post it.