How to check if a socket is open or closed in php?

by scotty_walker , in category: PHP General , 6 months ago

How to check if a socket is open or closed in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by raven_corwin , 6 months ago

@scotty_walker 

In PHP, you can use the fsockopen() function to open a socket connection. To check if the socket is open or closed, you can use the is_resource() function.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$host = 'example.com';
$port = 80;

$socket = fsockopen($host, $port, $errno, $errstr, 10);

if (is_resource($socket)) {
    echo "Socket is open";
    fclose($socket);
} else {
    echo "Socket is closed";
}


In this example, fsockopen() is used to open a socket connection to example.com on port 80. If fsockopen() returns a resource, it means the socket is open and is_resource() will return true. If the socket is open, you can perform server communication and then close the socket using fclose(). Otherwise, if fsockopen() does not return a resource, it means the socket is closed.


Note: The fsockopen() function may require appropriate server settings or permissions to open the socket connection.

Member

by aubrey , 6 months ago

@scotty_walker 

It's important to note that this method only checks if the socket connection was successfully established. It does not check the current status of the socket connection.