I am trying to loop through an array of four servers. I am trying to find a user on those servers. I am able to see the program works but PHP throws errors from the servers it cannot find from the array. Could someone help how to avoid those errors?
$ID = '1234';
$server_list = array("example1.com", "example2.com", "example3.com");
function serverQuery($server_array, $ID){
foreach ($server_array as $value) {
$host = $value;
try{
include('info.php');
$response = $client->getUser(array("name" => ID))->return;
//print_r($response);
}catch (Exception $e){
echo "Print the error";
}
}
}
Every time I search the user, it did fine in one of the servers but "Print the Error" is also printed along with it. Please help.
Thanks.
Related
php foreach - try catch, I don't know why I get 500 Error.
in my code, I used this way to call activeMQ, but I will get 500 Error. I don't know what's happen.
This code only run to $url = "tcp://".$url; cannot run to uder try{}. Where is issues?
$stomp = null;
$mqUser='aaa';
$mqPasswd='aaa';
foreach ($urls as $url) {
$url = "tcp://".$url;
//echo $url." stomp status: null;<br />";
try {
$stomp = new Stomp($url);
} catch(Exception $e) {
}
if ($stomp) {
break;
}
}
I am running a web app to get a list of users with Google API PHP Client Library 2.0.3. and save them to a CSV file and at the same time, I am tracking the process on screen. The code I am using is the following:
$pageToken = null;
$optParams = array(
"customer" => "my_customer",
"maxResults" => 500,
"orderBy" => "email",
"sortOrder" => "ASCENDING"
);
try {
$usernum = 0;
do {
if ($pageToken){
$optParams['pageToken'] = $pageToken;
}
$results = $service->users->listUsers($optParams);
$pageToken = $results->getNextPageToken();
$users = $results->getUsers();
foreach ($users as $user) {
$usernum++;
$csvfileusers = array($user->getPrimaryEmail());
fputcsv($savecsv, $csvfileusers);
$usersemails = $user->getPrimaryEmail();
print "<li>".$usernum." - <font color='#9dd7fb'>".$usersemails."</font></li>";
}
} while($pageToken);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
Everything works fine. The problem is that from time to time I am getting { error: { errors: [ { domain: global, reason: backendError, message: Service unavailable. Please try again } ], code: 503, message: Service unavailable. Please try again } }
I know this means that I am sending requests to Google Server too fast hence I need to implement an exponential backoff solution. My problem is that I don't know how to do that. Would someone be kind enough to provide me an example on how to do that using the PHP Client Library? I know that I might be able to figure this out at the long term but if I can get some help I will greatly appreciate it.
Unfortunately, the documentation is lacking for the actual backoff implementation. However, the Google_Task_Runner class outlines the backoff implementation process. You can see how it does it here.
However, based on what you're doign you don't actually want to implement a exponential backoff procedure in general networking terms. You're really wanting to just throttle the request so you don't slam the API. Depending on how many $pageToken you're iterating over, you could just do a sleep before doing the next while iteration.
Additionally, what does $pageToken = $results->getNextPageToken(); become after one request? Becuase you're setting that from the response rather than decrementing it programatically, which may be causing an infinute loop or something of that nature.
So after 20 days of trying and investigating and thanks to the information provided by #kyle, I came up with this exponential backoff solution.
$attemptNum = 1; // retry attempt
$expBackoff = false; // exponential backoff rety indicator
do {
if($attemptNum <= 4) {
try {
$usernum = 1;
do {
if ($pageToken){
$optParams['pageToken'] = $pageToken;
}
$results = $service->users->listUsers($optParams);
$pageToken = $results->getNextPageToken();
$users = $results->getUsers();
foreach ($users as $user) {
$csvfileusers = array($user->getPrimaryEmail());
fputcsv($savecsv, $csvfileusers);
$usersemails = $user->getPrimaryEmail();
print "<li>".$usernum." - <font color='#9dd7fb'>".$usersemails."</font></li>";
$usernum++;
}
} while($pageToken);
} catch (Exception $e) {
$err503ReasonA = "Service unavailable"; // Service unavailable.
$err503ReasonB = "Backend Error"; //Backend Error
$exception = $e->getMessage();
if(strpos($exception, $err503Reason) !== false || strpos($exception, $err503ReasonB) !== false){
$expBackoff = true;
$sleeptime = $retrynum * 1; //retrynum * seconds
sleep($sleeptime);
$retrynum++;
} else {
$expBackoff = false;
print "There was an error -> $exception";
}
}
} else {
$expBackoff = false;
}
} while ($expBackoff);
I have been trying this solution for two days now and it has worked like a charm. Hopefully this might be helpful for someone else. I´m happy now. :)
Im try to send a Message from PHP Website via TCP/IP to an Arduino.
With following code i'm able to send a message from php website
<?php
$errno = NULL;
$error = NULL;
if (!$handle = #fsockopen("192.168.188.24", "49419", $errno, $error, 10))
{
die("Fehler (".$errno."): ".$error);
}
fwrite($handle, "ON\r\n");
fclose($handle);
?>
The problem is, when calling the website for the first time, the message doesnt get delivered immediatly. Just after some refreshes of the website, the message arrives, but logical so many times like amount of website refreshes.
Already tried to limit the messagelength to 2bytes, but without any success.
Try adding inside a try - catch block.
try {
} catch (Exception $e) {
echo $e->getMessage();
}
To see what exception you may get.
I have a cron job running every 10-15 minutes pinging minecraft servers in my database, and if one of them returns "offline", the database records the time this happened and sticks in it the lastDT (last downtime) table. My question is, how can I collect all of the times, and at the end of each month figure out the average downtime (if any). I assume this would be ((totalMinutesInMonth-totalMinutesOfDT)*100). Is there a way to do this? To get a better idea of what I'm dealing with, here is some code to reference:
<?php
require_once './inc/connectToDB.php';
date_default_timezone_set('UTC');
session_start();
try {
$collectServers = $database->prepare('SELECT * FROM servers');
$collectServers->execute();
$serversDat = $collectServers->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log($e->getMessage());
exit();
}
foreach ($serversDat as $server) {
try {
$remoteCon = #fsockopen(#gethostbyname($server['address']),$server['port'],$errno,$errstr,1);
$connected = false;
if (#is_resource($remoteCon)) { $connected = true; #fclose($remoteCon); }
if ($connected) { $serverStat = 'Online'; } else { $serverStat = 'Offline'; }
if ($serverStat == 'Offline') {
$downTime=date('H:i:s',time());
} else {
$downTime=0;
}
$reinsert = $database->prepare('UPDATE servers SET status=:status,lastPing=:time,lastDT=:lastdt WHERE id=:id');
$reinsert->bindValue(':id',$server['id'],PDO::PARAM_INT);
$reinsert->bindValue(':status',$serverStat,PDO::PARAM_STR);
$reinsert->bindValue(':time',date('H:sa T',time()),PDO::PARAM_STR);
$reinsert->bindValue(':lastdt',$downTime,PDO::PARAM_STR);
$reinsert->execute();
} catch (PDOException $e) {
error_log($e->getMessage());
exit();
}
}
unset($database);
exit();
?>
The database table looks like:
(http://i.imgur.com/0ypc99g.png)
If I can provide more info, I'd be glad to do so. Not sure what to do from here, however. Thanks in advance.
EDIT: If anyone has any idea how to do this more efficiently, I'm all for rewriting. This is not working out for me.
It seems like finding the time the server went down is only half of the equation. You will also need to know when the server came back up.
Down at 10:00AM, Up at 10:15AM equals 15min downtime.
You will need to store that in the database somewhere. That isn't solution, but it does seem like the next step.
I've been playing around with a php class I found on the net called Config Magik that I use to store some info in a INI file but have recently run into some problems when using removeKey. I wanted to know if someone can point me to a similar class that would work as well or better. Or if there is a better way to go about this.
This is my function right now, after playing around with it like crazy, so it is probably very faulty.
require_once('class.ConfigMagik.php');
$config = new ConfigMagik('config.ini', true, true);
if(!empty($_GET)){
if(!is_writeable('config.ini')){
echo 'Could not write to config.ini';
return false;
}
//if there is no section parameter, we will not do anything.
if(!isset($_GET['section'])){
echo false; return false;
} else {
$section_name = $_GET['section'];
unset($_GET['section']); //Unset section so that we can use the GET variable to manipulate the other parameters in a foreach loop.
if (!empty($_GET)){
foreach ($_GET as $var => $value){
echo $var.'='.$_GET[$var].'<br />';
//Check if said variable $var exists in the section.
if($config->get($var, $section_name) !== NULL){
//Set variable value.
try{
$config->set($var, $value, $section_name);
echo 'Setting variable '. $var.' to '.$value.' on section '.$section_name;
} catch(Exception $e) {
echo 'Could not set variable '.$var;
echo $e;
return false;
}
} else {
echo $var.' does not exist <br />';
}
}
}
try{
$section = $config->get($section_name); //Get the entire section so that we can manipulate it.
echo '<pre>';print_r($section);echo '</pre>';
foreach ($section as $title=>$value){
if(!isset($_GET[$title]) && isset($section[$title])){
try{
$config->removeKey($title, $section_name);
echo '<b>'.$title.'</b>: removed <br />';
} catch(Exception $e){
echo $e;
}
}
}
} catch(Exception $e){
echo $e;
}
$config->save();
//echo $config->toString('HTML');
echo true;
return true;
}
} else { RUN SOME HTML }
It basically saves the settings I pass on from the GET parameters and if the parameters are not there it is supposed to delete it. When I get to $config->removeKey($title, $section_name); in the last try catch statement it won't save automatically (as it should), so I tried running $config->save() and I ended up with a ini file that had section = array everywhere. Any advice will be appreciated as I've been learning PHP on the web for the last few weeks so I believe I've got a ways to go.
I have definitely isolated the problem to the $config->save() part, just don't know how to solve it.
Thanks in advance.
I have been using Zend_Config_Ini and Zend_Config_Writer_Ini in the past and was satisfied with the features. You will have extract the whole library/Zend/Config folder from Zend Framework and make Zend_Exception available though.