Morning. Im trying to check if i can connect via telnet and echo a string depending on the result. The problem is it shows the error message followed by echoes

PHP Code:
    $usenet fsockopen($cfgServer$cfgPort$errno$errstr$cfgTimeOut);      
$usenet){     echo "failed";     echo "  ".date('H:i:s'time()+3600);}     
else { echo 
"connected"; } 

Warning: fsockopen(): unable to connect to 213.***.***.***:**** (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.) in C:\Program Files (x86)\EasyPHP-DevServer-13.1VC11\data\localweb\projects\Testing2.0\privatepingtelnet.php on line 17 failed 09:27:27
expected result

failed 09:27:27
How to properly catch the error ?