Question

don't have enough reputation to tag this properly (ruby,PHP,socket,rescue)

I haven't practised my PHP in a long time, as I've been doing more Ruby scripting. I'm kind of embarrassed to ask for help with this.

I know, in Ruby, that I can use rescue to prevent the script from crashing in the case of error, and I'm hoping to achieve the same thing with PHP.

For example, in Ruby:

require 'socket'

begin puts "Connecting to host..." 
host = TCPSocket.new("169.121.77.3", 333) 
# This will (intentionally) fail to connect, triggering the rescue clause. 
rescue puts "Something went wrong." 
# Script continues to run, allowing, for example, the user to correct the host IP. 
end

My PHP code is a little messy - it's been quite a long time.

function check_alive($address,$service_port) { 
    /* Create a TCP/IP socket. */ 
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); 
    if ($socket === false) { 
      echo socket_strerror(socket_last_error());
    } 
    else { 
      echo null; 
    } 
    $result = socket_connect($socket, $address, $service_port); 
    if ($result === false) { 
       echo socket_strerror(socket_last_error($socket)); 
       return 1; 
    }
    else { 
       echo null; 
    } 
    socket_close($socket); 
    return 0; } 
    $hosts = [...]; 
    // list of hosts to check 
    foreach($hosts as $key=>$host) { 
       check_alive($hosts); 
    }

Essentially, I have an array of hosts, and I'd like to check to see if they're alive. It's not necessary for ALL hosts to be alive, so here's where I'm stuck - the first dead host in the array crashes the script.

Any suggestions would be very much appreciated - I'm willing to accept that I don't fully understand socket connections in PHP.

Was it helpful?

Solution

The PHP equivalent is:

try { ... } catch (...) { ... }

If you're using PHP 5.5, there also is:

try { ... } catch (...) { ... } finally { ... }

You can have several catch clauses, each catching a different exception class.

The finally part is always run, including when an exception got raised.

OTHER TIPS

The following is the PHP equivalent for exception handling:

try { // equivalent of Ruby `begin`

} catch(Exception $e) { // equivalent of Ruby `rescue(e)`

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top