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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP fsockopen() Function: Usage, Parameters, and Examples

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

<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />
";
} else {
    $out = "GET / HTTP/1.1
";
    $out .= "Host: www.example.com
";
    $out .= "Connection: Close

";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

Example 2 – UDP socket

<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br />
";
} else {
    fwrite($fp, "
");
    echo fread($fp, 26);
    fclose($fp);
}
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPNetwork programmingSocketfsockopen
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.