fsockopen()
fsockopen() — Open Internet or Unix domain socket connection.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, 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 socket connection to the resource specified by hostname.
Signature
fsockopen(string $hostname, int $port = -1, int &$error_code = null, string &$error_message = null, ?float $timeout = null): resource|false
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $hostname | string | If OpenSSL support is installed, you may prefix the hostname with either ssl:// or tls:// to use an SSL or TLS client connection over TCP/IP to connect to the remote host. |
| $port | int | The port number. This can be omitted and skipped with -1 for transports that do not use ports, such as unix://. |
| &$error_code | int | If provided, holds the system level error number that occurred in the system-level connect() call. |
| &$error_message | string | The error message as a string. |
| $timeout | ?float | The connection timeout, in seconds. When null, the default_socket_timeout php.ini setting is used. |
Return value
fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets(), fgetss(), fwrite(), fclose(), and feof()). If the call fails, it will return false
Example
A runnable snippet:
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30); 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); }
Changelog
| Version | Change |
|---|---|
| 8.0.0 | timeout is nullable now. |
See also
pfsockopen(), stream_socket_client(), stream_set_blocking(), stream_set_timeout(), fgets(), fwrite(), fclose(), feof()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page fsockopen() (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.