What are some best practices for handling the return value of socket_write() in PHP to ensure successful data transmission?

When using socket_write() in PHP to send data over a socket connection, it is important to handle the return value of the function to ensure successful data transmission. The return value of socket_write() indicates the number of bytes successfully written to the socket. It is crucial to check this return value against the length of the data being sent to ensure that all data has been transmitted successfully.

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    // Handle socket creation error
}

$bytes_sent = socket_write($socket, $data, strlen($data));
if ($bytes_sent === false) {
    // Handle socket write error
} elseif ($bytes_sent < strlen($data)) {
    // Handle partial data transmission
} else {
    // Data transmitted successfully
}

socket_close($socket);