Full Disclosure: There's a similar question here.
Is there any way I can test if a particular port is open and forwarded properly using PHP? Specifically, how do I go about using a socket to connect to a given user with a given port?
An Example of this is in the 'Custom Port Test' section of WhatsMyIP.org/ports.