sharing images on twitter using php - php

<?php
$title = urlencode('Nature');
$url = urlencode('http://amazingpics.net/content/Nature/Amazing%20Nature%20698.jpg');
$image = urlencode('http://trainees.ocs.org/training/hariharan/01-09-2014/images/img2.jpg');
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sharing Images</title>
<link href="css/share.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="all">
<div class="top">
<div class="nature" align="center">
<p class="nat">I LOVE NATURE</p>
</div>
<p> </p>
<div class="img"><img src="images/img2.jpg" height="250" width="500" /></div>
<div class="share"><a onClick="window.open('http://www.facebook.com/sharer.php?s=100&p[title]=<?php echo $title;?>&p[url]=<?php echo $url; ?>&&p[images][0]=<?php echo $image;?>','sharer','toolbar=0,status=0,width=600,height=400');" href="javascript: void(0)"><img src="images/share.png" width="200" height="40" /></a></div>
<div class="share"><a onClick="window.open('http://twitter.com/intent/tweet?url=<?php echo $url;?>','sharer','toolbar=0,status=0,width=600,height=400');" href="javascript: void(0)"><img src="images/twitter.png" width="200" height="40" /></a></div>
<p> </p>
</div>
</div>
</body>
</html>
I tried the above code for sharing images on facebook and twitter. it works correctly in facebook, but the image cannot displayed in twitter. the link only displayed. please help me to share images on twitter in php. thanks in advance...

Even the code and examples on twitter API documentation is straight forward but It wasn’t easy to figure out the right code with twitter API for tweet images.
To create twitter application you need to do that from : https://dev.twitter.com/
In twitter dev site, you have to specify the name and decryption of your application plus the URL to your main page and the callback page (more on these two page later). Also you have to make sure you set your twitter application access to “Read and Write” in order to give it authorization to tweet images on user behalf.
After the app is created correctly, twitter will provide you with a “Consumer key” and “Consumer secret”, you need to keep these two string variables because they are required to identify your application while communicating with twitter API to tweet images.
Download twitter code libraryDownload the Required PHP Libraries
For twitter authentication and image uploading to twitter you need tmhOAuth.php and tmhUtilities.php you can download them from https://github.com/opauth/twitter/tree/master/Vendor/tmhOAuth
How the Tweet Images Code Works?
The code for tweet images divided in two files, the first is “start.php” where the code start and a second file “callback.php” where twitter will redirect user back after giving authorization to our app. (the URL to our callback.php file has been updated in App settings in steps above)
How the code works
i)In “start.php” the first thing we have to do is asking for temporary access token from twitter API using the key and secret that we get them when we create the application (this process call get request token).
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => API_KEY,
'consumer_secret' => API_SEC,
'curl_ssl_verifypeer' => false
));
$tmhOAuth->request('POST', $tmhOAuth->url('oauth/request_token', ''));
$response = $tmhOAuth->extract_params($tmhOAuth->response["response"]);
ii). After we have the temporary access token we need to save them in cookies for later use after the user authenticate our App and redirected back to
“callback.php”
$temp_token = $response['oauth_token'];
$temp_secret = $response['oauth_token_secret'];
$time = $_SERVER['REQUEST_TIME'];
setcookie("Temp_Token", $temp_token, $time + 3600 * 30, '/twitter_test/');
setcookie("Temp_Secret", $temp_secret, $time + 3600 * 30, '/twitter_test/'); setcookie("Tweet_Txt", $txt, $time + 3600 * 30, '/twitter_test/');
setcookie("Img_Url", $img, $time + 3600 * 30, '/twitter_test/');
iii). Asking user to give authorization to our app requires a redirect to Twitter API page where user will fill his username and password and complete the authorization process.
$url = $tmhOAuth->url("oauth/authorize", "") . '?oauth_token=' . $temp_token;
header("Location:".$ url);
exit();
iv). When authorization is been given to our app, Twitter API will redirect the user to “callback.php” URL specified in App settings.
v). In “callback.php” file the actual code to tweet images exists. First we retrieve the temporary access token from cookies and we exchange them with correct access token.
$token = $_COOKIE['Temp_Token'];
$secret = $_COOKIE['Temp_Secret'];
$img = $_COOKIE['Img_Url'];
$txt = $_COOKIE['Tweet_Txt'];
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => API_KEY,
'consumer_secret' => API_SEC,
'user_token' => $token,
'user_secret' => $secret,
'curl_ssl_verifypeer' => false
));
$tmhOAuth->request("POST", $tmhOAuth->url("oauth/access_token", ""), array(
// pass the oauth_verifier received from Twitter
'oauth_verifier' => $_GET["oauth_verifier"]
));
$response = $tmhOAuth->extract_params($tmhOAuth->response["response"]);
$tmhOAuth->config["user_token"] = $response['oauth_token'];
$tmhOAuth->config["user_secret"] = $response['oauth_token_secret'];
vi). After we get the correct access token, we tweet the image we want.
$img = './'.$img;
$code = $tmhOAuth->request('POST', 'https://api.twitter.com/1.1/statuses/update_with_media.json',
array(
'media[]' => "#{$img}",
'status' => "$txt"
),
true, // use auth
true // multipart
);
vii). The returned code from twitter API will tell us if the operation was done correctly or not.
if ($code == 200){
echo '<h1>Your image tweet has been sent successfully</h1>';
}else{
tmhUtilities::pr($tmhOAuth->response['response']);
}

