Using PHP’s fsockopen() Function to Open Network Connections
This article explains the PHP fsockopen() function, detailing its syntax, parameters, return values, and provides a complete example that demonstrates opening a TCP connection, sending an HTTP request, handling errors, and reading the response, including notes on SSL connections.
Function Syntax
resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]])
Function Parameters
$hostname : The target host address, either an IP or domain name.
$port : Optional port number; default -1 uses the default port.
&$errno : Variable that receives an error code if the connection fails.
&$errstr : Variable that receives an error message if the connection fails.
$timeout : Optional timeout in seconds; defaults to the value of ini_get("default_socket_timeout") .
Return Value
On success, returns a resource handle containing the connection information, which can be used by other functions. On failure, returns false .
Usage Example
The following PHP script opens a connection to www.example.com on port 80, sends a simple HTTP GET request, reads the response, and closes the connection.
<code><?php
// Define target server and port
$hostname = 'www.example.com';
$port = 80;
// Open a network connection
$fp = fsockopen($hostname, $port, $errno, $errstr, 10);
// Output error and exit if connection fails
if (!$fp) {
echo "Connection failed: $errno - $errstr";
exit;
}
// Send HTTP request headers
$request = "GET / HTTP/1.1\r\n";
$request .= "Host: $hostname\r\n";
$request .= "Connection: close\r\n\r\n";
fwrite($fp, $request);
// Read and output the response
while (!feof($fp)) {
echo fgets($fp, 128);
}
// Close the connection
fclose($fp);
?>
</code>The script demonstrates creating a socket, sending request headers, reading the response with fgets() , and handling errors.
To open an SSL‑encrypted connection, prepend ssl:// to the hostname and use the appropriate port (typically 443).
Overall, fsockopen() is a powerful PHP tool for network communication, allowing developers to connect to remote servers, send requests, and process responses.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.