When there is a concept that somehow links hardware to software things fall into place better for me, personally, with understanding. For me, this is because hardware is that interesting thing out there that is more unknown, and so much more mysterious, to me, than software.
One conduit to the hardware world, for me, then, is the concept of a port, which is, to quote Wikipedia …
In computer networking, a port is an endpoint of communication in an operating system.
… linking the software, via networking principals, to hardware. So if there is a way to find an underlying operating system PID (process identifier) associated with a designated port (number), then my ears prick up.
What initially puts you off such an endeavour is that there is no way the Windows command line would have the same command as the Linux or unix command line to do this? Is there? Well, actually, there almost is, with netstat -an but the lack of an “o” switch in Linux (or unix) is the reason this cannot be used … as “o” supplies a PID column to the result set. However Linux has alternatives with the lsof command, so the project will be undertaken by PHP using its ever useful exec method to …
- Linux (or unix) …
lsof -i:[portNumber]
- Windows …
netstat -ano | findstr ":[portNumber] PID"
… and so, that brings us to the question of how the PHP tells what operating system underlies it. We make use of this link‘s great advice (to make use of the pre-defined constant PHP_OS) to come up with (where $gp contains port number of interest) the PHP code snippet …
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
// echo 'This is a server using Windows!';
exec('netstat -ano | find ":' . $gp . ' PID" > ppi.txt');
} else {
// echo 'This is a server not using Windows!';
exec('sh -c "lsof -i:' . $gp . '" > ppi.txt');
}
To look at the PHP source code, try this port_process_info.php or try a live run link. We worked with a Windows local Apache web server called EasyPHP ( for URL http://localhost:8887/port_process_info.php ) and a Mac OS X local Apache web server called MAMP ( for URL http://localhost:8888/port_process_info.php ) to test the PHP code today.
Stop Press
The last MAMP for Windows install we did, in 2021, ended up with HTTP://localhost/ being the resultant local Apache/MySql/PHP’s $_SERVER[‘DOCUMENT_ROOT’] C:\MAMP\ disk directory URL (part).
If this was interesting you may be interested in this too.
14 Responses to PHP Port Process Primer Tutorial