Monday, March 14, 2022

[SOLVED] How to handle fsockopen error in PHP?

Issue

try {
    $fp = fsockopen($site, $port, $errno, $errstr, 2);
}
catch(Exception $ex) {
    echo 'error';
}

Why is the catch not working, while I'm see that warnings are given for fsockopen

Warning: fsockopen(): php_network_getaddresses: getaddrinfo failed: No such host is known.

and

Warning: fsockopen(): unable to connect to www.myrandsitedf.net:80 (php_network_getaddresses: getaddrinfo failed: No such host is known. )

I know that I can use @ to suppress the error/warning messages, but I don't think that this is the right way to handle an error.

Also the Cronjob at my host doesn't allow PHP files with errors in it, @ doesn't solve it.


Solution

You have to make the difference between exceptions and errors. If you want errors (warning, etc...) to be transformed into exception such that they can be caught in the catch, you should register a error_handler that converts the error into an exception:

function error_handler($errno, $errstr, $errfile, $errline)
{
    if( ($errno & error_reporting()) > 0 )
        throw new ErrorException($errstr, 500, $errno, $errfile, $errline);
    else
        return false;
}
set_error_handler('error_handler');


Answered By - Simon
Answer Checked By - Robin (WPSolving Admin)