Facebook-PHP-SDK Getting friends list is very slow - php

Using below code to get friend's list ,But its takes lot of time to give the result.How can I get the result quicker.Can anyone help me to solve this issue?
or is there any other way I can get friends list?
try {
$requestFriends = $fb->get('/me/taggable_friends?fields=name&limit=100');
$friends = $requestFriends->getGraphEdge();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// if have more friends than 100 as we defined the limit above on line no. 68
if ($fb->next($friends)) {
$allFriends = array();
$friendsArray = $friends->asArray();
$allFriends = array_merge($friendsArray, $allFriends);
while ($friends = $fb->next($friends)) {
$friendsArray = $friends->asArray();
$allFriends = array_merge($friendsArray, $allFriends);
}
foreach ($allFriends as $key) {
echo $key['name'] . "<br>";
}
} else {
$allFriends = $friends->asArray();
$totalFriends = count($allFriends);
$counter = 0;
foreach ($allFriends as $key) {
echo $key['name'] . "<br>";
$counter++;
}
echo $counter;
}

Related

How to decode a base64 email with php?

I'm trying to decode my message with base 64 decode method. Does anybody know how to do this, or maybe via a php function?
<?php
class Gmail
{
public function __construct($client)
{
$this->client = $client;
}
public function readLabels()
{
$service = new Google_Service_Gmail($this->client);
// Print the labels in the user's account.
$user = 'me';
$results = $service->users_labels->listUsersLabels($user);
$the_html = "";
if (count($results->getLabels()) == 0) {
// print "No labels found.\n";
$the_html .= "<p>No labels found</p>";
} else {
// print "Labels:\n";
$the_html .= "<p>labels</p>";
foreach ($results->getLabels() as $label) {
// printf("- %s\n", $label->getName());
$the_html .= "<p>" . $label->getName() . "</p>";
}
return $the_html;
}
}
/**
* Get list of Messages in user's mailbox.
*
* #param Google_Service_Gmail $service Authorized Gmail API instance.
* #param string $userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* #return array Array of Messages.
*/
public function listMessages()
{
$service = new Google_Service_Gmail($this->client);
// Print the labels in the user's account.
$userId = 'me';
$pageToken = null;
$messages = array();
$opt_param = array();
$messagesResponse = array();
$i = 0;
do {
if ($i == 5) break;
$i++;
try {
if ($pageToken) {
$opt_param['pageToken'] = $pageToken;
}
$messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param);
if ($messagesResponse->getMessages()) {
$messages = array_merge($messages, $messagesResponse->getMessages());
$pageToken = $messagesResponse->getNextPageToken();
}
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
} while ($pageToken);
foreach ($messages as $message) {
print 'Message with ID: ' . $message->getId() . '<br/>';
$msg = $service->users_messages->get($userId, $message->getId());
echo "<pre>" . var_export($msg->payload->parts[1]->body->data->base64_decode, true) . "</pre>";
}
return $messages;
}
}
As mentioned on the comment above by #Marvin, try to use base64_decode function.
Here is an example:
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str); // This is an encoded string
So in your case, instead of using
echo "<pre>" . var_export($msg->payload->parts[1]->body->data->base64_decode, true) . "</pre>";
try
echo "<pre>" . var_export(base64_decode($msg->payload->parts[1]->body->data), true) . "</pre>";
Reference
base64_decode

Updating price and stock of thousands of entries in DB

