What are some best practices for error handling when sending data to a server using stream_socket_client() in PHP?
When sending data to a server using `stream_socket_client()` in PHP, it is important to handle errors gracefully to ensure the stability and reliability of the application. One best practice is to check for errors using `stream_get_meta_data()` after attempting to establish the connection. This allows you to detect any connection issues and take appropriate action, such as logging the error or displaying a message to the user.
$socket = stream_socket_client('tcp://example.com:80', $errno, $errstr, 30);
if (!$socket) {
$metadata = stream_get_meta_data($socket);
if ($metadata['timed_out']) {
echo 'Connection timed out';
} else {
echo 'Error connecting to server: ' . $errstr;
}
} else {
// Send data to the server
fwrite($socket, 'Hello, server!');
// Close the connection
fclose($socket);
}