PHP comes preloaded with a good socket handling function set. Using fsockopen to make HTTP connections however is in most cases obsoleted as the php-curl and set of curl functions covers more HTTP related stuff than you could ever need! fsockopen is available in both PHP4 and PHP5
Regardless, to cover the most basic usage of fsockopen, to establish a TCP connection to “mailserver” on port 110 (POP3):
if (!$resource) {
//fsockopen failed
echo “No connection established. Error: ” . $errorstr . “[" . $errorno . "]<br />\n”;
} else {
//fsockopen succeeded
//while there is data to read from $resource…
while (!feof($resource)) {
//read the data, 128 bytes at a time and echo it out
echo fgets($fp, 128);
}
//no more data to read, close the resource
fclose($resource);
}
?>
The above is a commented version of the basics of fsockopen for TCP, I’ll publish a crude POP3 client using PHP in my next post.
To connect using UDP, prefix your hostname with “udp://”, i.e. “udp://mailserver”.
If your PHP supports crypto, you may also use ssl:// and tls://
Tags: fsockopen, http, PHP, php4, php5, SSL, tcp, tls, udp
[...] my last post I described the basics of PHP’s fsockopen. This script is far from perfect and only contains [...]