Backend Development 4 min read

Using PHP pfsockopen() for Persistent Socket Connections

This article explains the PHP pfsockopen() function, its parameters, return values, and provides a complete example demonstrating how to establish a persistent SSL socket, send an HTTP POST request, and read the response using low‑level socket operations.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP pfsockopen() for Persistent Socket Connections

pfsockopen() opens a persistent network or Unix socket connection, behaving like fsockopen() but keeping the connection alive after the script finishes, effectively providing a long‑lived socket.

Parameter description

hostname : The remote host name; prepend ssl:// or tls:// for encrypted connections.

port : Port number; use -1 for protocols without a port (e.g., unix:// ).

errno : Variable that receives the system‑level error number if the connection fails.

errstr : Variable that receives the error message string.

timeout : Connection timeout in seconds (default taken from default_socket_timeout ).

The function returns a file handle that can be used with standard file functions such as fgets() , fwrite() , fclose() , etc.; on failure it returns FALSE .

Example

<?php
$host = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$host = 'www.example.com';
$service_uri = '/cgi-bin/processACT';
$vars = 'code=22&act=TEST';

$header = "Host: $host\r\n";
$header .= "User-Agent: PHP Script\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($vars) . "\r\n";
$header .= "Connection: close\r\n\r\n";

$fp = pfsockopen("ssl://" . $host, 443, $errno, $errstr);
if (!$fp) {
    echo "$errstr ($errno)
\n";
    echo $fp;
} else {
    fputs($fp, "POST $service_uri HTTP/1.1\r\n");
    fputs($fp, $header . $vars);
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

The script builds the request headers, opens a secure socket to the target host, sends a POST request with the defined variables, reads the response line by line, and finally closes the connection.

PHPNetwork ProgrammingSocketPersistent Connectionpfsockopen
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

login 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.