This article mainly introduces PHP cross-platform Server IP address acquisition User-Defined Function sharing. In this article, the function will select different commands based on the system type to obtain the Server IP address. For more information, see
This article mainly introduces PHP cross-platform Server IP address acquisition User-Defined Function sharing. In this article, the function will select different commands based on the system type to obtain the Server IP address. For more information, see
Recently, a log mechanism needs to be improved to monitor the script execution status of machines from different servers. This function is compatible with windows, Linux, and web and command line modes.
Write the following function to meet the above requirements:
The Code is as follows:
Function getServerAddr (){
// Run the web app
If (isset ($ _ SERVER ["SERVER_ADDR"]) {
Return $ _ SERVER ["SERVER_ADDR"];
} Else {// Running CLI
If (stristr (PHP_ OS, 'win ')){
// A hacky Method for windows Servers
Exec ("ipconfig/all", $ catch );
Foreach ($ catch as $ line ){
$ New_catch [] = iconv ("gbk", "UTF-8", $ line). "\ n ";
}
Foreach ($ new_catch as $ new_line ){
If (preg_match ('/IPv4 address/', $ new_line) {// Chinese System
List ($ t, $ ip) = explode (':', $ new_line );
$ Ip = trim ($ ip );
Preg_match ('/((? :(? : 25 [0-5] | 2 [0-4] \ d | (1 \ d {2}) | ([1-9]? \ D) \.) {3 }(? : 25 [0-5] | 2 [0-4] \ d | (1 \ d {2}) | ([1-9]? \ D)/', $ ip, $ match );
Return $ match [1];
}
}
} Else {
$ Ifconfig = shell_exec ('/sbin/ifconfig eth0 ′);
Preg_match ('/addr :( [\ d \.] +)/', $ ifconfig, $ match );
Return $ match [1];
}
}
}
$ Ip = getServerAddr ();
Print $ ip;