Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP Network fsockopen() Function



The PHP Network fsockopen() function is used to connect to a server or resource, such as a website or a Unix socket. It can be used to establish a socket connection with a variety of protocols, like TCP, SSL, and TLS. It accepts hostnames (server addresses), port numbers and optional parameters such as timeouts, error codes, and messages.

The function returns a file pointer, allowing you to read from and write to the connection using file operations like fgets() and fwrite(). If the connection fails, it returns false. This function is useful for dealing with network connectivity and custom server connections.

Syntax

Below is the syntax of the PHP Network fsockopen() function −

resource fsockopen(
    string $hostname,
    int $port = -1,
    int &$error_code = null,
    string &$error_message = null,
    ?float $timeout = null
)

Parameters

Here are the parameters of the fsockopen() function −

  • $hostname − (Required) It is the address of the server or resource to connect to.

  • $port − (Required) It is the port number to connect to.

  • $error_code − (Required) It is a variable to store the error number if the connection fails.

  • $error_message − (Required) It is a variable to store a detailed error message if the connection fails.

  • $timeout − (Optional) It is the time in seconds to wait before giving up on the connection.

Return Value

The fsockopen() function returns a usable connection resource or FALSE if the connection cannot be established.

PHP Version

First introduced in core PHP 4, the fsockopen() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

First we will show you the basic example of the PHP Network fsockopen() function. This program basically creates a basic TCP connection to a web server using port 80 (HTTP). Using a simple HTTP GET request, it gets the homepage and displays the outcome.

<?php
   // Connect to example.com on port 80
   $socket = fsockopen("example.com", 80, $error_code, $error_message, 5);

   if ($socket) {
      // Send HTTP GET request
      fwrite($socket, "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: Close\r\n\r\n");

      // Read and display response
      while (!feof($socket)) {
         echo fgets($socket, 1024);
      }

      fclose($socket); // Close connection
   } else {
      echo "Connection failed: $error_message ($error_code)";
   }
?>

Output

Here is the outcome of the following code −

HTTP/1.1 200 OK
Accept-Ranges: bytes
Age: 444932
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Thu, 09 Jan 2025 08:34:06 GMT
Etag: "3147526947+gzip"
Expires: Thu, 16 Jan 2025 08:34:06 GMT
Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT
Server: ECAcc (nyd/D182)
Vary: Accept-Encoding
X-Cache: HIT
Content-Length: 1256
Connection: close

<!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
        
    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 2em;
        background-color: #fdfdff;
        border-radius: 0.5em;
        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
    }
    a:link, a:visited {
        color: #38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        div {
            margin: 0 auto;
            width: auto;
        }
    }
    </style>    
</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>

Example 2

In the below PHP code we will use the fsockopen() function and try to secure SSL connection. So it connects to a server with the help of SSL on port 443 (HTTPS). It gets and displays the website's homepage securely.

<?php
   // Connect to example.com using SSL on port 443
   $socket = fsockopen("ssl://example.com", 443, $error_code, $error_message, 5);

   if ($socket) {
      // Send HTTPS GET request
      fwrite($socket, "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: Close\r\n\r\n");

      // Read and display response
      while (!feof($socket)) {
         echo fgets($socket, 1024);
      }

      fclose($socket); // Close connection
   } else {
      echo "Connection failed: $error_message ($error_code)";
   }
?> 

Output

This will generate the below output −

HTTP/1.1 200 OK
Age: 568541
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Thu, 09 Jan 2025 08:38:06 GMT
Etag: "3147526947+ident"
Expires: Thu, 16 Jan 2025 08:38:06 GMT
Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT
Server: ECAcc (nyd/D134)
Vary: Accept-Encoding
X-Cache: HIT
Content-Length: 1256
Connection: close
php_function_reference.htm
Advertisements