What are the best practices for handling errors in PHP functions like fsockopen?

When using functions like fsockopen in PHP, it is important to handle errors properly to ensure robustness and prevent unexpected behavior. One common practice is to check for errors using the error handling functions provided by PHP, such as error_get_last(). Additionally, using try-catch blocks can help catch and handle exceptions that may occur during the execution of the function.

// Open a socket connection using fsockopen
$fp = @fsockopen('example.com', 80, $errno, $errstr, 5);

// Check for errors
if (!$fp) {
    // Handle the error
    echo "Error: $errstr ($errno)";
} else {
    // Connection successful, continue with operations
    // ...
    
    // Close the socket connection
    fclose($fp);
}