Related

How to play hls content without saving the file as .m3u8?

I'm using PHP code to retrieve the content of .m3u8 with a Signed URL from AWS CloudFront.
I can't be able to play the chunk .ts files inside it since you need also to sign their URL.
So, using PHP code, I re-write the contents of .m3u8
<?php
$resourceKey = 'https://abcdefg.cloudfront.net/abcdef-1234.MOV_1000k*';
$expires = time() + 172800;
$customPolicy = <<<POLICY
{
"Statement": [
{
"Resource": "{$resourceKey}",
"Condition": {
"DateLessThan": {"AWS:EpochTime": {$expires}}
}
}
]
}
POLICY;
$signedUrl = $cloudFrontClient->getSignedUrl([
'url' => $resourceKey,
'policy' => $customPolicy,
'private_key' => public_path().'/pk-ABCDEFGHIJ.pem',
'key_pair_id' => 'ABCDEFGHIJ'
]);
$signedUrl = str_replace('*', '.m3u8', $signedUrl);
// get contents of the file and the query string
$content = file_get_contents($signedUrl);
parse_str(parse_url($signedUrl)['query'], $params);
$qs = "?Policy=".$params['Policy']."&Signature=".$params['Signature']."&Key-Pair-Id=".$params['Key-Pair-Id'];
// rewriting process
$replaceThis = array(".m3u8", ".ts");
$withThisValue = array(".m3u8".$qs, ".ts".$qs);
$content = str_replace($replaceThis, $withThisValue, $content);
?>
I was able to sign the .ts inside the .m3u8 file. But the problem now is that, how can I convert $content to something playable to HTML5 video with VideoJS without downloading the file contents using file_put_contents? I don't want to save it on the directory. Just to convert it on blob data or decode it and play it Something like this. Is this possible?
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
</head>
<body>
<video id='hls-example' class="video-js vjs-default-skin" width="640" height="480" controls>
<source src="<?php echo $content; ?>" type="application/x-mpegURL">
Your browser does not support the video tag.
</video>
<script src="https://vjs.zencdn.net/7.2.3/video.js"></script>
<script>
var player1 = videojs('hls-example');
</script>
</body>
</html>
PS: I tried AWS Lambda Edge. But, it doesn't work when there are many chunk .ts inside the m3u8 file. It returns an error that exceeds the Viewer Request Quota of 40KB.

Google App Engine PHP file upload

