PHP fsockopen() Function: Everything You Need to Know
As a PHP developer, you may need to establish a network connection and communicate with another server using the TCP/IP protocol. In such scenarios, the PHP
As a PHP developer, you may need to establish a network connection and communicate with another server using the TCP/IP protocol. The fsockopen() fsockopen() fsockopen() stream_socket_client() or cURL instead. This article explains the legacy function for reference and migration purposes.
What is the fsockopen() Function?
The fsockopen() function opens a TCP/IP network connection to a specified host and port, allowing data to be sent and received via file pointers.
How to Use the fsockopen() Function
Using the fsockopen() function is straightforward. Here is the syntax:
PHP Syntax
fsockopen($hostname, $port, &$errno, &$errstr, $timeout);The function accepts five parameters:
$hostname: The host name or IP address of the server.$port: The port number to connect to.&$errno: A variable that stores the error number, if any.&$errstr: A variable that stores the error message, if any.$timeoutfsockopen()default_socket_timeoutstream_socket_client()inisetting if omitted.
Note: For secure connections, prefix the hostname with
ssl://tls://tls://example.com).
Here is an example of how to use the fsockopen() function to establish a network connection with a server and send/receive data:
Example Usage
<?php
$host = "example.com";
$port = 80;
$timeout = 30;
$fp = fsockopen($host, $port, $errno, $errstr, $timeout);
if (!$fp) {
echo "Error: $errstr ($errno)<br/>";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: $host\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}In this example, we use the fsockopen() fsockopen() example.com fgets() function.
Note: For HTTPS requests, use
tls://$hostvariable.
Conclusion
While fsockopen() fsockopen() stream_socket_client() or cURL for new projects. This reference remains useful for maintaining legacy codebases.
Practice
What does the fsockopen function in PHP do?