PHP Open Port Check Script

Written by A.Jesin Saturday, 16 July 2011 11:17

A quick tutorial on how to check for open ports using PHP. This function fsockopen() is used in the Open Port Check Tool in this blog. You can check whether a certain port is open on a specified IP address or hostname. Before reading take note that most FREE web hosting providers disable fsockopen() function as a security measure so first check whether the function can be used. Another thing to take note is that if fsockopen is unable to connect to a port it doesn’t necessarily mean that port is closed on the remote host, your server in which the script is running might also have block the OUTBOUND connection to that port.

Did you land up in this page searching for the Open Port Check Tool ?

Lets go straight to the syntax of fsockopen(). The complete syntax as shown in the official PHP documentation is

resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )

But for this PHP open port check tutorial we’ll use only the first two parameters

fsockopen(hostname,portno)

The fsockopen() function returns a resource identifier if the connection is successful or the Boolean value FALSE if connection couldn’t be established. We’ll use the if else loop to check this out.

<?php
if(fsockopen("jesin.tk",80))
{
print "I can see port 80";
}
else
{
print "I cannot see port 80";
}
?>

Y0u can also replace hostnames with IP addresses in the fsockopen() function. An important thing is that when the script is unable to open a connection to the specified port it may also issue a PHP Warning message “[13-Jul-2011 10:53:09] PHP Warning:  fsockopen() [<a href='function.fsockopen'>function.fsockopen</a>]: unable to connect to hostname:80 (Connection timed out) in /path/to/script.php(42) : eval()’d code on line 20″

To prevent PHP from displaying such errors at runtime read Disabling PHP Display Errors

Also read:

Enjoyed reading this article, subscribe to stay up-to-date with more such articles

Leave a Reply




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>