What potential issues can arise when using fsockopen() to send HTTP requests in PHP?
One potential issue when using fsockopen() to send HTTP requests in PHP is that the connection may not be properly closed, leading to resource leaks and potential performance issues. To solve this problem, it is important to explicitly close the connection using fclose() after sending the request and reading the response.
$fp = fsockopen($host, $port, $errno, $errstr, $timeout);
if (!$fp) {
echo "Error: $errstr ($errno)\n";
} else {
// Send HTTP request
fwrite($fp, "GET / HTTP/1.1\r\n");
fwrite($fp, "Host: $host\r\n");
fwrite($fp, "Connection: close\r\n\r\n");
// Read response
while (!feof($fp)) {
echo fgets($fp, 128);
}
// Close connection
fclose($fp);
}