How to Use fsockopen in PHP for Network Connections

This article provides a straightforward guide on how to initiate a network connection using the fsockopen() function in PHP. You will learn the basic syntax of the function, how to handle connection errors, and how to write and read data through the established socket connection.

Understanding fsockopen() in PHP

The fsockopen() function is a built-in PHP tool used to open an Internet or Unix domain socket connection. Unlike higher-level tools like cURL, fsockopen() operates at a lower network level, allowing you to establish direct TCP or UDP connections to a remote server. This is highly useful for custom protocols, port checking, or sending raw HTTP requests.

Syntax

The basic syntax of fsockopen() is as follows:

resource fsockopen ( 
    string $hostname, 
    int $port = -1, 
    int &$errno = null, 
    string &$errstr = null, 
    float $timeout = null 
)

Step-by-Step Implementation

To successfully initiate a connection, write to the socket, read the response, and close the connection, follow these steps:

1. Initiate the Connection

Use fsockopen() to establish the connection and verify that the socket resource was successfully created.

$hostname = 'example.com';
$port = 80;
$timeout = 30;

$connection = @fsockopen($hostname, $port, $errno, $errstr, $timeout);

if (!$connection) {
    echo "Connection failed: $errstr ($errno)";
    exit;
}

(Note: The @ operator suppresses default PHP PHP warning messages, allowing you to handle errors gracefully using $errno and $errstr.)

2. Send Data (Write to Socket)

Once the connection is open, you can send data to the server using the fwrite() function. In this example, we send a standard HTTP GET request.

$request = "GET / HTTP/1.1\r\n";
$request .= "Host: $hostname\r\n";
$request .= "Connection: Close\r\n\r\n";

fwrite($connection, $request);

3. Retrieve Data (Read from Socket)

Use a while loop combined with fgets() to read the server’s response line-by-line until the end of the file (EOF) is reached.

$response = '';
while (!feof($connection)) {
    $response .= fgets($connection, 128);
}

4. Close the Connection

Always close the network socket using fclose() once your data transfer is complete to free up system resources.

fclose($connection);

// Output the response
echo $response;

Connecting via SSL/TLS (HTTPS)

To establish a secure connection using fsockopen(), prepending the transport protocol ssl:// or tls:// to the hostname is required, and the port must be updated to 443.

$secure_connection = @fsockopen('ssl://example.com', 443, $errno, $errstr, 30);