msgbartop
Adam Palmer MBCS CITP, Linux, PHP Programmer, MySQL Developer, Embedded Hardware, Security Consultant
Did my blog help you? Please link to me!
  dns test
 
RSS Feed
msgbarbottom

15 Jan 09 PHP – fsockopen, TCP and UDP

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):

<?php
//Attempt to establish a connection to “mailserver” on port 110. On error, place the error number into $errorno, and a string response to $errorstr. Timeout after 10 seconds.
$resource = fsockopen(”mailserver”, 110, $errorno, $errorstr, 10);

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: , , , , , , , ,



Reader's Comments

  1. |

    [...] my last post I described the basics of PHP’s fsockopen. This script is far from perfect and only contains [...]



Leave a Comment