PHP pinging, even 1 request timeout - php

I have been using the script below, however, I want it to ping 3-4 times, and within that 3-4 times if it has even a single request timeout, I want php to come back as failed.
Here's a script I'm using:
<?php
function pingAddressHasNeverFailed($tries) {
for ($i = 0; $i < $tries; $i++) {
$pingresult = shell_exec("ping -c 1 www.google.com", $outcome, $status);
if ($status != 0)
return false;
}
return true;
}
if (pingAddressHasNeverFailed(3)) {
echo "uoc gi";
}
?>
Please help if you can, thank you so much in advance!

If any ping fails (in a set) it will not have 0% in the output (i.e. 0% packet loss), which is the same for Linux and Windows:
function ping($host, $times = 3)
{
exec("/bin/ping -c 3 $host", $out, $status);
return $status === 0 && false !== strpos(join('', $out), '0%');
}
if (ping('www.google.com)) {
echo "yay\n";
} else {
echo "oh dear\n";
}
You may have to adjust the ping arguments to fit your environment and make sure that the host name is sanitized.

In that case you'll need to execute command n (n is a number of tries) times. E.g.:
function pingAddressHasNeverFailed($tries) {
$outcome = array();
$status = -1;
for ($i = 0; $i < $tries; $i++) {
$pingresult = exec("/bin/ping -n 1 www.google.com", $outcome, $status);
if ($status != 0)
return false;
}
return true;
}
Usage:
if (pingAddressHasNeverFailed(3)) {
//do something useful
}

Related

Recursive function to find the number of ways a number can be generated out of a set of numbers

I had a job interview test and the question I got was about making a function which would return the number of ways a number could be generated by using numbers from a certain set and any number in the set can be used N times.
It is like if I have the number 10 and I want to find out how many ways 10 can be generated using [2,3,5]
2+2+2+2+2 = 10
5+3+2 = 10
2+2+3+3 = 10
5+5 = 10
to solve it I made this function:
function getNumberOfWays($money, $coins) {
static $level = 0;
if (!$level) {
sort($coins);
}
if ($level && !$money) {
return 1;
} elseif (!$level && !$money) {
return 0;
}
if ($money === 1 && array_search(1, $coins) !== false) {
return 1;
} elseif ($money === 1 && array_search(1, $coins) === false) {
return 0;
}
$r = 0;
$tmpCoins = $coins;
foreach ($coins as $index => $coin) {
if (!$coin || $coin > $money) {
continue;
}
$tmpCoins[$index] = 0;
$tmpMoney = $money;
do {
$tmpMoney -= $coin;
if ($tmpMoney >= 0) {
$level++;
$r += getNumberOfWays($tmpMoney, $tmpCoins);
$level--;
} elseif (!$tmpMoney) {
$r++;
}
} while ($tmpMoney >= 0);
}
return $r;
}
This function works ok and returns the right value.
My question is if there is a better way for it.
Thanks

Pausing PHP process via command line

I am running this via the command line. When the loop is running, is there any way I can pause the execution of the code? Ideal case would be that I could press a key to pause and then another key to resume. If I don't press the pause key then the loop continues until $i == 1000
<?php
echo "How long should the code sleep between increments?\n";
echo ">> ";
$sleep = trim(fgets(STDIN));
for ($i = 1; $i <= 1000; $i++) {
echo "$i\n";
sleep($sleep);
}
This is a heavily simplified example of my actual need for the code.
I don't sure my code is best solution or not but it work.
function checkResume()
{
$r = false;
while (!$r) {
if (fgets(STDIN) == "r") {
$r = true;
}
}
}
function checkPause()
{
$input = fgets(STDIN);
if (!empty($input) && $input == "p") {
return true;
}
return false;
}
echo "How long should the code sleep between increments?\n";
echo ">> ";
$sleep = trim(fgets(STDIN));
echo "\nStart ...\n";
stream_set_blocking(STDIN, false);
for ($i = 1; $i <= 1000; $i++) {
if (checkPause()) {
echo "wait for resume \n";
checkResume();
}
echo "$i\n";
sleep($sleep);
}
Hope this help.

Switch emails servers every thousand?

I am trying to switch phpmailer information to shift email server loads every 1000 emails sent. For example every 1000 emails sent, I want to use a different server.
1-1000 emails use server 1
1001-2000 use server 2
2001-3000 use sever 1 and so on
So far I am using this:
$x =1;
foreach($data as $value) {
if ($x <= 1000) {
//use server 1
$x++;
} else {
//use server 2
if ($x == 2000) {
$x = 1;
}
}
Is there a better or more standardized way to achieve this?
Maybe a bit more elegant than if/else:
$phpMailerInstances = ['server1' => $yourInstance, 'server2' => $yourInstance2]
function getServer($currentServer){
if($currentServer == 'server1')
{
return 'server2';
}
return 'server1';
}
$currentServer = 'server1';
for($i = 0; $i < 10000; $i++)
{
echo $i.PHP_EOL;
if($i % 1000 == 0)
{
$currentServer = getServer($currentServer);
echo '>>>>>'.$currentServer.PHP_EOL;
}
$phpMailerInstances[$currentServer]->send()
}
?>

Symfony Tasks wait for multiple tasks

I'm starting 10 processes asynchronously:
$procs = [];
for($i = 0; $i < 10; $i++) {
$proc = new Process('ls -lsa');
$proc->start();
$procs[$i] = $proc;
}
Now i want to wait asynchronous for every process to finish and print out state informations while waiting:
foreach($procs as $proc) {
$proc->wait(function ($type, $buffer) {
if (Process::ERR === $type) {
// Print out error ...
} else {
// Print out state informations ...
});
}
}
The Problem is at the wait function. It waits for the task to finish and then go on to the next tasks. But i want this to run asynchronous.
How can i do this?
Thanks !
As per the Symfony docs the wait method is blocking and therefore will wait until that process is finished before continuing.
If you don't want to wait you could refactor your code to use the run method:
for($i = 0; $i < 10; $i++) {
$process = new Process('ls -lsa');
$process->run(function ($type, $buffer) {
if (Process::ERR === $type) {
echo 'ERR > '.$buffer;
} else {
echo 'OUT > '.$buffer;
}
});
$procs[$i] = $proc;
}

PHP - If no results, wait and try again

I'm calling a web service via GET protocol and the response will either be echoed out on the page as true or false.
I'm trying to write logic that will retry up to 3 times if the web service returns false. However, the first time I want to wait 1 second, the second time I want to wait 10 seconds, and the third time I want to wait 60 seconds.
This is what I currently have. Is there a better way to achieve this?
if ($wsReturn == 'false') {
sleep(1);
$wsReturn = strip_tags(file_get_contents($link));
if ($wsReturn == 'false') {
sleep(10);
$wsReturn = strip_tags(file_get_contents($link));
if ($wsReturn == 'false') {
sleep(60);
$wsReturn = strip_tags(file_get_contents($link));
}
}
}
Just use an array and a loop to make any number of iterations with any pause times
$i = 0;
$sleep = [1, 10, 60];
while( $wsReturn == 'false' )
{
sleep( $sleep[$i] );
// your logic goes here
$wsReturn = strip_tags(file_get_contents($link));
if( ++$i >= count($sleep) )
break;
}
This is what I ended up with after #Pavel Lint sparked the idea for me:
$i = 0;
$waitTimes = array();
$waitTimes = [1, 10, 30]
while ($wsReturn == 'false') {
sleep( $waitTimes[$i] );
$wsReturn = strip_tags(file_get_contents($link));
$++i
if ($i >= count($waitTimes)-1) { break; }
}

Categories