I'm working on a project to update a daatabase of products (price and stock) in prestashop based on data from a vending program. I'm doing this using PHP code and a MySQL conneectio to the DB.
The problem is that there is about 58.000 products and it seems to take very long to update all products.
Here is my code:
<?php
$host = '127.0.0.1';
$uname = '*******';
$pwd = '*******';
$db = "*******";
$con = mysqli_connect($host,$uname,$pwd,$db) or die("connection failed");
echo 'Updating init...' . "<br>";
//Create an instance of the class Update to get and update the data
$update = new Update();
try
{
// Get the product list from prestashop's DB
$productsFromPS = $update->getProductListFromPS($con);
// Cycle through all the product IDs
foreach ($productsFromPS as $product)
{
// Id of the product
$id = (int) $product['id_product'];
// Price from PS
$pricePS = (float) $product['price'];
// Get the product's stock from PS
$stockPS = $update->getProductStockFromPS($con, $id);
// Physical and reserved quantities in PS
$physQty = $stockPS['physical_quantity'];
$resQty = $stockPS['reserved_quantity'];
// Get product's price and stock from Vendus
$priceAndStockVendus = $update->getPriceAndStockFromVendus($id);
// Price from Vendus
$priceVendus = (float) $priceAndStockVendus[0];
// Tools for float compardsion
$zero = (float) 0.00;
$epsilon = (float) 0.00001;
// If the price in Vendus is 0, put 0 to stock in PS
if(!(abs($priceVendus-$zero) < $epsilon))
$stockVendus = (int) $priceAndStockVendus[1];
else
$stockVendus = 0;~
// If the prices do not match, update price
if(!(abs($pricePS-$priceVendus) < $epsilon))
$update->updatePrice($con, $id, $priceVendus);
// If the stocks do not matcth, update stock
if ($stockVendus!=$physQty)
$update->updateStock($con, $id, $stockVendus, $resQty);
}
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Other error: <br />' . $ex->getMessage();
}
/*
Class which method to get and update data
*/
class Update
{
public function getProductListFromPS ($con)
{
try
{
$sql_q = mysqli_query($con,"SELECT `id_product`, `price` FROM `ps_product` ORDER BY `id_product` ASC");
$output = "";
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
//echo $result['id_product'] . "<br>";
}
if($output)
{
//echo '4: ' . $output[4]['id_product'] . "<br>";
}
else
{
echo "empty ressult set <br>";
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "<br>";
}
return $output;
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage() . '<br>';
}
}
public function getProductStockFromPS ($con, $id)
{
try
{
$sql_q = mysqli_query($con,"SELECT `quantity`, `physical_quantity`, `reserved_quantity` FROM `ps_stock_available` WHERE `id_product` = $id");
$output = "";
if($sql_q)
{
while($result = mysqli_fetch_assoc($sql_q))
{
$output[] = $result;
//echo $result['id_product'] . "<br>";
}
if($output)
{
//echo 'qty: ' . $output[0]['quantity'] . "<br>";
//echo 'phys qty: ' . $output[0]['physical_quantity'] . "<br>";
//echo 'res qty: ' . $output[0]['reserved_quantity'] . "<br>";
}
else
{
echo "empty ressult set <br>";
}
}
else
{
echo 'Invalid query: ' . mysqli_error() . "<br>";
}
return $output[0];
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage();
}
}
public function getPriceAndStockFromVendus ($id)
{
try
{
$url = 'https://www.vendus.pt/ws/v1.1/products/';
$apiKey = '***********';
$method = 'GET';
$params = array(
'reference' => $id,
);
$url .= '?' . http_build_query($params);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, $apiKey);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
//echo 'URL to Vendus - ' . $url . '<br />';
$result = curl_exec($curl);
$resultArray = json_decode($result, true);
curl_close($curl);
return array($resultArray[0]['gross_price'], $resultArray[0]['stock']);
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage();
}
}
public function updatePrice ($con, $id, $price)
{
try
{
$sql_q = mysqli_query($con,"UPDATE `ps_product` SET `price` = '$price' WHERE `id_product` = '$id'");
$sql_q = mysqli_query($con,"UPDATE `ps_product_shop` SET `price` = '$price' WHERE `id_product` = '$id' AND `id_shop` = '1'");
if($sql_q)
{
//echo $sql_q;
}
else
{
echo 'Invalid query: ' . mysqli_error($con) . "\n";
}
echo 'Price updated (' . $id . ')' . '<br />';
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Error: <br />' . $ex->getMessage();
}
}
public function updateStock ($con, $id, $stock, $resQty)
{
try
{
$newPhysQty = $stock;
if ($newPhysQty!=0)
$newQty = $newPhysQty - $resQty;
else
$newQty = 0;
$sql_q = mysqli_query($con,"UPDATE `ps_stock_available` SET `physical_quantity` = '$newPhysQty', `quantity` = '$newQty' WHERE `id_product` = '$id'");
if($sql_q)
{
//echo $sql_q;
}
else
{
echo 'Invalid query: ' . mysqli_error($con) . "\n";
}
echo 'Stock updated(' . $id . ')' . '<br />';
}
catch (Exception $ex) {
// Shows a message related to the error
echo 'Other error: <br />' . $ex->getMessage();
}
}
}
?>
The plan is to have this code run at certain intervals to keep the DB updated.
Am I doing something wrong? Is there a faster way to do this?
This code is running on a server with 2GB of RAM and not a very fast processor. Should it be ruinning on a computer with higher specs?
I will appreciate any remarks/critcs about the code and tips on how to improve it.
Thanks in advance! ;)
EDIT: It appears running the code produces a 500 Internal Server Error, any idea what could be causing this? If I run the foreach only once it doesn't occur. How can i check the error in detail? I have CPannel as the control panel for the server.

