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.
Related
I have a script on my website, to prevents bots, it works fine but since i modified it to make changes i had a lot of errors, i'm not good at php.
<?php
error_reporting();
session_start();
$config_antibot['apikey'] = '________________________';
$config_antibot['bot'] = 'https://google.com';
$config_antibot['real'] = 'https://mywebsite.com';
class Antibot
{
function apikey($api_key){
$this->apikey = $api_key;
}
function get_client_ip()
{
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
$_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
function httpGet($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
return $response;
}
function check(){
$ip = $this->get_client_ip();
$respons = $this->httpGet("https://antibot.pw/api/v2-blockers?ip=".$ip."&apikey=".$this->apikey."&ua=".urlencode($_SERVER['HTTP_USER_AGENT']));
$json = json_decode($respons,true);
if($json['is_bot'] == 1 || $json['is_bot'] == true){
return true;
}else{
return false;
}
}
}
$Antibot = new Antibot;
$Antibot->apikey( $config_antibot['apikey'] );
if($Antibot->check() == true){
die(header("location: ".$config_antibot['bot']));
}else{
die(header("location: ".$config_antibot['real']));
}
?>
The lines that i tried to change
Line 7
$config_antibot['real'] = 'https://mywebsite.com';
Line 63
die(header("location: ".$config_antibot['real']));
Line 7 If the visitor is real not a bot it redirected to my website, but this redirect is causing a problem and affecting the nature of my website
Because when users sign up and get link mywebsite.com/user/02331/index?ref=02331 via email to activate their account, the user is redirected to mywebsite.com the user cannot not check mywebsite.com/user/02331/index?ref=02331 to complete registration
i change in line 63 to
die( header("HTTP/1.1 401 Unauthorized") );
exit();
}
But that doesn't seem to work for me, is there a way to let the user stay on the current url that the user is browsing if the user is real and not a bot?
What you're trying to create is a middleware (https://laravel.com/docs/8.x/middleware for laravel), or chain of responsibility (https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern). Depending on how you have it structured at the moment, this could mean you need to change the entire architecture of your code, which obviously isn't a great solution.
Ideally, you would have a router or some such that you can call here:
}else{
Route::get( ... );
// die(header("location: ".$config_antibot['real']));
}
You don't need to die() into the next portion of your site, you just need the page that they want to load to appear instead of the redirect. This could be done in any number of ways, but the die() portion is probably the least best option of them.
How to get live video id from YouTube channel using simple HTML dom parser or any other method rather than YouTube api?
https://www.youtube.com/embed/live_stream?channel=UC8Z-VjXBtDJTvq6aqkIskPg&autoplay=1
Because YouTube api does not work to get live video id.
Finaly i fund answer
function getvideourl($chid)
{
$videoId = null;
// Fetch the livestream page
if($data = file_get_contents('https://www.youtube.com/embed/live_stream?
channel='.$chid))
{
// Find the video ID in there
if(preg_match('/\'VIDEO_ID\': \"(.*?)\"/', $data, $matches))
$videoId = $matches[1];
else
$videoId ="";
}
else
throw new Exception('Couldn\'t fetch data');
$video_url = "https://www.youtube.com/embed/".$videoId;
return $video_url;
}
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";
https://coinbase.com/api/v1/transactions/send_money?api_key=xxx
I have that URL but after the api_key paramter what comes next (I blocked out my API Key so people can't access my BTC)?
Can someone give me an example of how to properly use coinbase's send_money API?
I don't have a PHP environment handy to test this with but I think it would go like this:
Get their PHP library: https://github.com/coinbase/coinbase-php
<?php
require_once(dirname(__FILE__) . '/../lib/Coinbase.php');
// Create an application at https://coinbase.com/oauth/applications and set these values accordingly
$_CLIENT_ID = "83a481f96bf28ea4bed1ee8bdc49ba4265609efa40d40477c2a57e913c479065";
$_CLIENT_SECRET = "a8dda20b94d09e84e8fefa5e7560133d9c5af9da93ec1d3e79ad0843d2920bbb";
// Note: your redirect URL should use HTTPS.
$_REDIRECT_URL = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$coinbaseOauth = new Coinbase_OAuth($_CLIENT_ID, $_CLIENT_SECRET, $_REDIRECT_URL);
if(isset($_GET['code'])) {
// Request tokens
$tokens = $coinbaseOauth->getTokens($_GET['code']);
// The user is now authenticated! Access and refresh tokens are in $tokens
// Store these tokens safely, and use them to make Coinbase API requests in the future.
// For example:
$coinbase = new Coinbase($coinbaseOauth, $tokens);
try {
echo 'Balance: ' . $coinbase->sendMoney($to, $amount, $notes=null, $userFee=null, $amountCurrency=null) . '<br>';
echo $coinbase->createButton("Alpaca socks", "10.00", "CAD")->embedHtml;
} catch (Coinbase_TokensExpiredException $e) {
$newTokens = $coinbaseOauth->refreshTokens($tokens);
// Store $newTokens and retry request
}
} else {
// Redirect to Coinbase authorization page
// The provided parameters specify the access your application will have to the
// user's account; for a full list, see https://coinbase.com/docs/api/overview
// You can pass as many scopes as you would like
echo "Connect with Coinbase";
}
Here is the send money code
public function sendMoney($to, $amount, $notes=null, $userFee=null, $amountCurrency=null)
{
$params = array( "transaction[to]" => $to );
if($amountCurrency !== null) {
$params["transaction[amount_string]"] = $amount;
$params["transaction[amount_currency_iso]"] = $amountCurrency;
} else {
$params["transaction[amount]"] = $amount;
}
if($notes !== null) {
$params["transaction[notes]"] = $notes;
}
if($userFee !== null) {
$params["transaction[user_fee]"] = $userFee;
}
return $this->post("transactions/send_money", $params);
}
In an iframe .php app, how to detect itself is in a Page mode or in the Canvas mode? Thanks!
Reading the documentation:
Facebook will always send a signed_request (for canvas and page urls)
If it's a page, Facebook will add an extra parameter called page
so based on this, you could do something like:
<?php
if( isset($_REQUEST['signed_request']) ) {
// We are in Canvas or Page now
// Let's extract the data from the signed_request
// to check if we are inside a Facebook Page
$app_secret = "APP_SECRET";
$data = parse_signed_request($_REQUEST["signed_request"], $app_secret);
if( isset($data["page"]) ) {
echo "Page";
} else {
echo "Canvas";
}
} else {
echo "None, or something went wrong!";
}
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
?>
I also had to add website in the criteria. This is my Yii code
if(empty($_POST['signed_request']) === false)
$signedRequest = Yii::app()->fb->getSignedRequest();
if(isset($signedRequest['page']))
$this->layout = 'tab';
else if(isset($signedRequest['user']) && ! isset($signedRequest['page']))
$this->layout = 'canvas';
else
$this->layout = 'website';
Thanks to #ifaour solution;
I had to modify it to get it work;
This what worked for me;
I noticed that signed request is only sent when site is loaded under canvas; but when direct access then no signed request is sent.
So I ended using this code:
if( !isset($_SESSION['signed_request']) && empty($_SESSION['signed_request']) ) {
exit("direct access not allowed.");
}
else
{
// echo 'Canvas';
// continue script
}