importing gmail contacts using php - oauth-2.0

May be am creating a lot of confusion with the previous post, so am trying redesign my entire post with my requirement and effort.
I want to fetch GMAIL contact list using PHP, to achieve this I have done the following thing:
Create Google Client ID with oAuth 2.0 protocol
Create 2 PHP files (oAuth.php and index.php)
Here is the code for 2 files:
oAuth.php:
<html>
<head>
<meta name="robots" content="noindex" />
<title>Email address list - Import Gmail or Google contacts</title>
<style type="text/css">
a:link {color:Chocolate;text-decoration: none;}
a:hover {color:CornflowerBlue;}
.logo{width:100%;height:110px;border:2px solid black;background-color:#666666;}
</style>
</head>
<body>
<div class="logo" >
</div>
<br/>
<div><b>Visit Tutorial: </b><a style="font-size:17px;" href="" >Import Gmail or Google contacts using Google Contacts Data API 3.0 and OAuth 2.0 in PHP</a></div>
<br/>
<div style="padding-left: 50px;">
<?php
$client_id = '1041526369396-kmnbhsos616eqcqimjrs07icn2c176ln.apps.googleusercontent.com';
$client_secret = '*************';
$redirect_uri = 'https://www.test.multicon.in/test9/oauth.php';
$max_results = 25;
$auth_code = $_GET["code"];
function curl_file_get_contents($url)
{
$curl = curl_init();
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';
curl_setopt($curl,CURLOPT_URL,$url); //The URL to fetch. This can also be set when initializing a session with curl_init().
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5); //The number of seconds to wait while trying to connect.
curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); //The contents of the "User-Agent: " header to be used in a HTTP request.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); //To follow any "Location: " header that the server sends as part of the HTTP header.
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); //To automatically set the Referer: field in requests where it follows a Location: redirect.
curl_setopt($curl, CURLOPT_TIMEOUT, 10); //The maximum number of seconds to allow cURL functions to execute.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); //To stop cURL from verifying the peer's certificate.
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$contents = curl_exec($curl);
curl_close($curl);
return $contents;
}
$fields=array(
'code'=> urlencode($auth_code),
'client_id'=> urlencode($client_id),
'client_secret'=> urlencode($client_secret),
'redirect_uri'=> urlencode($redirect_uri),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($curl,CURLOPT_POST,5);
curl_setopt($curl,CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$accesstoken = $response->access_token;
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&oauth_token='.$accesstoken;
$xmlresponse = curl_file_get_contents($url);
if((strlen(stristr($xmlresponse,'Authorization required'))>0) && (strlen(stristr($xmlresponse,'Error '))>0))
{
echo "<h2>OOPS !! Something went wrong. Please try reloading the page.</h2>";
exit();
}
echo "<h3>Email Addresses:</h3>";
$xml = new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
$result = $xml->xpath('//gd:email');
foreach ($result as $title) {
echo $title->attributes()->address . "<br>";
}
?>
</div>
</body></html>
And index.php
<html>
<head>
<meta name="robots" content="noindex" />
<title>Import Gmail or Google contacts using Google Contacts Data API 3.0 and OAuth 2.0</title>
<style type="text/css">
a:link {color:Chocolate;text-decoration: none;}
a:hover {color:CornflowerBlue;}
.logo{width:100%;height:110px;border:2px solid black;background-color:#666666;}
</style>
</head>
<body>
<div class="logo" >
</div>
<br/>
<div><b>Visit Tutorial: </b><a style="font-size:17px;" href="http://test.multicon.in/test9/" >Import Gmail or Google contacts using Google Contacts Data API 3.0 and OAuth 2.0 in PHP</a></div>
<br/><br/>
<div align="center" >
<a style="font-size:25px;font-weight:bold;" href="https://accounts.google.com/o/oauth2/auth?client_id=1041526369396-kmnbhsos616eqcqimjrs07icn2c176ln.apps.googleusercontent.com&redirect_uri=https://www.test.multicon.in/test9/oauth.php&scope=https://www.google.com/m8/feeds/&response_type=code">Click here to Import Gmail Contacts</a>
</div>
</body>
</html>
Now while clicking on the links in index.php it shows me that the My Project wants to access my Gmail contact...but when it takes me to the redirected page...it shows page not available whereas that page is there. I don't know whether am clear to you or not...if possible please check the link http://test.multicon.in/test9/index.php may be this will help you to understand my problem

finally...I have resolved this issue, the my domain was not added with WWW records, that's why I was getting the error "DNS_PROBE_FINISHED_NXDOMAIN", the moment I have added the WWW records for test.multicon.in,the error resolved

Related

Token Generation for Botframework Webchat

I've been migrating my Direct Line Bot from Webchat v3 to v4.
The new version demands the use of tokens rather than the Direct Line secret in the calling page.
Here is the code (index.html) used to start the bot:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Full-featured bundle</title>
<script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
<style>
html, body {
height: 100%
}
body {
margin: 0
}
#webchat,
#webchat > * {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
const res = await fetch('https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token', { method: 'POST' });
const { token } = await res.json();
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token })
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
Question:
What code do I need to write to generate the token in other to be called by https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token ??
Realize it's got to be something like
POST https://directline.botframework.com/v3/directline/tokens/generate
Authorization: Bearer SECRET
but I don't know if it's got to be a php, js or other type of file to work.
Thanks in advance
I used php to solve this. You could give it a try.
<?php
$botSecret = '<your secret>';
$response = wp_remote_get( 'https://webchat.botframework.com/api/tokens', array( 'headers' => 'Authorization: BotConnector ' . $botSecret ) );
if( is_array($response) ) {
$header = $response['headers'];
$token = $response['body'];
}
?>
<script type="text/javascript">
var webChatToken = <?php echo $token; ?>;
</script>
I had the same issue yesterday, I just post it here in case it helps anyone in the future. If you change your code to this it should work:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Full-featured bundle</title>
<script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>
<style>
html, body {
height: 100%
}
body {
margin: 0
}
#webchat,
#webchat > * {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
const res = await fetch('https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token',
{ method: 'POST', headers: { Authorization: 'write your direct line secret here' }});
const { token } = await res.json();
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token })
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
</script>
</body>
</html>
You had to add the authorization in the header of the post request to generate the token in the async function. Unfortunately this might not be obvious from Microsoft's documentation on how the generate the token
What you need to do is implement some kind of server side logic using whatever technology you're most comfortable with that uses the secret, which is kept only on your server, to generate a new token by making an HTTP request to the DirectLine channel as you point out above. Then, in your web page's start up logic, you make a request to get that token and, with the token, initialize the direct line instance in the web page. Using this approach ensures that nobody external ever gets a hold of your secret.
So, there is no one type of file to "make it work". You will need to choose Node, PHP, ASP.NET or any other server technology and implement it in the way you would any other HTTP request handler.
This article will help in understanding the authentication concepts and APIs and here's a blog post that shows how you might do it with ASP.NET and Node.

