I want to use PHP to check if anything is listening to localhost:81
, to ensure that is available for a PHP built in server to run on.
i.e. I want to check if the following would run properly php -S localhost:81
.
Now if something is already listening on port 81 (e.g. Apache), this will of course cause problems.
I read the following: How can I check if ports 465 and 587 are open with PHP? and the solution did not seem to work.
i.e.:
$fp = fsockopen('localhost', '81', $errno, $errstr, 5);
var_dump($fp); // returns false
if (!$fp) {
// port is closed or blocked
echo "CLOSED!";
return false;
} else {
// port is open and available
echo "OPEN!";
fclose($fp);
return true;
}
Unfortunately the above keeps returning "CLOSED!" even though its not.
I also get the following error message:
PHP Warning: fsockopen(): unable to connect to localhost:81 (Connection refused)
How do I solve my problem?
Is there any alternatives?
You should actually check to see if fsockopen()
has returned a resource
:
$connection = @fsockopen('localhost', '81');
if (is_resource($connection))
{
echo 'Open!';
fclose($connection);
return true;
}
else
{
echo 'Closed / not responding. :(';
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With