How to extract comments from a Facebook account to my Webapp?

I am trying to extract all the comments from a Facebook account to my Webapp using Graph API by coverting the result into an array and then printing the array,but the result that I am getting is a blank array followed by the respective post.I don't know whats wrong.
if (isset($accessToken))
{
echo 'Posts:';
echo '<br>';
// getting all posts published by user
try {
$posts_request = $fb->get('/me/feed');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
$total_posts = array();
$posts_response = $posts_request->getGraphEdge();
$response_array = $posts_response->asArray();
if($fb->next($posts_response)) {
$total_posts = array_merge($total_posts, $response_array);
while ($posts_response = $fb->next($posts_response)) {
$response_array = $posts_response->asArray();
$total_posts = array_merge($total_posts, $response_array);
}
foreach ($total_posts as $key) {
if(isset($key['message'])){
echo $key['message'];
echo '<br>','<br>';
}
}
//print_r($total_posts);
} else {
$posts_response = $posts_request->getGraphEdge()->asArray();
foreach ($posts_response as $key) {
if(isset($key['message'])){
echo $key['message'];
echo '<br>','<br>';
$o_id= $key['id'];
echo $o_id;
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/113932879436074_129461837883178/comments',$accessToken);
}
catch(Facebook\Exceptions\FacebookResponseException $e)
{
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e)
{
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphEdge();
$comments=$graphNode->asArray();
print_r($comments);
}
Output:
113932879436074_131399157689446Array ( ) #TrueStory 😁
113932879436074_131393101023385Array ( ) Good afternoon Pihu Jaiswal
113932879436074_129461837883178Array ( ) Super bored
if($fb->next($posts_response)) {
$total_posts = array_merge($total_posts, $response_array);
while ($posts_response = $fb->next($posts_response)) {
$response_array = $posts_response->asArray();
$total_posts = array_merge($total_posts, $response_array);
}
foreach ($total_posts as $key) {
if(isset($key['message'])){
echo $key['message'];
echo '<br>','<br>';
}
}
//print_r($total_posts);
} else {
$posts_response = $posts_request->getGraphEdge()->asArray();
foreach ($posts_response as $key) {
if(isset($key['message'])){
echo $key['message'];
echo '<br>','<br>';
$o_id= $key['id'];
echo $o_id;
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('me?fields=id,name,posts{comments{message}}');
}
catch(Facebook\Exceptions\FacebookResponseException $e)
{
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}
catch(Facebook\Exceptions\FacebookSDKException $e)
{
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
$comments=$graphNode->asArray();
print_r($comments);
}

I can't get records from a stored procedure

I can't get records from a stored procedure. If I run from SQL Server, I get records. If I call it from .NET, I get records... but if I call it from PHP, I don't get records.
I am using PHP 5.3.3 on CentOS 6. I am using mssql. All others SP are ok.
I tried
$provider = 1010;
$array = array();
$stmt2 = mssql_init("[dbo].[PORA_sp_GET_LetterGenerationRecords]");
mssql_bind($stmt2, "#ProviderID", $provider, SQLINT4);
$letters = mssql_execute($stmt2);
while($row = mssql_fetch_assoc($letters)){
$array[] = $row;
}
mssql_free_statement($stmt2);
echo '<pre>'; print_r($array); echo '</pre>';
and I have
Array
(
)
I tried too
$array = array();
$letters = mssql_query('EXEC [dbo].[PORA_sp_GET_LetterGenerationRecords] #ProviderID = 1010');
while($row = mssql_fetch_assoc($letters)){
$array[] = $row;
}
echo '<pre>'; print_r($array); echo '</pre>';
and I got
Array
(
)
I included
echo 'MSSQL error: '. mssql_get_last_message();
and the answer:
MSSQL error:
I am very curious. Right now I am running the SP step by step from PHP. It's a shameful.
I tried:
$provider = 1010;
$array = array();
// $letters = mssql_query('EXEC [dbo].[PORA_sp_GET_LetterGenerationRecords] #ProviderID = 1010');
$stmt2 = mssql_init("[dbo].[PORA_sp_GET_LetterGenerationRecords]");
mssql_bind($stmt2, "#ProviderID", $provider, SQLINT4);
$letters = mssql_execute($stmt2);
if($letters){
echo mssql_num_rows($letters);
while($row = mssql_fetch_assoc($letters)){
$array[] = $row;
}
mssql_free_statement($stmt2);
echo '<pre>'; print_r($array); echo '</pre>';
}
else{
echo 'MSSQL error: '. mssql_get_last_message();
echo error_get_last();
}
and same answer.
Your code looks fine but for some reason the sql statement is being terminated.
So you need to debug this,I would suggest first try to get it to work with the parameter hard coded:
try {
$array = array();
$result = mssql_query('EXEC [dbo].[PORA_sp_GET_LetterGenerationRecords] #ProviderID = 1010');
while ($row = mssql_fetch_assoc($result))
{
$array[] = $row;
}
var_dump($array);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
error_log($e->getMessage());// or log it to a txt file
echo 'MSSQL error: '. mssql_get_last_message();
echo 'Last error: '.error_get_last();
}
You should also run SQL profiler and filter on the exception to have a better idea.
<?php
$query = "EXEC [dbo].[PORA_sp_GET_LetterGenerationRecords] #ProviderID = 1010";
$result = mssql_query($query);
if (!$result) {
die('Invalid query: ' . mssql_error());
}
while ($row = #mssql_fetch_assoc($result)) {
echo $row['col1']
}
?>

get users geo location and echo out mysql results based on location?

Hi i am trying to find our what city my users are in from their ip address to be able to display a list of users in my database close to them/in their area.
I have been looking at this api:
http://ipinfodb.com/ip_location_api.php
and i have registered and got an api key, but im not sure where to go from here. Here is the example code they have used to get the users location:
<?php
include('ip2locationlite.class.php');
//Load the class
$ipLite = new ip2location_lite;
$ipLite->setKey('<api key>');
//Get errors and locations
$locations = $ipLite->getCity($_SERVER['REMOTE_ADDR']);
$errors = $ipLite->getError();
//Getting the result
echo "<p>\n";
echo "<strong>First result</strong><br />\n";
if (!empty($locations) && is_array($locations)) {
foreach ($locations as $field => $val) {
echo $field . ' : ' . $val . "<br />\n";
}
}
echo "</p>\n";
//Show errors
echo "<p>\n";
echo "<strong>Dump of all errors</strong><br />\n";
if (!empty($errors) && is_array($errors)) {
foreach ($errors as $error) {
echo var_dump($error) . "<br /><br />\n";
}
} else {
echo "No errors" . "<br />\n";
}
echo "</p>\n";
?>
but how would i now set a mysql query that says if the user location is london and users are listed as in london in the database then to display these to the user?
i would really appreciate a push in the right direction here if anyone can help, thanks.
Here is an example (without knowing your database structure and untested ;). Insert this in the foreach ($locations as $field => $val) loop as below:
foreach ($locations as $field => $val) {
echo $field . ' : ' . $val . "<br />\n";
$mysqli = new mysqli('<mysql server>', '<mysql user>', '<mysql password>', '<database>');
if(mysqli_connect_errno()) {
echo 'Error: Unable to connect to Database; ';
} else {
if ($stmt_evt = $mysqli -> prepare('SELECT <other_users>, ... FROM <your table> WHERE <user_location> LIKE ? ORDER BY <whatever>')) {
$stmt_evt -> bind_param('s', $val);
$stmt_evt -> execute();
$stmt_evt -> bind_result($<other_users>, $...);
while ($stmt_evt->fetch()) {
echo 'Other users in your area: '.$<other_users>;
}
} else {
echo 'Error: Unable to prepare Event statement.';
}
}
}

Categories