Google+ oauth / 0auth API: How can I prevent redirection by google-signin2 button?

I am just learning the basics of Google´s API 0auth authentication sign-in system.
I'm using this tutorial found on CodexWorld. Although this one worked out, it uses an ugly picture instead of a "real" google sign-in button (from the g-signin2 class), and that´s something I personally just can´t get over.
I tried replaced the picture with that button and added the required metas to work with it. But now it opened 2 windows, not only 1 through the php.
How can i prevent the second window, opened by the g-signin2-button, from opening?
Thanks for all your help!
VicStudio
Here´s the modified code by me. Notice how I replaced the picture button with a real google-signin2 button and added the required metas.
<?php
//Include GP config file && User class
include_once 'gpConfig.php';
include_once 'classuser.php';
if(isset($_GET['code'])){
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken();
header('Location: ' . filter_var($redirectURL, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$gClient->setAccessToken($_SESSION['token']);
}
if ($gClient->getAccessToken()) {
//Get user profile data from google
$gpUserProfile = $google_oauthV2->userinfo->get();
//Initialize User class
$user = new User();
//Insert or update user data to the database
$gpUserData = array(
'oauth_provider'=> 'google',
'oauth_uid' => $gpUserProfile['id'],
'email' => $gpUserProfile['email'],
'link' => $gpUserProfile['link']
);
$userData = $user->checkUser($gpUserData);
//Storing user data into session
$_SESSION['userData'] = $userData;
//Render facebook profile data
if(!empty($userData)){
$output = '<h1>Google+ Profile Details </h1>';
$output .= '<br/>Google ID : ' . $userData['oauth_uid'];
$output .= '<br/>Email : ' . $userData['email'];
$output .= '<br/>Logged in with : Google';
$output .= '<br/>Click to Visit Google+ Page';
$output .= '<br/>Logout from Google';
}else{
$output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
}
} else {
//New, modified code:
$authUrl = $gClient->createAuthUrl();
$authUrl = filter_var($authUrl, FILTER_SANITIZE_URL);
$output = "<div class='g-signin2' data-onsuccess='onSignIn' id='glog'></div> <script>document.getElementById('glog').onclick = function () { window.location.href = '".$authUrl."'; } </script>";
//Original Code:
// $authUrl = $gClient->createAuthUrl();
// $output = '<img src="images/glogin.png" alt=""/>';
}
?>
<html>
<head>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="246194741577-gajd75di0cam2j9u4q69l9trvg88hqkc.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div><?php echo $output; ?></div>
</body>
</html>

Google service account open p12 for "access token"

I have this code (see end of question) and all I have to do is put in my access token, the thing is I've downloaded the p12 file and whenever I try to open it, I just get some Microsoft certificate program that doesn't tell me the stuff I need, how do I go about getting inside this p12 file to get the access token that its asking for?
Thanks.
<!doctype html>
<html lang="en">
<head>
<title>Google Charts</title>
<script>
(function(w,d,s,g,js,fs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
</script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
gapi.analytics.ready(function() {
var ACCESS_TOKEN = '???'; // obtained from your service account
gapi.analytics.auth.authorize({
serverAuth: {
access_token: ACCESS_TOKEN
}
});
var data = new gapi.analytics.report.Data({
query: {
ids: 'ga:????????',
metrics: 'ga:users,ga:sessions,ga:bounceRate',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'output': 'dataTable',
}
});
data.execute();
data.on('success', function(response) {
var data = new google.visualization.DataTable(response.dataTable);
var formatter = new google.visualization.NumberFormat({fractionDigits: 2});
formatter.format(data, 1);
var table = new google.visualization.Table(document.getElementById('test'));
table.draw(data);
});
});
google.load('visualization', '1', {'packages':['table']});
google.setOnLoadCallback(table);
</script>
</head>
<body>
<div>
<div id="embed-api-auth-container"></div>
<div id="test"></div>
</div>
</body>
</html>
Don't try and use a service account with the embed API. Use normal oauth 2 as shown in the documentation Embeded API Getting started
gapi.analytics.ready(function() {
// Step 3: Authorize the user.
var CLIENT_ID = 'Insert your client ID here';
gapi.analytics.auth.authorize({
container: 'auth-button',
clientid: CLIENT_ID,
});
// Step 4: Create the view selector.
var viewSelector = new gapi.analytics.ViewSelector({
container: 'view-selector'
});
If you must use a service account I suggest you drop the embedded API and use a scripting language like PHP directly with the reporting API.

How to process backend coldfusion processing script response

I have implemented plupload using a ColdFusion backend script (available at https://gist.github.com/1116037).
The url attribute in the uploading page is url : '../upload.cfc?method=upload',
This simply calls a function within the cfc script. It works fine. This script also creates a variable called 'response' to hold information uploaded files.
The problem I am having is accessing the information held in the 'response' variable.
I would like to display that information in a table after the all the files have been uploaded to the server.
I am using the queue_widget for my needs’ think that an event (onComplete) needs to be triggered to call a function to process the information in variable, but I don't know how to do this.
I need to access the information held in the 'response' variable, preferably in ColdFusion code. Has anyone managed to get plupload working with ColdFusion yet?
Any help, guidance or coding would be appreciated.
Here is the full code I have used:
This is the main page - queue_widget.cfm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Plupload - Queue widget example</title>
<link rel="stylesheet" href="../../js/jquery.plupload.queue/css/jquery.plupload.queue.css" type="text/css" media="screen" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="../../js/plupload.js"></script>
<script type="text/javascript" src="../../js/plupload.flash.js"></script>
<script type="text/javascript" src="../../js/jquery.plupload.queue/jquery.plupload.queue.js"></script>
</head>
<body>
<h1>Queue widget example</h1>
<p>Shows the jQuery Plupload Queue widget and under different runtimes.</p>
<div style="float: left; margin-right: 20px">
<h3>Flash runtime</h3>
<div id="flash_uploader" style="width: 700px;">Your browser does not have Flash installed!</div>
</div>
<br style="clear: both" />
<cfoutput><cfset mnum=6></cfoutput>
<script type="text/javascript">
$(function() {
// Setup flash version
$("#flash_uploader").pluploadQueue({
// General settings
runtimes : 'flash',
url : '../upload.cfc?method=upload',
max_file_size : '1mb',
max_file_count: <cfoutput>#mnum#</cfoutput>, // You can limit the num of files that can be uploaded by manipulating the mnum variable above
unique_names : false,
multiple_queues : true,
multi_selection: true,
filters : [
{title : "Image files", extensions : "jpg,gif,png"}
],
init : {
FilesAdded: function(up, files) {
plupload.each(files, function(file) {
if (up.files.length > <cfoutput>#mnum#</cfoutput>) {
up.removeFile(file);
}
});
if (up.files.length >= <cfoutput>#mnum#</cfoutput>) {
$('#pickfiles').hide('slow');
}
},
FilesRemoved: function(up, files) {
if (up.files.length < 1) {
$('#pickfiles').fadeIn('slow');
}
}
},
resize : {width : 300, height : 10000, quality : 90}, // forces images to be resized to a width of 300px if wider than 300px
preinit: attachCallbacks,
UploadComplete: function(up, file, response) {
if ($("#result").length > 0){
$("#results").prepend(info.response);
} else {
$("#flash_uploader").after("<div id='results'>"+info.response+"</div>");
}
},
flash_swf_url : '../../js/plupload.flash.swf'
});
});
// Where should we go after upload
function attachCallbacks(Uploader){
Uploader.bind('FileUploaded', function(Up, File, response){
function IsJson(response) {
alert('Response from server: ' + response.file); // for testing only
counter++
var newRow = '<tr><td><input type="hidden" name="file_'+counter+'" value="'+response.file+'">'
newRow += 'Label the file: '+response.file+' <input type="text" name="filename_'+counter+'"></td></tr>'
$("#detail").append(newRow)
}});
};
</script>
<div id="results"></div>
<table id="detail">
</table>
<cfif IsDefined('response')><cfdump var="#response#"></cfif>
</body>
</html>
This the backend processing page - upload.cfc
<cfcomponent>
<cffunction name="upload" access="remote" returntype="struct" returnformat="json" output="false">
<cfscript>
var uploadDir = expandPath('/uploads/'); // should be a temp directory that you clear periodically to flush orphaned files
var uploadFile = uploadDir & arguments.NAME;
var response = {'result' = arguments.NAME, 'id' = 0};
var result = {};
</cfscript>
<!--- save file data from multi-part form.FILE --->
<cffile action="upload" result="result" filefield="FILE" destination="#uploadFile#" nameconflict="overwrite"/>
<cfscript>
// Example: you can return uploaded file data to client
response['size'] = result.fileSize;
response['type'] = result.contentType;
response['saved'] = result.fileWasSaved;
return response;
</cfscript>
</cffunction>
</cfcomponent>
You can try the above example here: [url] www.turn2cash.co.uk/plupload/examples/jquery/queue_widget.cfm [/url]
As mentioned above, the script works well with uploading (in this case) upto 6 images as determined by the mnum variable. What I need help with is with how to access the uploaded files (with page refresh) and be able to manipulate them.
I have setup an example (using cffileupload) of what I am after here [url] www turn2cash.co.uk/a/index.cfm [/url]
Although this works fine, it requires a page refresh, which is what I am trying to avoid.
Please provide any help you can.
Added 7 september 2012
I have tried both methods suggested by Miguel but did not achieve any positive outcomes. They actually caused the UI not to sow at all. However I found this and tried it:
preinit: attachCallbacks,
UploadComplete: function(up, file, response) {
if ($("#result").length > 0){
$("#results").prepend(info.response);
} else {
$("#flash_uploader").after("<div id='results'>"+info.response+"</div>");
}
},
flash_swf_url : '../../js/plupload.flash.swf'
});
});
// Where should we go after upload
function attachCallbacks(Uploader){
Uploader.bind('FileUploaded', function(Up, File, Response){
alert('Response from server: ' + Response.response);
});
};
</script>
I now get an alert displaying:
Response from server: {"saved":true,"result":"home.png","id":"0","size":"5988","type":"image"}
This at least prooves that the cfc script is working and the 'response' varialable is being returned. I still have no idea how to make use of this information as I have no knowledge of jquery, ajax or javascript. Please help if you can.
The link that I posted before has the example code. Sorry to post this as an answer but since I have no rep I cannot comment.
I think part of your confusion is in the request processing. You have this line of code at the bottom of your example.
<cfif IsDefined('response')><cfdump var="#response#"></cfif>
That will never fire because the coldfusion page is processed before you make the javascript ajax call to the server for the file upload. You will need to handle the response in javascript.
Are you seeing this alert from the attachCallbacks function?
alert('Response from server: ' + response.file); // for testing only

YouTube upload form entries with PHP/XML

I have a script for YouTube which allows me or anyone else to use on a site to upload videos directly to a YouTube account.
The problem is only the video is uploaded with no video information such as title & description I want the person who is uploading the video to have the options of filling in a form which will then result in the title & description on YouTube.
The script can be seen at the bottom. What I want is for a form to be in place which is something like the following:
Video Title: Cat Drives Car
Video By: MrShoez
Video Description: Watch this video of a cat driving a car.
And the title output would be something as "Cat Drives Car by MrShoez"
Along with the description displaying: This video was submitted on DATE HERE by MrShoez. "Watch this video of a cat driving a car."
*
<?php
$youtube_email = "email#address.com"; // Change this to your youtube sign in email.
$youtube_password = "password"; // Change this to your youtube sign in password.
$postdata = "Email=".$youtube_email."&Passwd=".$youtube_password."&service=youtube&source=Example";
$curl = curl_init("https://www.google.com/youtube/accounts/ClientLogin");
curl_setopt($curl, CURLOPT_HEADER, "Content-Type:application/x-www-form-urlencoded");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
$response = curl_exec($curl);
curl_close($curl);
list($auth, $youtubeuser) = explode("\n", $response);
list($authlabel, $authvalue) = array_map("trim", explode("=", $auth));
list($youtubeuserlabel, $youtubeuservalue) = array_map("trim", explode("=", $youtubeuser));
$youtube_video_title = "VIDEO TITLE"; // This is the uploading video name.
$youtube_video_description = "VIDEO DESCRIPTION"; // This is the uploading video description.
$youtube_video_category = "CATEGORY"; // This is the uploading video category.
$youtube_video_keywords = "tags, tags, tags, tags"; // This is the uploading video keywords.
$data = '<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:yt="http://gdata.youtube.com/schemas/2007">
<media:group>
<yt:private/>
<media:title type="plain">'.$youtube_video_title.'</media:title>
<media:description type="plain">'.$youtube_video_description.'</media:description>
<media:category
scheme="http://gdata.youtube.com/schemas/2007/categories.cat">'.$youtube_video_category.'</media:category>
<media:keywords>'.$youtube_video_keywords.'</media:keywords>
</media:group>
</entry>';
$key = "UNIQUEKEY HERE"; // Get your key here: http://code.google.com/apis/youtube/dashboard/.
$headers = array("Authorization: GoogleLogin auth=".$authvalue,
"GData-Version: 2",
"X-GData-Key: key=".$key,
"Content-length: ".strlen($data),
"Content-Type: application/atom+xml; charset=UTF-8");
$curl = curl_init("http://gdata.youtube.com/action/GetUploadToken");
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_REFERER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_HEADER, 0);
$response = simplexml_load_string(curl_exec($curl));
curl_close($curl);
?>
<script type="text/javascript">
function checkForFile() {
if (document.getElementById('file').value) {
return true;
}
document.getElementById('errMsg').style.display = '';
return false;
}
</script>
<?php
$nexturl = "http://website.com/directurl"; // This parameter specifies the URL to which YouTube will redirect the user's browser when the user uploads his video file.
?>
<form action="<?php echo($response->url); ?>?nexturl=<?php echo(urlencode($nexturl)); ?>" method="post" enctype="multipart/form-data" onsubmit="return checkForFile();">
<input id="file" type="file" name="file"/>
<div id="errMsg" style="display:none;color:red">
You need to specify a file.
</div>
<input type="hidden" name="token" value="<?php echo($response->token); ?>"/>
<input type="submit" value="go" />
</form>
</php>
*

Resources