Question

I am using php's net_ssh2 module to login to servers and retrieve a file for real time data collection. The servers all have the same username and password. The problem I am facing is, if one of the server is down or has a different password for some reason, my script stops. I need script to skip the problematic server and continue to process other servers in the array.

Here is my current php script to do this:

include('Net/SSH2.php');
$servers=array('server1', 'server2','server3', 'server4', 'server5');
foreach ($servers as &$value1) {

    $server=$value1."example.net";

    $ssh = new Net_SSH2($server);
        if (!$ssh->login('username', 'password')) {
            exit('Login Failed');
        }

How would I skip the servers in the servers array that I am not able to connect and continue processing the others?

Was it helpful?

Solution

Use continue:

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

if (!$ssh->login('username', 'password')) {
    echo('Login Failed'); // <-- remove if desired
    continue;
}

If you want your loop to end when you find a successful server connection you would use break, too:

if (!$ssh->login('username', 'password')) {
    continue;
}
else {
    break;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top