Hit API only when there is change - Live Score - php

I'm using an API that provides the score of the game. To show the score in real-time, I'm hitting API after every 2-3 seconds to see if any changes happen in the score but I think this method isn't very efficient. It would exceed my API requests very quickly. Is there any other way to achieve this method (that hits API only when there is a change in the score)? or Is this something that isn't possible with PHP?
This is what I'm currently doing (just an example)
<?php
while(true){
$api_url = "here goes url that returns response in json";
$score_api = file_get_contents($api_url);
$score_array = json_decode($score_api, true);
$score = $score_array['result']['score'];
sleep(2); // hit API again after 2 seconds
}
?>

Related

What type of configration is required to call run multirequest in PHP?

I want to run more than 2500+ call on same time. So i have created a batch of 100 (2500/100 = 25 total call).
// REQUEST_BATCH_LIMIT = 100
$insert_chunks = array_chunk(['array', 'i want', 'to', 'insert'], REQUEST_BATCH_LIMIT);
$mh = $running = $ch = [];
foreach ($insert_chunks as $chunk_key => $insert_chunk) {
$mh[$chunk_key] = curl_multi_init();
$ch[$chunk_key] = [];
foreach ($insert_chunk as $ch_key => $_POST) {
$ch[$chunk_key][$ch_key] = curl_init('[Dynamic path of API]');
curl_setopt($ch[$chunk_key][$ch_key], CURLOPT_RETURNTRANSFER, true);
curl_multi_add_handle($mh[$chunk_key], $ch[$chunk_key][$ch_key]);
}
do {
curl_multi_exec($mh[$chunk_key], $running[$chunk_key]);
curl_multi_select($mh[$chunk_key]);
} while ($running[$chunk_key] > 0);
foreach(array_keys($ch[$chunk_key]) as $ch_key) {
$response = curl_getinfo($ch[$chunk_key][$ch_key]);
$returned_data = curl_multi_getcontent($ch[$chunk_key][$ch_key]);
curl_multi_remove_handle($mh[$chunk_key], $ch[$chunk_key][$ch_key]);
}
curl_multi_close($mh[$chunk_key]);
}
When i running this in local the system is hanged totally.
But this limit of batch like 100, 500 are not same on different device and server, so what is the reason about it? and what changes should i do to increase it?
If i am adding 1000 data with batch of 50, so for every batch 50 records should insert, but it insert randomly for a batch like 40, 42, 48, etc. so way this is skipped calls? (If i am using single record with simple cURL using loop then it is working fine.)
P.S. This code is i am using for bigcommrece API.
The BigCommerce API definitely throttles requests. The limits are different depending on which plan you are on.
https://support.bigcommerce.com/s/article/Platform-Limits
The "Standard Plan" is 20,000 per hour. I'm not sure how that is really implemented, though, because in my own experience, I've been throttled before hitting 20,000 requests in an hour.
As Nico Haase suggests, the key is for you to log every response you get from the BigCommerce API. While not a perfect system, they do usually provide a response that is helpful to understand the failure.
I run a process that makes thousands of API requests every day. I do sometimes have requests that fail as if the BigCommerce API simply dropped the connection.

Problem executing some PHP data after 1.5 seconds

I have some PHP code whereby I post data to an API and get some response data. When a user pays the response status from the API should change. I am trying to delay the execution of PHP code and wait for 15 seconds before getting the payment status from the API which is not working as expected.. I have no idea how to do that in PHP or rather Laravel Queues since am using Laravel 5.4
~ Kindly assist?
$data = array(
'payment_reference' => $checkID,
'payment_type' => $type
);
//Post request to an API and get the status and store in a variable
$paySt = $this->global_Curl($data, 'api/payment/status')->data;
sleep(15);
//Second call to the API after sleep to check if status has changed
$payStat = $this->global_Curl($data, 'api/payment/status')->data;
if($payStat->status === '1'){
return 'true';
}
sleep() function is used to delay the current execution
check the link
https://www.w3schools.com/php/showphp.asp?filename=demo_func_misc_sleep
In your case, you need to again call the payment api after 4-5 sec delay
For Example:
#Payment process hit code
#sleep(4); //delay/wait for 4 second
#Again run code to check the payment status.

Calculate address from latitude and longitude in google API (More than one address calculation in one request)

This function for Reveres Geocoding works well for me. I have to display the address in the information window of a marker, and there are more then 200 in one map. I built the code below and it works perfectly. However, Google's API request limit of 2500/day gets exceeded easily.
Is there any way in I can bulk request Google's API?
Our project is currently a small one, so buying more requests/day isn't an option for us.
<?php
function getaddress($lat,$lng)
{
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($lat).','.trim($lng).'&sensor=false';
$json = #file_get_contents($url);
$data=json_decode($json);
$status = $data->status;
if($status=="OK")
return $data->results[0]->formatted_address;
else
return false;
}
?>
No, you can't "bulk query" a bunch of addresses and have it only count as one request when using the standard API. Each lookup counts as a request.
There are other APIs that don't have limits, or allow more lookups, like MapQuest. If you're hitting the daily limit with Google, try using another API.

Twilio - Putting two callers in the same dynamically-generated conference room creates infinite loop