I developed an API in PHP, hosted at Google App Engine, to use with my Android app.
Basically, when a user wants to change his profile picture, the android app send a request to the server containing the user id, the session key and the picture to upload. I want to upload this picture on the Google Cloud, but since Google App Engine require you to build a public upload URL to upload a file, how can I generate the upload URL and then use this URL to upload the profile picture in my Google Cloud in one request?
I tried to use a basic PHP redirect after generating the upload URL but I get a HTTP 405.
I am really stuck and I honestly don't understand why you NEED to create an URL before uploading a file to Google App Engine...
Source: https://cloud.google.com/appengine/docs/php/googlestorage/user_upload
It seems that the photo that you want to upload on Google Cloud Storage saves as a Blob on GCS that's why they ask you to create a URL. Follow the document [1] it is related to Blobstore API in python but the concept of blob is same for any language so its good to read about blobs. Also find below a sample code which might help you to upload a photo on GCS.
$options = [ 'gs_bucket_name' => 'bucket-name' ];
$upload_url = CloudStorageTools::createUploadUrl('/upload', $options);
<form action="<?php echo $upload_url?>" method="post" enctype="multipart/form-data">
<input type ="file" name="fileupload" id = "fileupload">
<input type="submit" value="Upload" name ="submit">
</form>
Upload Handler:
<?php
use google\appengine\api\cloud_storage\CloudStorageTools;
$gs_name = $_FILES['fileupload'];
$buffer = file_get_contents($gs_name['tmp_name']);
$bucket = CloudStorageTools::getDefaultGoogleStorageBucketName();
$user_pic_url = 'gs://' . $bucket
. (substr($final_file_path,0,1) != '/' ? '/' : '' )
. $final_file_path;
// set file options on Google Could Storage
$options = stream_context_create( ['gs' => ['acl' => 'public-read',
'Content-Type' => 'image/jpg']] );
echo "<br>";
$my_file = fopen($user_pic_url, 'w', false, $options);
fclose($my_file);
[1] BlobStore API: https://cloud.google.com/appengine/docs/python/blobstore/
$pdf->Output('example_025.pdf', 'I');
$DynamicNameofPic = rand(1000,10000)."_Invoice.pdf";
$FileNameDynamic = "gs://#######/".$DynamicNameofPic;
$pdf->Output($FileNameDynamic,'F');
$image_dataURL = "https://storage.googleapis.com/##########/".$DynamicNameofPic;
$image_data = file_get_contents($image_dataURL);$fileName = $DynamicNameofPic;

how to upload image created using php to users timeline on facebook

I have developed a facebook application that contains following files
1) index.php
2) cap3.php
where cap3.php generates an image using GD in PHP.
index.php displays this image using following code
<img src="cap3.php">
now I want this generated image to be posted on user's timeline.
I have tried to do so by using following code:
$facebook->setFileUploadSupport(true);
$img = 'cap3.php';
$args=array( 'source' => '#' .$current , 'message' => 'Photo uploaded via!' );
$photo = $facebook->api('/me/photos', 'POST', $args);
but the image is not posted on user's timeline
please help.
One way to do that is to put your cap3.php file in your remote host to get an URL to it. For example : http://www.example.com/cap3.php. Then, you download that image from your app and send it to facebook.
Let's see an example:
$local_img = 'cap3.png'; // I assume your cap3.php generates a PNG file
$remote_img = 'http://www.example.com/cap3.php';
// sample: check for errors in your production app!
$img_content = file_get_contents($remote_img);
file_put_contents($locale_img, $img_content);
$facebook->setFileUploadSupport(true);
$args=array( 'source' => '#' .$locale_img , 'message' => 'Photo uploaded via!' );
$photo = $facebook->api('/me/photos', 'POST', $args);

How to check if a user likes a Facebook Page, if Yes redirect to another page?

