PHP fsockopen() Function: Usage, Parameters, and Examples
fsockopen() opens a network or Unix socket connection in PHP, with detailed parameter explanations, default behavior, error handling, and two practical code examples demonstrating HTTP GET requests and UDP socket usage, along with notes on blocking mode and related functions.
The PHP fsockopen() function opens a network or Unix socket connection, returning a file handle that can be used with standard file functions.
Signature: resource fsockopen(string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout")]]]]) .
It initializes a socket to the specified host; if OpenSSL is available, the hostname may be prefixed with ssl:// or tls:// . The default mode is blocking, but stream_set_blocking() can change it. stream_socket_client() offers similar functionality with more options.
Parameters:
hostname : target host, optionally prefixed with ssl:// or tls:// for encrypted connections.
port : port number; -1 indicates no port (e.g., unix:// ).
errno : optional variable that receives the system error number if the connection fails before the socket is created.
errstr : optional variable that receives the error message string.
timeout : optional timeout in seconds, defaulting to the default_socket_timeout ini setting.
Return value: on success, a file handle resource; on failure, FALSE .
Example 1 – HTTP GET request
\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);
}
?>Example 2 – UDP socket
\n";
} else {
fwrite($fp, "\n");
echo fread($fp, 26);
fclose($fp);
}
?>Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.