PHP Function Reference

PHP stream_socket_client() Function



The PHP stream_socket_client() function opens Internet or Unix domain socket connection.

The function initiates a stream or datagram connection to the destination specified by remote_socket. The type of socket created is determined by the transport specified using standard URL formatting: transport://target. For Internet Domain sockets (AF_INET) such as TCP and UDP and the target portion of the remote_socket parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem.

By default, the socket is opened in blocking mode. It can be switched to non-blocking mode by using stream_set_blocking().

Syntax

stream_socket_client(remote_socket, errno, errstr, 
                     timeout, flags, context)

Parameters

remote_socket Required. Specify address to the socket to connect to.
errno Optional. Will be set to the system level error number if connection fails.
errstr Optional. Will be set to the system level error message if the connection fails.
timeout Optional. Specify the connection timeout, in seconds. When null, the default_socket_timeout of php.ini setting is used.
flags Optional. Specify Bitmask field which can be set to any combination of connection flags. It can be the following:
  • STREAM_CLIENT_CONNECT (default)
  • STREAM_CLIENT_ASYNC_CONNECT
  • STREAM_CLIENT_PERSISTENT
context Optional. Specify the context resource created with stream_context_create() function.

Return Value

Returns a file pointer which can be used together with the other file functions, such as fgets(), fgetss(), fwrite(), fclose(), and feof(), or false on failure.

Exceptions

On failure the errno and errstr arguments will be populated with the actual system level error that occurred in the system-level connect() call. If the value returned in errno is 0 and the function returned false, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Please note that the errno and errstr arguments will always be passed by reference.

Example: stream_socket_client() example

The example below shows the usage of stream_socket_client() function.

<?php
$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 20);
if (!$fp) {
  echo "$errstr ($errno)<br>\n";
} else {
  $out = "GET / HTTP/1.1\r\n";
  $out .= "Host: www.example.com\r\n";
  $out .= "Connection: Close\r\n\r\n";
  fwrite($fp, $out);
  while (!feof($fp)) {
    echo fgets($fp, 128);
  }
  fclose($fp);
}
?>

The output of the above code will be similar to:

HTTP/1.1 200 OK
Age: 256541
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Mon, 08 Nov 2021 06:35:57 GMT
Etag: "3147526947+gzip+ident"
Expires: Mon, 15 Nov 2021 06:35:57 GMT
Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT
Server: ECS (dna/63A8)
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: using UDP connection

In the example below, the stream_socket_client() function is used with UDP connection.

<?php
$fp = stream_socket_client("udp://127.0.0.1:13", $errno, $errstr);
if (!$fp) {
  echo "ERROR: $errno - $errstr<br>\n";
} else {
  fwrite($fp, "\n");
  echo fread($fp, 26);
  fclose($fp);
}
?>

Note: When specifying a numerical IPv6 address (e.g. fe80::1), the IP must be enclosed in square brackets, for example - tcp://[fe80::1]:80.

❮ PHP Streams Reference