I would like to create a PHP script to check if the user 'Like's the page. If the user likes the page he is redirected to another URL if not the User is asked to like the page and the facebook like button appears so the user can like.
How can this be done please? I managed to get hold of this script and got errors. Any help please?
Thanks
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Facebook "If-Like" Application | ThreeDots</title>
</head>
<body>
<?php
include_once( "facebook.php" );
$fbAppArray = array(
'appId' => 'YOUR_APPLICATION_ID',
'secert' => 'YOUR_APPLICATION_SECRET',
'cookie' => true
);
$fbAppObj = new Facebook( $fbAppArray );
$signedRequest = $fbAppObj->getSignedRequest();
function parsePageSignedRequest()
{
if( isset( $_REQUEST['signed_request'] ) )
{
$encoded_sig = null;
$payload = null;
list( $encoded_sig, $payload ) = explode( '.', $_REQUEST['signed_request'], 2 );
$sig = base64_decode( strtr( $encoded_sig, '-_', '+/' ) );
$data = json_decode( base64_decode( strtr( $payload, '-_', '+/' ), true ) );
return $data;
}
return false;
}
if( $signedRequest = parsePageSignedRequest() )
{
if( $signedRequest->page->liked )
{
// What to show the user if he liked the application...
}else{
// Please like the application so you will be able to see the contents...
}
}
?>
</body>
</html>
The signed_request parameter is only available if your app is running as canvas app or page tab app inside of Facebook. If that’s the case, please read up on this parameter and how to interpret it in the docs.
(Btw., just saying “I get errors” is neither a helpful nor a smart way of describing a programming related problem. So please read http://facebook.stackoverflow.com/questions/how-to-ask as well.)
If your app is not running inside Facebook, then you have to have the user connect to your app, get his permission to read his likes, and look for yourself if your specific page is amongst them. For all that, please refer to documentation as well.

Automating Linkedin oAuth usin Curl and PHP

I am trying to automate the process of authenticating LinkedIn login in order to perform a public search for people on LinkedIn.
First i will try to explain what i was doing.
I am using four files:
oAuth.php (required)
linkedin.php (php LinkedIn library)
auth.php (which gets oAuth token from the LinkedIn lib file)
callback url demo.php?params (which, after successful authenticaton, prints the current user's profile and the search results using params)
The authentication url is https://api.linkedin.com/uas/oauth/authorize?oauth_token=$oauthtoken.
I did two things, neither seems to work; they are:
I am using curl to automate the process of going to the authentication url, posting fields (username, password, oauth token, csrfToken, duration, sourceAlias, etc., which I came to know from Firebug).
The only two things which change here are oauth token and csrfToken (by parsing the content in the authentication url). I was able to get both, each time the page loads, and finally trying to print the GET response from curl_exec.
Trying to post just the email and password, and trying to print a GET response.
For reference here is my auth.php:
function extract_unit($string, $start, $end)
{
$pos = stripos($string, $start);
$str = substr($string, $pos);
$str_two = substr($str, strlen($start));
$second_pos = stripos($str_two, $end);
$str_three = substr($str_two, 0, $second_pos);
$unit = trim($str_three); // remove whitespaces
return $unit;
}
session_start();
$config['base_url'] = 'http://linkedin.tweetrank.tk/auth.php';
$config['callback_url'] = 'http://linkedin.tweetrank.tk/demo.php';
$config['linkedin_access'] = 'my key';
$config['linkedin_secret'] = 'my secret';
include_once "linkedin.php";
# First step is to initialize with the consumer key and secret. We'll use
# an out-of-band oauth_callback
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url']);
//$linkedin->debug = true;
# Now we retrieve a request token. It will be set as $linkedin->request_token
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
# With a request token in hand, we can generate an authorization URL, which
# we'll direct the user to
//echo "Authorization URL: " . $linkedin->generateAuthorizeUrl() . "\n\n";
echo $url = $linkedin->generateAuthorizeUrl();
$token = $linkedin->generateAuthorizeToken();
//echo '<br><br>';
$data = file_get_contents($url);
$csrfToken = extract_unit($data,'name="csrfToken" value="','"');
//echo $csrfToken;
//echo $token;
//echo 'https://www.linkedin.com/uas/oauth/authenticate?oauth_token='.$token.'&trk=uas-continue';
// INIT CURL
$postParams = 'email=myemail&password=mypassword&duration=720&authorize=Ok%2C+I%27ll+Allow+It&extra=&access=-3&agree=true&oauth_token='.$token.'&appId=&csrfToken='.$csrfToken.'&sourceAlias=0_8L1usXMS_e_-SfuxXa1idxJ207ESR8hAXKfus4aDeAk';
Now I used the authentication URL and the postParams with curl.
In order to get login process through, one has to use linkedIn web page authorization step; No way we can have third party app accepting credentials and making linkedIn authorization with the link https://api.linkedin.com/uas/oauth/authorize?oauth_token=$oauthtoken
I think I understand what you are asking and the answer is no you cannot do that with LinkedIn. I have been facing similar problem recently and wasn't able to solve it. I guess the LinkedIn guys have a good point about data protecting and stuff.
Check this out:
http://developer.linkedin.com/message/6460
http://getsatisfaction.com/linkedin/topics/cant_use_linkedin_api_to_view_public_profiles_without_oauth_login

Categories