PHP mysql Twitter API 500 error - php

<?php
function saveTweets($screen_name) {
$db = array("h"=>"localhost", "u"=>"user", "p"=>"pass", "n"=>"db");
$dbconnect = mysql_connect($db['h'], $db['u'], $db['p']);
$dbselect = mysql_select_db($db['n']);
$screen_name = mysql_real_escape_string(strtolower(trim($screen_name)));
if (!$screen_name) {
echo "<p><strong>Error: No screen name declared.</strong></p>\n"; return false;
}
$row = mysql_query("SELECT `id` FROM `twitter` WHERE `screen_name`='$screen_name' ORDER BY `id` DESC LIMIT 1");
$row = mysql_fetch_array($row);
$last_id = $row['id'];
$url = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=$screen_name" ;
if ($last_id) {
$url .= "&since_id=$last_id" ;
}
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
$xml = curl_exec ($ch);
curl_close ($ch);
$affected = 0;
$twelement = new SimpleXMLElement($xml);
foreach ($twelement->status as $status) {
$text = mysql_real_escape_string(trim($status->text));
$time = strtotime($status->created_at);
$id = $status->id;
mysql_query("INSERT INTO `twitter` (`id`,`screen_name`,`time`,`text`,`hidden`) VALUES ('$id','$screen_name','$time','$text','n')");
$affected = $affected + mysql_affected_rows();
}
return "<p>".number_format($affected)." new tweets from $screen_name saved.</p>\n" ;
}
echo saveTweets('screenName');
?>
I am trying to use this script to grab from my twitter feed. But it returns 0 new tweets saved from 'screenName'. Does anyone can help please?
Note: I actually replaced the screenName with many account of mine and my friends.

After retirement of twitter api 1.0 , now almost everything data come from twitter is by authentication. you can read all details through below link
Twitter user timeline

The script you have uses Twitter API 1.0 and is no longer active.
I personally think the API documentation is terrible, and I suggest you read this StackOverflow post.
Hope this helps.

Your code is not working because your using a deprecated API. below is the output from the feed.
<errors>
<error code="68">
The Twitter REST API v1 is no longer active. Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.
</error>
</errors>

Related

saving picture on server - PHP Facebook

I am trying to save the picture which you get from the $FB->get on my server. So I can get that pic and make it a profile picture when login in with facebook. The only thing now is that I don't know how to save that pic on my server. I think I need to use copy or rename function from php or something like that. As you can see I tried using it but I have no clue how I need to fix this.
$oAuth2Client = $FB->getOAuth2Client();
if (!$accessToken->isLongLived())
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
$response = $FB->get("/me?fields=id, first_name, last_name, email,gender,link, birthday,picture.type(large)", $accessToken);
$userData = $response->getDecodedBody();
$fb_foto_url = $userData['picture']['data']['url'];
copy($fb_foto_url ,'assets/images/profielfotos');
$voornaam= $app->get_klant_fb($userData['first_name']);
$_SESSION['voornaam'] = $userData['first_name'];
$_SESSION['achternaam'] = $userData['last_name'];
$fb_fotoUrl = $app->saving_fb_foto($userData['picture']['data']['url']);
How I am making a user based on facebook login.
//data ophalen
$klant= $app->get_klant_fb($userData['id']);
if($klant['id'] > 0) {
//sessie klant zetten
$_SESSION['klant_id'] = $klant['id'];
} else {
//klant aanmaken
unset($query);
$query['oauth_uid'] = $userData['id'];
$query['ledenpagina_id']= $_SESSION['ledenpagina_id'];
$query['voornaam'] = $userData['first_name'];
$query['achternaam'] = $userData['last_name'];
$query['emailadres'] = $userData['email'];
$query['geboortedatum'] = $userData['birthday'];
$query['gender'] = $userData['gender'];
$query['link'] = $userData['link'];
$app->insert_query('klanten', $query);
$klant= $app->get_klant_fb($userData['id']);
if($klant['id'] > 0) {
$_SESSION['klant_id'] = $klant['id'];
}
}
This is what the develeper.facebook looks like
If you have the URL which it looks like..
You can do a save..
file_put_contents("your/local/server/file.png", fopen($fb_foto_url, 'r'));
However it would make more sense to me, to store the Facebook URL in your database, and simply use that.. .
Ref : http://php.net/manual/en/function.file-put-contents.php
Please try using the curl option to save the image to the server.
$fb_foto_url = $userData['picture']['data']['url'];
$ch = curl_init($fb_foto_url);
$fp = fopen('assets/images/profielfotos/photo.ext', 'wb'); //Please print out the url and replace the .ext with extension returned such as jpg/png
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
//The image will be stored by now
//Remove the copy function
But if you really don't want to edit the picture or something try getting it directly from the url so it will be automatically updated as well.

How to use AWS SDK PHP for AWSECommerceService

