Skip to content

PHP socket_get_status() Function: Everything You Need to Know

As a PHP developer, you may need to check the status of a socket to ensure that it is open and ready for use. The socket_get_status() function is a built-in PHP function that retrieves this information.

What is the socket_get_status() Function?

The socket_get_status() function retrieves the status of a stream resource. Note that it is designed for stream resources (e.g., from fsockopen() or stream_socket_client()) rather than raw socket resources from socket_create(), which can trigger deprecation warnings in PHP 8+.

How to Use the socket_get_status() Function

Using the socket_get_status() function is straightforward. Here is the syntax of the function:

The PHP syntax of socket_get_status() Function

php
socket_get_status(resource $socket);

The function takes one parameter:

  • $socket: The stream resource to retrieve the status of.

Here is an example of how to use the socket_get_status() function to retrieve the status of a socket:

How to Use the socket_get_status() Function?

php
<?php

$socket = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$socket) {
    die("Error: $errstr ($errno)");
}

$status = socket_get_status($socket);
if ($status["eof"]) {
    echo "Socket closed";
} else {
    echo "Socket open";
}

fclose($socket);
?>

In this example, we use fsockopen() to create a stream resource, then verify it was created successfully before checking its status. We check if the eof field is true, which indicates the stream has reached the end, or false, which indicates it is still active.

The function returns an associative array with the following keys:

  • wrappable: Boolean indicating if the stream can be wrapped.
  • stream_type: String describing the stream type (e.g., tcp_socket).
  • mode: String indicating the access mode (e.g., r, w).
  • unread_bytes: Integer representing the number of unread bytes in the stream buffer.
  • timed_out: Boolean indicating if the stream timed out.
  • eof: Boolean indicating if the end of the stream has been reached.

Conclusion

The socket_get_status() function is a useful tool for checking the status of a socket in your PHP web application. By understanding the syntax, return values, and proper resource types, you can easily monitor socket states to ensure reliable network communication. We hope this article has been informative and useful in understanding the socket_get_status() function in PHP.

Practice

What is the purpose of socket_get_status() function in PHP?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.