I've seen some Twilio experts answer other questions on here before about using Twilio's service so I'm hoping this catches the eye of one of them. :)
Essentially, I need to create a system whereby two callers can connect (a sales agent and a customer) with the capability for a manager to listen in to a live call. From my research into Twilio's API I believe the only way to accomplish this is to have each call be a conference call, and allow the managers to join that call in 'muted' mode, thereby only allowing them to listen to the call between the agent and customer.
I'm developing in PHP and I believe I have 90% of the puzzle solved, however I'm have trouble with one small detail.
I'll lay out the logical flow below so you can see what I'm trying to do:
1) Customer or Sales Agent dials a number.
2) Conference room gets dynamically generated and the person dialing out is placed into that room.
3) I use the REST API to make a call request to the other number, then direct them into the conference room that was already generated with the first person waiting.
I have steps 1 and 2 completed and working fine, step 3 is where the problem occurs. When I use the API to generate the second call to bring the other person into the conference room the request goes through the same application that was used to generate the first call, thereby creating an infinite loop of making new calls and generating new rooms. I have attached my code below to help explain the issue.
public function index()
{
if (isset($_REQUEST['PhoneNumber'])) {
// The agent is making a call (outgoing)
$data['callerId'] = $this->users->getPhoneNumber($_REQUEST['Caller']);
$userIdExplode = explode(':', $_REQUEST['Caller']);
$data['userId'] = $userIdExplode[1];
$callTarget = $this->security->xss_clean($_REQUEST['PhoneNumber']);
$data['numberOrClient'] = "<Number>" . $callTarget . "</Number>";
$data['phoneIsOnline'] = $this->users->isPhoneOnline($data['userId']);
// Call log information
$data['ani'] = $data['callerId'];
$data['dnis'] = $callTarget;
} elseif (isset($_REQUEST['To'])) {
// The agent is receiving a call (incoming)
$callTarget = $this->security->xss_clean($_REQUEST['To']);
$data['userId'] = $this->users->getIdByPhoneNumber($callTarget);
$data['numberOrClient'] = "<Client>" . $data['userId'] . "</Client>";
$data['phoneIsOnline'] = $this->users->isPhoneOnline($data['userId']);
// Call log information
$data['ani'] = $_REQUEST['From'];
$data['dnis'] = $_REQUEST['To'];
}
// Log the new call and receive it's log ID
$data['callLogId'] = $this->call->logNewCall($data['ani'], $data['dnis'], $data['userId']);
// Load the TWIML (Twilio XML) to bring the caller into a conference room
$this->load->view('twilio/connections_twiml', $data);
// Bring the destination number into the same conference room as the origin number
$this->dialToConference($data['ani'], $data['dnis'], $data['callLogId']);
}
public function dialToConference($caller, $callee, $confNum)
{
// Twilio capability library (capable of incoming and outgoing calls)
include APPPATH . 'libraries/twilio/Services/Twilio.php';
// Twilio account codes required for the client
$accountSid = $this->config->item('twilio_accountSid');
$authToken = $this->config->item('twilio_authToken');
$client = new Services_Twilio($accountSid, $authToken);
$call = $client->account->calls->create(
$caller,
$callee,
BASE_URL . 'twilio/twilio_connections/loadConferenceTwiml?conferenceId=' . $confNum
);
}

Twitter API: Get Followers +99

Using the twitter API (and OAuth) if i was to call for the user followers, (statuses/followers) i would be returned only 99 results.
Is there a way i can return 99, then call again starting at follower 100 then looping through this style of calling until the total number of followers has been returned?
Or just return ALL followers?
You need to specify cursor parameter as described in the API documrnation. E.g. specify cursor=-1 to request the first page and then use a next_cursor value returned in the first response:
http://twitter.com/statuses/followers/barackobama.xml?cursor=-1
http://twitter.com/statuses/followers/barackobama.xml?cursor=1300794057949944903
<?php
$trends_url = "http://api.twitter.com/1/statuses/followers/fawadghafoor.json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $trends_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
foreach($response as $friends){
$thumb = $friends['profile_image_url'];
$url = $friends['screen_name'];
$name = $friends['name'];
?>
<a title="<?php echo $name;?>" href="http://www.twitter.com/<?php echo $url;?>"><img class="photo-img" src="<?php echo $thumb?>" border="0" alt="" width="40" /></a>
<?php } ?>
Be sure you're using the right call. followers/ids gives you 5000 at a time (but it's just a list of ids). This call, too, uses the cursor to let you step through pages of users. You get a zero back when you have them all.
Twitter API restricts us to make api Call for method followers/ids is 15 requests per 15 minutes. If you make more than this api will give you an error message that Rate Limit Reached.
For more information of twitter API rate Limit
Visit-https://dev.twitter.com/docs/rate-limiting/1.1 and https://dev.twitter.com/docs/rate-limiting/1.1/limits
Twitter only allows a certain number of API requests per hour, and I think minute. You might not be able to retrieve any more than 99 requests at once.
Though I asked this quite a while ago, I came back to building something quite similar recently (+ new programming skills).
I noticed Twitter API have a method to get all of a users followers (or followings) user ID's in one request. I found the best way was to array_chunk up the ID's into batches of 100 (and only take the first 30 arrays as I dont want to use all the users api requests that hour - they might want to actually tweet!). Then there is a method that allows you to get up to 100 users userinfo (from the view of the currently authenticated user) so I just do a loop (sleep a bit inbetween) and then you've got 30,000 twitter followers!
I would recommend doing this asynchronously in a queue system, as if you do this on the fly when the users requests a page on the site it could be very slow and you might be prone to a HTTP timeout. Also cache them like hell!
Sorry I didn't post any code, but hopefully this thought process will help someone :)
$cursor = -1;
$account_from = 'twitter_account';
do
{
$json = file_get_contents('http://api.twitter.com/1/statuses/followers/' . $account_from .'json?cursor=' . $cursor);
$accounts = json_decode($json);
foreach ($accounts->users as $account)
{
array(
':twitter_id' => $account->id_str,
':account' => $account->screen_name,
':description' => $account->description,
);
}
$cursor = $accounts->next_cursor;
}
while ($cursor > 0);

Categories