I have to use following API URL to fetch Books information (found here)-
http://webservices.amazon.com/onca/xml?
Service=AWSECommerceService
&Operation=ItemLookup
&ResponseGroup=Large
&SearchIndex=All
&IdType=ISBN
&ItemId=076243631X
&AWSAccessKeyId=[Your_AWSAccessKeyID]
&AssociateTag=[Your_AssociateTag]
&Timestamp=[YYYY-MM-DDThh:mm:ssZ]
&Signature=[Request_Signature]
I can use PHP SDK for this, I could not find any doc on how to achieve this using SDK.
EDIT
Following this & this links, I have written following code-
<?php
date_default_timezone_set('UTC');
$ItemId = 1603843698;
$ResponseGroup = 'Offers';
//$Timestamp = gmdate("Y-M-DTh:m:sZ");
$Timestamp = gmdate("Y-m-d\TH:i:s\Z");
$AWSAccessKeyId = "EXAMPLEEXAMPLE";
$associateTag = "something-10";
echo $Timestamp;
echo "<br />";
$str = "GET\n
webservices.amazon.com\n
/onca/xml\n
AWSAccessKeyId=".$AWSAccessKeyId."&AssociateTag=".$associateTag."&ItemId=".$ItemId."&Operation=ItemLookup&ResponseGroup=".$ResponseGroup."&Service=AWSECommerceService&Timestamp=".urlencode($Timestamp);
$str = urlencode(base64_encode(hash_hmac("sha256",$str,'my secrete',true)));
$url = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&Operation=ItemLookup&ResponseGroup=Offers&IdType=ASIN&ItemId=".$ItemId."&AssociateTag=ebooksprices-20&AWSAccessKeyId=".$AWSAccessKeyId."&Timestamp=".urlencode($Timestamp)."&Signature=".$str;
echo "<br />";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
But with no success, I get this output-
2016-07-14T09:50:06Z string(427) " SignatureDoesNotMatchThe request
signature we calculated does not match the signature you provided.
Check your AWS Secret Access Key and signing method. Consult the
service documentation for
details.34b23224-4750-46c7-8f75-929239f955de"
Any help will be appreciated.
Thanks
Finally I got time to post my working code-
$ItemId = $_GET['isbn'];
$ResponseGroup = 'Offers';
//$Timestamp = gmdate("Y-M-DTh:m:sZ");
//date_default_timezone_set('America/Los_Angeles');
$Timestamp = gmdate("Y-m-d\TH:i:s\Z");
$AWSAccessKeyId = "/your key/";
$AssociateTag = "/your-tag/";
$Version = "2013-08-01";
//echo $Timestamp;
//echo "<br />";
$str = "Service=AWSECommerceService&Operation=ItemLookup&ResponseGroup=".$ResponseGroup."&IdType=ASIN&ItemId=".urlencode($ItemId)."&AssociateTag=".$AssociateTag."&AWSAccessKeyId=".$AWSAccessKeyId."&Timestamp=".urlencode($Timestamp);
$ar = explode("&", $str);
//var_dump($ar);
natsort($ar);
//var_dump($ar);
$str = "GET
webservices.amazon.com
/onca/xml
";
$str .= implode("&", $ar);
//echo $str;
//echo "<br />";
$str = urlencode(base64_encode(hash_hmac("sha256",$str,'/your secret/',true)));
$url = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&Operation=ItemLookup&ResponseGroup=Offers&IdType=ASIN&ItemId=".$ItemId."&AssociateTag=your-tag&AWSAccessKeyId=".$AWSAccessKeyId."&Timestamp=".urlencode($Timestamp)."&Signature=".$str;
//echo "<br />";
//echo $url;
//echo "<br />";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
//var_dump($result);
$xml=simplexml_load_string($result) or die("Error: Cannot create object");
echo "<h1>AMAZON API</h1><pre>";
print_r($xml);
This code returns the response in XML format.
Thanks
The AWS SDK's does currently not support the Amazon Product Advertising API.
For implementation there's a PHP code example provided by Amazon on this page: Implementing a Product Advertising API Request
For the request signature, follow this documentation: http://docs.aws.amazon.com/AWSECommerceService/latest/DG/rest-signature.html. More specific details on a PHP implementation of the request signing has been answer here before: Amazon Product API returns “SignatureDoesNotMatch”

Convert huge number of places into latitude & longitude and update MySQL database using PHP

I'm new to PHP, and I want to get latitude and longitude of a place and then add them to MySQL database.
I'm using Google Geo-code API to get them, this is what I do right-row
for ($i = 0; $i<1000; $i++) {
$sql = mysql_query("SELECT place_address FROM place_locator WHERE place_id =".$i, $this->db) or die('invalide request : ' . mysql_error());
if (mysql_num_rows($sql)) {
while ($place = mysql_fetch_assoc($sql)) {
//Encode the place string I got, to get rid of space
$encodePlace = str_replace(" ", "%20", $place["place_address"]);
//Use Google API
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='.$encodePlace.'&sensor=false';
//Use Curl to send the request
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$obj = json_decode($response, true);
$updateSql = mysql_query("UPDATE `place_locator`.`place_locator` SET
`latitude` = '".$obj["results"][0]["geometry"]["location"]["lat"]."',
`longitude` = '".$obj["results"][0]["geometry"]["location"]["lng"]."' WHERE `place_locator`.`place_id` = ".$i, $this->db) or die('Invalide : ' . mysql_error());
curl_close($ch);
}
}
It works for a loop of 10,when going to 1000, it will take a lot of time and many results didn't updated to the database.
I think may be multi thread should help, but I don't really know how it works, please help me.
Thanks in advance
I had the same problem. Google limits the frequency of the requests! Try a sleep(1); in the loop and it will work but need much more time.

How do I use PHP, Twitter API to get more or all of my followers?

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.

Get user's name from Facebook Graph API

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

Categories