Master PHP’s fsockopen(): Open Network Connections & Fetch Remote Content
This guide explains PHP’s fsockopen() function, detailing its syntax, parameters, return values, and a complete example that opens a TCP connection, sends an HTTP GET request, reads the response, and notes how to use SSL for secure connections.
Function Overview
The fsockopen() function in PHP opens a network connection using the TCP/IP protocol, allowing communication with remote servers to send requests and receive responses.
Syntax
resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )Parameters
$hostname: Target host address (IP or domain name). $port: Optional port number; default -1 uses the service’s default port. &$errno: Variable that receives an error code on failure. &$errstr: Variable that receives an error message on failure. $timeout: Optional timeout in seconds; defaults to the value of ini_get("default_socket_timeout").
Return Value
On success, returns a resource handle containing connection information, which can be used by other functions. On failure, returns false.
Usage Example
The following script demonstrates how to use fsockopen() to connect to a remote web server, send a simple HTTP GET request, and output the response.
<?php
// Define target server and port
$hostname = 'www.example.com';
$port = 80;
// Open a network connection
$fp = fsockopen($hostname, $port, $errno, $errstr, 10);
if (!$fp) {
echo "Connection failed: $errno - $errstr";
exit;
}
// Build HTTP request headers
$request = "GET / HTTP/1.1
";
$request .= "Host: $hostname
";
$request .= "Connection: close
";
// Send request
fwrite($fp, $request);
// Read and output response
while (!feof($fp)) {
echo fgets($fp, 128);
}
// Close connection
fclose($fp);
?>This code creates a connection to www.example.com on port 80, sends an HTTP GET request, and continuously reads the server’s response until the connection closes.
SSL Connections
To open an SSL‑encrypted connection, prefix the hostname with ssl:// and use the appropriate port (typically 443).
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
