I have been trying for quite a while to check if submitted links are valid film-clips from youtube.com or vimeo.com but I didn't succeed.
Any ideas how to check url's like:
http://www.youtube.com/watch?v=jc0rnCBCX2c&feature=fvhl (valid)
http://www.youtube.com/watch?v=jc0FFCBCX2c&feature=fvhl (not valid)
http://www.youtube.com/v/jc0rnCBCX2c (valid)
http://www.youtube.com/v/ddjcddddX2c (not valid)
http://www.vimeo.com/463l522 (not valid)
http://www.vimeo.com/1483909 (valid)
http://www.vimeo.com/lumiblue (not valid)
http://www.youtube.com/user/dd181921 (not valid)
?
I use php.
If you check the response headers from a request to http://gdata.youtube.com/feeds/api/videos/videoId where videoId is the google video Identifier, you should get a 200 if the video exists and a 400 (bad request) if the video doesn't exist.
// PHP code
// Check if youtube video item exists by the existance of the the 200 response
$headers = get_headers('http://gdata.youtube.com/feeds/api/videos/' . $youtubeId);
if (!strpos($headers[0], '200')) {
echo "The YouTube video you entered does not exist";
return false;
}
i see a answer in this site :
www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_23765374.html
and he said :
I would suggest using youtube's API since you are trying to validate if the video exists.
or if you don't want to go into API stuff then you can do simple trick.
check this link:
http://code.google.com/apis/youtube/developers_guide_php.html#RetrievingVideoEntry
to check for the existence of a video you will need to extract "v" value and send a request that contains the video id to :
http://gdata.youtube.com/feeds/api/videos/videoID
where videoID is the "v" value
for example a video FLE2htv9oxc
will be queried like this
http://gdata.youtube.com/feeds/api/videos/FLE2htv9oxc
if it does not exist then you will get a page with "Invalid id"
if it exists, will return an XML feed having various info about the video.
this way you can check that the video exists.
hope this will get you in the right direction.
the same thing with vimeo , try to look in api documentation in there site.
http://www.vimeo.com/api
I wrote this function to check if the link is a valid youtube link.
/**
* This function will check if 'url' is valid youtube video and return the ID.
* If the return value === false then this is **not** a valid youtube url, otherwise the youtube id is returned.
*
* #param <type> $url
* #return <type>
*/
private static function get_youtube_id($url) {
$link = parse_url($url,PHP_URL_QUERY);
/**split the query string into an array**/
if($link == null) $arr['v'] = $url;
else parse_str($link, $arr);
/** end split the query string into an array**/
if(! isset($arr['v'])) return false; //fast fail for links with no v attrib - youtube only
$checklink = YOUTUBE_CHECK . $arr['v'];
//** curl the check link ***//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$checklink);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$result = curl_exec($ch);
curl_close($ch);
$return = $arr['v'];
if(trim($result)=="Invalid id") $return = false; //you tube response
return $return; //the stream is a valid youtube id.
}
You can try to catch the 301 header that you tube throws if the video is no longer valid
/*
* Verify YouTube video status
*/
$videoID = "o8UCI7r1Aqw";
$header = get_headers("http://gdata.youtube.com/feeds/api/videos/". $videoID);
switch($headers[0]) {
case '200':
// video valid
break;
case '403':
// private video
break;
case '404':
// video not found
break;
default:
// nothing above
break;
}
Since most of the comments here are a bit old, here's a quick thing I set up that checks if YouTube links are private or not.
The good thing about this approach is that it doesn't require us to set up API Credentials with Google or anything like that. I will assume that you would be able to follow the same approach with Vimeo or any other video provider that doesn't provide accurate status codes on request.
axios
.get(link)
.then((res) => {
if (StringUtils.isYouTubeLink(link)) {
// The "streamingData" substring should be present on
// all valid video requests. Private or non-existent
// videos won't have it
if (!res.data.includes("streamingData")) {
errorData.reason = "Video unavailable";
brokenLinks.push(errorData);
}
}
})
Related
i am trying to dynamically generate the goo.gl links via function.php ,when a post is created ...but its not getting updating the field with the link created on localhost..and i just cant figure out the issue
function newlinks($post_id){
$permaurl=get_permalink($post_id);
$shorturl=make_my_url($permaurl);
update_post_meta('$post_id','shorturl',$shorturl)
}
add_action( 'save_post', 'newlinks' );
function make_my_url($myurl)
{
//got te key from https://console.developers.google.com/iam-admin/projects
$key = 'AIzBP0';
$googer = new GoogleURLAPI($key);
// Test: Shorten a URL
$shortDWName = $googer->shorten($myurl);
return $shortDWName; // returns the short url
}
// Declare the class
class GoogleUrlApi {
// Constructor
function GoogleURLAPI($key,$apiURL = 'https://www.googleapis.com/urlshortener/v1/url') {
// Keep the API Url
$this->apiURL = $apiURL.'?key='.$key;
}
// Shorten a URL
function shorten($url) {
// Send information along
$response = $this->send($url);
// Return the result
return isset($response['id']) ? $response['id'] : false;
}
// Send information to Google
function send($url,$shorten = true) {
// Create cURL
$ch = curl_init();
// If we're shortening a URL...
if($shorten) {
curl_setopt($ch,CURLOPT_URL,$this->apiURL);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
curl_setopt($ch,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
}
else {
curl_setopt($ch,CURLOPT_URL,$this->apiURL.'&shortUrl='.$url);
}
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Execute the post
$result = curl_exec($ch);
// Close the connection
curl_close($ch);
// Return the result
return json_decode($result,true);
}
}
your code is good. I've created my own API key and tried this and works fine. The problem may be in google console.
Please login to https://developers.google.com/apis-explorer/?hl=pl#p/urlshortener/v1/ and try to generate short url there. Google should ask you to authorize the key you created before. After that code should work fine.
I am using google drive php sdk to get the content of the files on google drive but i am not understanding that how can i download the content i tried this function
function downloadFile($service, $file)
{
if ($file) {
$request = new Google_HttpRequest($file, 'GET', null, null);
$httpRequest = Google_Client::$io->authenticatedRequest($request);
echo $httpRequest->getResponseHttpCode();
if ($httpRequest->getResponseHttpCode() == 200) {
return $httpRequest->getResponseBody();
} else {
// An error occurred.
//return null;
//echo "error";
print_r($httpRequest);
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
calling this function like this
$down=downloadFile($service, $divefl['webContentLink']);
if i pass webContentLink link it is giving the response code 302 that means file temperately moved . and if i pass alternateLink it is giving an error code 401 i.e unauthorize . please help me how can i get the content
I think you need to provide the downloadURL.
If you provide webContentLink, this is if you want to create a link in the browser and locally download this file.
Unfortunately in my system this didn't work either, since the API has changed.
I have read a lot about it but i still don't completely get it.
I may use a library of an existing solution in the future but i want to understand and implement my own system right now.
In order to be stateless and scalable I think i mustn't store user context on server.
The main problem is a conception one, if i understand the system i will succeed to code it
I have tested code found on Internet which i have modified (french website ref : http://blog.nalis.fr/index.php?post/2009/09/28/Securisation-stateless-PHP-avec-un-jeton-de-session-(token)-protection-CSRF-en-PHP).
Can you tell me if it's correct or if i don't get it?
So to create a token i use this function which takes as parameters, the user's data
define('SECRET_KEY', "fakesecretkey");
function createToken($data)
{
/* Create a part of token using secretKey and other stuff */
$tokenGeneric = SECRET_KEY.$_SERVER["SERVER_NAME"]; // It can be 'stronger' of course
/* Encoding token */
$token = hash('sha256', $tokenGeneric.$data);
return array('token' => $token, 'userData' => $data);
}
So a user can authentified himself and receive an array which contains a token (genericPart + his data, encoded), and hisData not encoded :
function auth($login, $password)
{
// we check user. For instance, it's ok, and we get his ID and his role.
$userID = 1;
$userRole = "admin";
// Concatenating data with TIME
$data = time()."_".$userID."-".$userRole;
$token = createToken($data);
echo json_encode($token);
}
Then the user can send me his token + his un-encoded data in order to check :
define('VALIDITY_TIME', 3600);
function checkToken($receivedToken, $receivedData)
{
/* Recreate the generic part of token using secretKey and other stuff */
$tokenGeneric = SECRET_KEY.$_SERVER["SERVER_NAME"];
// We create a token which should match
$token = hash('sha256', $tokenGeneric.$receivedData);
// We check if token is ok !
if ($receivedToken != $token)
{
echo 'wrong Token !';
return false;
}
list($tokenDate, $userData) = explode("_", $receivedData);
// here we compare tokenDate with current time using VALIDITY_TIME to check if the token is expired
// if token expired we return false
// otherwise it's ok and we return a new token
return createToken(time()."#".$userData);
}
$check = checkToken($_GET['token'], $_GET['data']);
if ($check !== false)
echo json_encode(array("secureData" => "Oo")); // And we add the new token for the next request
Am I right?
Sorry for this long message and sorry for my english.
Thanks in advance for your help!
The problem in your code is: You are basing your entire system on $_GET in the original post is based on Cookies.. You should store the token in cookies (based on your original post, instead of using $_GET
By the way; a few tweaks:
list($tokenDate, $userData) = array_pad(explode("_", $receivedData));
In the next code I don't see how you use $login,$password
function auth($login, $password)
{
// we check user. For instance, it's ok, and we get his ID and his role.
$userID = 1;
$userRole = "admin";
// Concatenating data with TIME
$data = time()."_".$userID."-".$userRole;
$token = createToken($data);
echo json_encode($token);
}
I've got a Flash app that includes a twitter share for a customized mini application.
I'm achieving this very simply using flashvars passed in via a php querystring so your custom colour and message are passed to the mini-app.
The problem of course is url length for twitter so i'm looking to use the bit.ly api for php to shorten the dynamic url and pass that hashed url back to flash.
I've written a function to do this which works fine however it is chopping off the second querystring parameter after the first '&' symbol?
So for example, the following function running the url 'http://s46264.gridserver.com/apps/soundgirl/fbwall.php?colour=red&message=twittertest'
Gets shortened to http://bit.ly/i4kfj0 which, when parsed becomes http://s46264.gridserver.com/apps/soundgirl/fbwall.php?colour=red
It's chopping off the second querystring parameter. Anyone know of a way I can stop this from happening?
Thanks.
<?php
function bitly_shorten($url)
{
$username = "modernenglish";
$apikey = "myapikey";
$response = file_get_contents("http://api.bit.ly/v3/shorten?login=$username&apiKey=$apikey&longUrl=$url&format=json");
$response = json_decode($response);
if ($response->status_code == 200 && $response->status_txt == "OK")
{
return $response->data->url;
} else
{
return null;
}
}
$link = urldecode("http://s46264.gridserver.com/apps/soundgirl/fbwall.php?colour=red&message=twittertest");
echo bitly_shorten($link);
?>
Maybe try:
No urldecode() before calling bitly_shorten():
$link = "http://s46264.gridserver.com/apps/soundgirl/fbwall.php?colour=red&message=twittertest";
Add urlencode() on the URL into your bitly_shorten() function:
$response = file_get_contents("http://api.bit.ly/v3/shorten?login=$username&apiKey=$apikey&longUrl=".urlencode($url)."&format=json");
In my project, users insert a Google Video code into a textbox - I'd like to certify that the video being referenced does indeed exist. I'm presently using the YouTube API to do something similar with YouTube references, but I'm not sure what would be the best method with Google Video. Any direction would be appreciated.
Can you request the URL and see if it 404s or not?
function googleVideoExist($id) {
// Validate id however you need to
$id = (int) $id;
$headers = get_headers('http://video.google.com/videoplay?docid=' . $id, TRUE);
// get_headers() follows Location: headers,
// and they are all sent back in sequential order
foreach(array_reverse($headers) as $header => $value) {
if (strstr($value, '200')) {
return TRUE;
}
}
return FALSE;
}
URL above is a guide only - adapt it to suit. Also, you can use cURL if you are more comfortable with that.