I would like to know how is it possible to retrieve a string from an external page.
For example: In a PHP website, the user sends a facebook id, ex: 1157251270
And the website returns the name from http://graph.facebook.com/1157251270.
I hope I made it clear.
Thank you
The Graph API returns JSON strings, so you can use:
echo json_decode(file_get_contents('http://graph.facebook.com/1157251270'))->name;
or more verbose:
$pageContent = file_get_contents('http://graph.facebook.com/1157251270');
$parsedJson = json_decode($pageContent);
echo $parsedJson->name; // Romanos Fessas
See json_decode — Decodes a JSON string
If you are using Facebook's PHP SDK, you can also do this to query their graph API:
$fb = new Facebook();
$object = $fb->api('/1157251270');
you get it by:
$link = json_decode(file_get_contents('http://graph.facebook.com/1157251270'));
echo $link->name;
Nice tut:
http://webhole.net/2009/08/31/how-to-read-json-data-with-php/
Either you use :
$res_json = file_gets_contents("http://graph.facebook.com/1157251270")
$res = json_decode($res_json)
Or, if you prefer curl (here with https and access token) :
$ch4 = curl_init();
curl_setopt($ch4, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch4, CURLOPT_URL, "https://graph.facebook.com/1157251270?access_token=YOUR_ACCESS_TOKEN");
curl_setopt($ch4, CURLOPT_SSL_VERIFYPEER, false);
if(!$result = curl_exec($ch4))
{
echo curl_error($ch4);
} else {
$res = json_decode($res_json)
}
curl_close($ch4);
For facebook data you can use json_decode.
For another sites try with webscraping, for example:
here
Related
I am attempting to convert an image url provided by the facebook api into base64 format with cURL.
the api provides a url as such:
https://fbcdn-sphotos-g-a.akamaihd.net/hphotos-ak-xfp1/v/t1.0-9/p180x540/72099_736078480783_68792122_n.jpg?oh=f3698c5eed12c1f2503b147d221f39d1&oe=54C5BA4E&__gda__=1418090980_c7af12de6b0dd8abe752f801c1d61e0d
The issue is that the url only works with the oh, oe and gda parameters included in the url string, there is no direct img url. Removing the params send you to a facebook error page.
With the parameterized url my curl_exec is not getting correct image data. Is there a way to get the base64 data from facebook, or is there something I can do to get access the pure image url given the parameterized url?
This is what my decode scrip looks like:
header('Access-Control-Allow-Origin: *');
$url = $_GET['url'];
try {
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 3);
$result = curl_exec($c);
curl_close ($c);
if(false===$result) {
echo 'fail';
} else {
$base64 = "data:image/jpeg;charset=UTF-8;base64,".base64_encode($result);
echo $base64;
}
} catch ( \ErrorException $e ) {
echo 'fail';
}
To address your specific problem, your script is likely failing because the required oh, oe, __gda__ parameters are getting separated during the GET request and therefore are not included in $_GET['url'].
Make sure you're using a URL-encoded string so any unencoded & characters aren't handled as delimiters. Then just decode the string before passing it on to cURL.
...
$url = urldecode($_GET['url']);
...
For anyone curious, you can still load any Facebook image from any one of their legacy CDNs without needing the new parameters:
https://scontent-a-iad.xx.fbcdn.net/hphotos-frc3/
https://scontent-b-iad.xx.fbcdn.net/hphotos-frc3/
https://scontent-c-iad.xx.fbcdn.net/hphotos-frc3/
Just append the original image filename to the URL et voila.
Disclaimer: I have no idea how long this little trick will work for so don't use it on anything important in production.
Maybe this won't help much but it seems that the original picture (ending with _o) does not need gda nor oe oh parameters
to get the original profile picture you can do:
var username_or_id = "name.lastname" //Example
get_url ("http://graph.facebook.com/$username_or_id/picture?width=9999")
hth
I had similar problem. My solution:
$url = urldecode($url);
return base64_encode(file_get_contents($url));
Where the URL is to Graph API:
https://graph.facebook.com/$user_id/picture?width=160
(You probably want to also check, if file_get_contents returns something)
You just need to add the CURLOPT_SSL_VERIFYPEER set to false as the url from facebook is https and not http., or you could just as well request the url without ssl by replacing https with http.
Try the code below
$url = 'https://fbcdn-sphotos-g-a.akamaihd.net/hphotos-ak-xfp1/v/t1.0-9/p180x540/72099_736078480783_68792122_n.jpg?oh=f3698c5eed12c1f2503b147d221f39d1&oe=54C5BA4E&__gda__=1418090980_c7af12de6b0dd8abe752f801c1d61e0d';
try {
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 3);
/***********************************************/
// you need the curl ssl_opt_verifypeer
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
/***********************************************/
$result = curl_exec($c);
curl_close ($c);
if(false===$result) {
echo 'fail';
} else {
$base64 = '<img alt="Embedded Image" src="data:image/jpeg;charset=UTF-8;base64,'.base64_encode($result).'"/>';
echo $base64;
}
}
catch ( \ErrorException $e ) {
echo 'fail';
}
I am learning the instagram api to fetch certain hashtag image into my website recently.
After searching on the webs for a very long time I coundnt find any workable code for it.
Anyone can help?
Thanks!
If you only need to display the images base on a tag, then there is not to include the wrapper class "instagram.class.php". As the Media & Tag Endpoints in Instagram API do not require authentication. You can use the following curl based function to retrieve results based on your tag.
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$tag = 'YOUR_TAG_HERE';
$client_id = "YOUR_CLIENT_ID";
$url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
//Now parse through the $results array to display your results...
foreach($results['data'] as $item){
$image_link = $item['images']['low_resolution']['url'];
echo '<img src="'.$image_link.'" />';
}
You will need to use the API endpoint for getting a list of recently tagged media by the hashtag. It would look something like this to get media for the hashtag #superpickle
https://api.instagram.com/v1/tags/superpickle/media/recent
You will need to read the Instagram API documentation to learn more about it and how to register for a client ID. http://instagram.com/developer/
You can use statigram cURL method, isnt Instagram API, but can resolve it.
Im use CodeIgniter and make a service to return a XML, usign simple_xml_load to read feed.
Good Lucky.
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_URL, "http://statigr.am/feed/cristiano");
$content = curl_exec($curl);
curl_close($curl);
$this->xml = simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA);
echo json_encode($this->xml->channel);
So, I'm working with the Instagram API, but I cannot figure out how to create a like (on a photo) for the logged in user.
So my demo app is currently displaying the feed of a user, and it's requesting the permission to like and comment on behalf of that user. I'm using PHP and Curl to make this happen, creds to some guide I found on the internet:
<?php
if($_GET['code']) {
$code = $_GET['code'];
$url = "https://api.instagram.com/oauth/access_token";
$access_token_parameters = array(
'client_id' => '*MY_CLIENT_ID*',
'client_secret' => '*MY_CLIENT_SECRET*',
'grant_type' => 'authorization_code',
'redirect_uri' => '*MY_REDIRECT_URI*',
'code' => $code
);
$curl = curl_init($url); // we init curl by passing the url
curl_setopt($curl,CURLOPT_POST,true); // to send a POST request
curl_setopt($curl,CURLOPT_POSTFIELDS,$access_token_parameters); // indicate the data to send
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // to stop cURL from verifying the peer's certificate.
$result = curl_exec($curl); // to perform the curl session
curl_close($curl); // to close the curl session
$arr = json_decode($result,true);
$pictureURL = 'https://api.instagram.com/v1/users/self/feed?access_token='.$arr['access_token'];
// to get the user's photos
$curl = curl_init($pictureURL);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$pictures = curl_exec($curl);
curl_close($curl);
$pics = json_decode($pictures,true);
// display the url of the last image in standard resolution
for($i = 0; $i < 17; $i++) {
$id = $pics['data'][$i]['id'];
$lowres_pic = $pics['data'][$i]['images']['low_resolution']['url'];
$username = $pics['data'][$i]['user']['username'];
$profile_pic = $pics['data'][$i]['user']['profile_picture'];
$created_time = $pics['data'][$i]['created_time'];
$created_time = date('d. M - h:i', $created_time);
$insta_header = '<div class="insta_header"><div class="insta_header_pic"><img src="'.$profile_pic.'" height="30px" width="30px"/></div><div class="insta_header_name">'.$username.'</div><div class="insta_header_date">'.$created_time.'</div></div>';
$insta_main = '<div class="insta_main"><img src="'.$lowres_pic.'" /></div>';
$insta_footer = '<div class="insta_footer"><div class="insta_footer_like"><button onClick="insta_like(\''.$id.'\')"> Like </button></div><div class="insta_footer_comment"><form onSubmit="return insta_comment(\''.$id.'\')"><input type="text" id="'.$id.'" value="Comment" /></form></div></div>';
echo '<div class="insta_content">'. $insta_header . $insta_main . $insta_footer .'</div>';
}
}
?>
Now, it might be a stupid question, but how do I make a like on a particular photo on behalf of the user? I'm used to using JavaScript to these kinds of things, therefore I've setup the Like-button with a JS function (which does not exist). But since the Instagram thing have been using Curl and PHP, I'm guessing I have to do the same thing here? I have no experience with Curl, and I do not understand how it works. It would be great if someone could give me a headsup on that as well. But first off, the liking. If it's possible to do it with JS, I'd be very glad. If not, please show me how to do it with PHP and Curl.
Here's a link to the Instagram developers site, which contain the URL you should send a POST request to http://instagram.com/developer/endpoints/likes/.
And if you're not to busy, I'd be really glad if you could show me how to make a comment on behalf of a user as well :)
Thanks in advance.
Aleksander.
I'm a beginner at PHP. I have one task in my project, which is to fetch all videos from a YouTube link using curl in PHP. Is it possible to show all videos from YouTube?
I found this code with a Google search:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.youtube.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
echo $contents;
curl_close ($ch);
?>
It shows the YouTube site, but when I click any video it will not play.
You can get data from youtube oemebed interface in two formats Xml and Json which returns metadata about a video:
http://www.youtube.com/oembed?url={videoUrlHere}&format=json
Using your example, a call to:
http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=B4CRkpBGQzU&format=json
So, You can do like this:
$url = "Your_Youtube_video_link";
Example :
$url = "http://www.youtube.com/watch?v=m7svJHmgJqs"
$youtube = "http://www.youtube.com/oembed?url=" . $url. "&format=json";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
$result = json_decode($return, true);
echo $result['html'];
Try it...Hope it will help you.
You could use curl to retrieve the Google main page (or an alternative page) and parse the returned html using a library such as html5lib. If you wanted to try this approach the first step could be to 'view source' on the relevant page and look at how the links are structured.
A more elegant way to approach the problem could be to use the Youtube API (a way to interact with the Youtube system), which may allow you to retrieve the links directly. e.g it may be possible to just ask the Youtube API to send you the links. Try this.
You can also get all youtube's channel videos using file_get_contents
bellow is sample and working code
<?php
$Youtube_API_Key = ""; // you can obtain api key : https://developers.google.com/youtube/registering_an_application
$Youtube_channel_id = "";
$TotalVideso = 50; // 50 is max , if you want more video you need Youtube secret key.
$order= "date"; ////allowed order : date,rating,relevance,title,videocount,viewcount
$url = "https://www.googleapis.com/youtube/v3/search?key=".$Youtube_API_Key."&channelId=".$Youtube_channel_id."&part=id&order=".$order."&maxResults=".$TotalVideso."&format=json";
$data = file_get_contents($url);
$JsonDecodeData=json_decode($data, true);
print_r($data);
?>
I have a twitter api php script successfully spits out the last 100 of my followers
$flwrs_url = "http://api.twitter.com/1/statuses/followers/exampleuser.json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $flwrs_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
foreach($response as $friends){
$id = $friends['id'];
$screen_name = $friends['screen_name'];
....
(I used exampleuser instead of my own account)
How do I extend this to include more or all of my followers?
Thank you
According to the Twitter API Documentation for GET followers/ids the request should return up to 5000 followers.
However, if not all followers are returned by the API, there should be a next_cursor element in the response which can be used to retrieve the next batch of followers. You only have to append the value of next_cursor as cursor to the request (see also the API documentation).
Please note that you are using Version 1 of the Twitter API which has been deprecated recently. That is, it will stop working probably early next year. You should upgrade to Version 1.1 as soon as possible. There are new guidelines in place, one of them is that all requests must be authenticated with oAuth.
Thanks for the answer Florian. BTW stumbing around I think I found the correct way to do what I was looking for. Correct me if I'm wrong.
after using the:
$code=$tmhOAuth->request('GET', $tmhOAuth->url('1/followers/ids'),
array('screen_name' => $user, 'cursor' => $cursor));
technique to grab all 5000 followers (user ids). I use the following code to grab batches of 100 (user details) at a time:
$status_url = "http://api.twitter.com/1/users/lookup.json?user_id=";
$lastNum=$last; // $lastNum=100;
$i=$first; // $i=0;
while($i<$lastNum){
if ($i==($lastNum-1)){
$status_url = $status_url . "$followers[$i]";
}else{
$status_url = $status_url . "$followers[$i],";
}
$i++;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $status_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
$i = 0;
foreach($response as $friends){
$id = $friends['id'];
$screen_name = $friends['screen_name'];
$name = $friends['name'];
$thumb = $friends['profile_image_url'];
$url = $friends['screen_name'];
$location = $friends['location'];
$description = $friends['description'];
echo "$i) $id $screen_name $name $location $description<br />";
$i++;
}
I realize I need to put "sleep" in between each of these "batches of 100", but I'm not quite sure how much to use.