HomePHP Page 4 - Adding Methods to the Query Processor in PHP
More methods ahead: defining the "Netstat()" and "getMXRecordsWin()" methods - PHP
Over this second article in a series covering network programming in PHP, you will learn how to run popular Windows network monitoring utilities, such as the “ping,” “netstat” and “ipconfig” programs, by adding some new methods to the “QueryProcessor” class introduced in the previous article.
As you've seen in the previous section, running commands on Windows-based systems can be quite useful for executing some well-know utilities. That's exactly the case with the "netstat" command, which can be used basically for checking the status of your different network connections. That said, here is the class method that runs that command on a Windows-based computer:
// execute 'netstat' command on Windows systems public function Netstat(){ $output='Running netstat command...Please wait.<br />'; exec('netstat',$lines); foreach($lines as $line){ $output.=$line.'<br />'; } return $output; }
As you can appreciate, this new method also uses the PHP "exec()" function, in order to execute the "netstat" command. As with the previous cases, after running this command, the output is processed as an array, which is traversed by a regular "foreach" loop, and finally returned to calling code.
Since the above method is very easy to grasp, I won't spend a long time explaining its logic. I'll move forward and show you the last method (at least for this article) that uses the PHP "exec()" function for running Windows commands. What I referencing here is the "getMXRecordsWin()" method, which comes in handy for getting the list of MX records that correspond to a given Internet host. The source code of this method is listed below:
// get MX records on Windows systems public function getMXRecordsWin(){ $output='Retrieving MX Records...please wait.<br />'; exec("nslookup -type=mx $this->host",$mxhosts); foreach($mxhosts as $mxhost){ $output.=$mxhost.'<br />'; } return $output; }
In this case, the method shown above utilizes the "exec()" function for running the "nslookup" utility in conjunction with the "type" flag, in order to obtain (when applicable) the list of MX records corresponding to an Internet host. As you'll recall, this host is passed to the constructor and assigned as a class property, thus obtaining the respective MX records for it is really a no-brainer process.
All right, at this stage I added some valuable networking methods to the "QueryProcessor" class, in order to expand its existing capabilities. Therefore, it's convenient that you see how the class looks now, after attaching the new methods. To see the full source of the class, please jump into the next section.