The title pretty much sums it up:
How can I get the server IP address using PHP from the CLI?
Using PHP's CLI, $_SERVER does not contain the server's IP address, so the obvious solution is out of the question.
Thanks!
This bit of code will get the IP address of the interface "eth0" on a *nix system.
// get the local hosts ip address
$hostsipaddress = str_replace("\n","",shell_exec("ifconfig eth0 | grep 'inet addr' | awk -F':' {'print $2'} | awk -F' ' {'print $1'}"));
The thing is, when running PHP on the CLI, there's no network activity involved whatsoever, hence no IP addresses. What you need to define first and foremost is, what IP you want to get.
The IP of the client running the script?
Not possible, since there is no "client".
The local IP of a network interface?
Run some system utility like ifconfig
, but you may get more than one IP if the server has more than one network interface.
The IP of a domain, which may or may not correspond to the server you're running on?
Use gethostbyname()
, but you need to know which domain you want to query for.
The public facing IP of the network/server you're on?
You'll need to use an external service like www.whatsmyip.org (note that they don't like this) which will tell you what IP your request came from. Whether this address corresponds to anything useful is a different topic.
The bottom line is, if you're interested in $_SERVER['REMOTE_ADDR']
or $_SERVER['SERVER_ADDR']
, it simply does not apply to a CLI-run script.
At that point PHP doesnt know the IP unless you pass_thru() or exec() a shell utility like ifconfig. I recommend you reconsider using CLI for this purpose.
Think of PHP CLI as "Basic interpreter" in this case.
Since I found this while searching for it here's the function I quickly put together. Could use better error checking and such but it does the job. Perhaps others will find it useful:
function get_external_ip() {
$ch = curl_init("http://icanhazip.com/");
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
if ($result === FALSE) {
return "ERROR";
} else {
return trim($result);
}
}
I'm assuming you're calling a PHP CLI script while handling a connection via PHP. If this is the case, you could pass the value of $_SERVER to the CLI script as a command line argument.
although vrillusions post is great there is a better method to doing this because of two reasons (a) the source page may not always stay as just the ip no buts (they recently modified the index to have html) now while we could just point to the /s for a bot it would be much easier to use regex to match the ip on the page and pull it out. Here is the function how I envisioned it
function RemoteIP($source = 'http://canihazip.com'){
$c = file_get_contents($source);
$ip = false;
if(preg_match('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/', $c, $m)){
$ip = $m[1];
}
return $ip;
}
print RemoteIP().PHP_EOL;