stream_socket_client()

stream_socket_client() — Open Internet or Unix domain socket connection.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Initiates a stream or datagram connection to the destination specified by address. 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, the target portion of the address 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.

Signature

stream_socket_client(string $address, int &$error_code = null, string &$error_message = null, ?float $timeout = null, int $flags = STREAM_CLIENT_CONNECT, ?resource $context = null): resource|false

Parameters

ParameterTypeWhat it takes
$addressstringAddress to the socket to connect to.
&$error_codeintWill be set to the system level error number if connection fails.
&$error_messagestringWill be set to the system level error message if the connection fails.
$timeout?floatNumber of seconds until the connect() system call should timeout. By default, default_socket_timeout is used. Note: This parameter only applies when not making asynchronous connection attempts. Note: To set a timeout for reading/writing data over the socket, use the stream_set_timeout(), as the timeout only applies while making connecting the socket.
$flagsintBitmask field which may be set to any combination of connection flags. Currently the select of connection flags is limited to STREAM_CLIENT_CONNECT (default), STREAM_CLIENT_ASYNC_CONNECT and STREAM_CLIENT_PERSISTENT.
$context?resourceA valid context resource created with stream_context_create().

Return value

On success a stream resource is returned which may be used together with the other file functions (such as fgets(), fgetss(), fwrite(), fclose(), and feof()), false on failure.

Example

A runnable snippet:

$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)<br />\n"; } else { fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n"); while (!feof($fp)) { echo fgets($fp, 1024); } fclose($fp); }

Changelog

VersionChange
8.0.0timeout and context are now nullable.

See also

stream_socket_server(), stream_set_blocking(), stream_set_timeout(), stream_select(), fgets(), fwrite(), fclose(), feof()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page stream_socket_client() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.