- How can I get the server IP address using PHP from the CLI?
- 6 Answers 6
- Как получить IP через PHP для сервера и пользователя
- Как в PHP узнать IP сервера
- Как в PHP получить IP посетителя
- Как в PHP определить IP пользователя, использующего прокси
- gethostbyname
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 31 notes
How can I get the server IP address using PHP from the CLI?
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!
6 Answers 6
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':' | awk -F' ' "));
Keep in mind that would fail if the device is connected over wi-fi. stackoverflow.com/a/1814633/572660
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\.\d\.\d\.\d)/', $c, $m)) < $ip = $m[1]; >return $ip; > print RemoteIP().PHP_EOL;
This question is in a collective: a subcommunity defined by tags with relevant content and experts.
Как получить IP через PHP для сервера и пользователя
Доброго времени суток 🙂
На практике часто возникает необходимость узнать IP в PHP скрипте сайта. Причём, это может быть как IP адрес сервера, так и посетителя, производящего действия на вашем ресурсе.
Причём, последний иногда может пользоваться сайтом не напрямую, а по каким-то причинам подключаясь к нему через прокси сервер. Этот случай усложняет жизнь тем, что для подключения используется изменённый IP адрес.
Но, к счастью, в PHP получить IP адрес как клиента, так и самого сайта в этом случае более, чем реально. Причём, для этого не потребуются никакие специальные библиотеки и средства движков сайтов. Всё необходимое уже есть в самом PHP «на борту».
Нам осталось только пользоваться 🙂
Как в PHP узнать IP сервера
Вся необходимая информация об IP сервера, да и пользователя тоже, в PHP доступна через суперглобальный массив $_SERVER. Однако, помимо перечисленных данных он содержит ещё много различной информации.
В этой ситуации отыскать нужное становится непростой задачей, для решения которой нужно знать назначение переменных массива.
В частности, для того, чтобы в PHP определить IP адрес сервера, в коде нужно прописать следующую конструкцию:
Данный PHP код позволит вам вывести на экран IP адрес сервера, на котором он запускается. Это же значение будет и IP адресом сайта, если он вам где-нибудь понадобится.
Как в PHP получить IP посетителя
Для определения в PHP IP пользователя, с которого он подключается к вашему сайту, мы воспользуемся тем же массивом $_SERVER. В данном случае нас будет интересовать переменная REMOTE_ADDR, содержимое которой можно вывести на экран привычным способом:
Однако, в случаях использования клиентом прокси соединений, т.е. когда при подключении трафик идёт через сторонний прокси сервер, данная переменная будет содержать IP адрес не посетителя, а прокси сервера.
Чтобы узнать в PHP IP адрес посетителя в данном случае, нужно воспользоваться другим способом.
Как в PHP определить IP пользователя, использующего прокси
Первым делом, в PHP IP посетителя при использовании прокси можно попробовать получить следующим способом:
Данный код можно найти практически во всех PHP скриптах, определяющих реальный IP посетителя. Однако, мало кто может объяснить, что хранится в данной переменной.
Если прописать данный код у себя в сайте на локальном сервере, то вы вообще получите пустое значение, т.е. данной переменной в массиве $_SERVER у вас не окажется. И это не удивительно, т.к. в HTTP_CLIENT_IP хранится глобальный IP пользователя, т.е. его адрес в сети Интернет.
И, самое главное, что на это значение не влияет прокси соединение, т.е. здесь вы найдёте реальный IP пользователя, а не его прокси сервера.
Если по каким-то причинам данная переменная будет отсутствовать в PHP $_SERVER, то можете попробовать узнать IP адрес клиента ещё и таким способом:
В данную переменную прокси сервера сами помещают реальный IP посетителя.
Таким образом, для того, чтобы в PHP узнать IP клиента гарантированно, можно использовать следующую конструкцию:
Данный скрипт выведет на экран значение переменной $ip, в которую при использовании прокси соединения будет записан глобальный IP посетителя. Если же его не будет найдено в PHP $_SERVER, то скрипт попытается узнать IP пользователя, записанный самим прокси сервером.
Если же ни одной переменной не будет присвоено значение, то с большой вероятностью можно предположить, что посетитель не использует прокси либо прокси сервер не предоставляет реальный IP посетителя. В этом случае, чтобы получить хоть какое-то значение IP, мы берём его из REMOTE_ADDR. Но, с высокой долей вероятности, это значение будет IP адресом прокси сервера (благо, что ими не пользуется абсолютно каждый клиент сайтов).
Для проверки существования значений переменных я, как видите, решил воспользоваться PHP функцией filter_var, которая фильтрует переменные с применением определённого фильтра (шаблона), которым в данном случае является FILTER_VALIDATE_IP.
В завершение хочу подытожить, что описанным выше способом, несмотря на все тщательные проверки всех возможных серверных переменных PHP, определить IP пользователя с использованием прокси всё равно не получится на 100%.
Дело в том, что IP адрес клиента предоставляют только определённый тип прокси серверов, которые называют «прозрачными». Как правило, это открытые службы.
Если же ваш пользователь решил скрыть свой реальный IP с помощью коммерческого непрозрачного прокси, то шансы узнать его реальный адрес стремятся к нулю. Благо, что процент таковых клиентов совсем невелик, так что приведённая финальная версия скрипта поможет вам в большинстве случаев.
Оставляйте свои отзывы в комментариях — что понравилось, что нет, может быть, о чём-то следовало бы рассказать поподробнее… Мне интересно любое ваше мнение.
P.S.: если вам нужен сайт либо необходимо внести правки на существующий, но для этого нет времени и желания, могу предложить свои услуги.
Более 5 лет опыта профессиональной разработки сайтов. Работа с PHP, OpenCart, WordPress, Laravel, Yii, MySQL, PostgreSQL, JavaScript, React, Angular и другими технологиями web-разработки.
Опыт разработки проектов различного уровня: лендинги, корпоративные сайты, Интернет-магазины, CRM, порталы. В том числе поддержка и разработка HighLoad проектов. Присылайте ваши заявки на email cccpblogcom@gmail.com.
И с друзьями не забудьте поделиться 😉
gethostbyname
Returns the IPv4 address of the Internet host specified by hostname .
Parameters
Return Values
Returns the IPv4 address or a string containing the unmodified hostname on failure.
Examples
Example #1 A simple gethostbyname() example
$ip = gethostbyname ( ‘www.example.com’ );
?php
See Also
- gethostbyaddr() — Get the Internet host name corresponding to a given IP address
- gethostbynamel() — Get a list of IPv4 addresses corresponding to a given Internet host name
- inet_pton() — Converts a human readable IP address to its packed in_addr representation
- inet_ntop() — Converts a packed internet address to a human readable representation
User Contributed Notes 31 notes
If you do a gethostbyname() and there is no trailing dot after a domainname that does not resolve, this domainname will ultimately be appended to the server-FQDN by nslookup.
So if you do a lookup for nonexistentdomainname.be your server may return the ip for nonexistentdomainname.be.yourhostname.com, which is the server-ip.
To avoid this behaviour, just add a trailing dot to the domainname; i.e. gethostbyname(‘nonexistentdomainname.be.’)
This function says «Returns the IPv4 address or a string containing the unmodified hostname on failure.
This isn’t entirely true, any hostname with a null byte in it will only return the characters BEFORE the null byte.
$hostname = «foo\0bar» ;
var_dump ( $hostname );
var_dump ( gethostbyname ( $hostname ));
?>
Results:
string ‘foo�bar’ (length=7)
string ‘foo’ (length=3)
Important note: You should avoid its use in production.
DNS Resolution may take from 0.5 to 4 seconds, and during this time your script is NOT being executed.
Your customers may think that the server is slow, but actually it is just waiting for the DNS resolution response.
You can use it, but if you want performance, you should avoid it, or schedule it to some CRON script.
Options for the underlying resolver functions can be supplied by using the RES_OPTIONS environmental variable. (at least under Linux, see man resolv.conf)
Set timeout and retries to 1 to have a maximum execution time of 1 second for the DNS lookup:
putenv ( ‘RES_OPTIONS=retrans:1 retry:1 timeout:1 attempts:1’ );
gethostbyname ( $something );
?>
You should also use fully qualified domain names ending in a dot. This prevents the resolver from walking though all search domains and retrying the domain with the search domain appended.
For doing basic RBL (Real Time Blacklist) lookups with this function do:
$host = ‘64.53.200.156’ ;
$rbl = ‘sbl-xbl.spamhaus.org’ ;
// valid query format is: 156.200.53.64.sbl-xbl.spamhaus.org
$rev = array_reverse ( explode ( ‘.’ , $host ));
$lookup = implode ( ‘.’ , $rev ) . ‘.’ . $rbl ;
if ( $lookup != gethostbyname ( $lookup )) echo «ip: $host is listed in $rbl \n» ;
> else echo «ip: $host NOT listed in $rbl \n» ;
>
?>
Tomas V.V.Cox
gethostbyname and gethostbynamel does not ask for AAAA records. I have written two functions to implement this. gethostbyname6 and gethostbynamel6. I don’t believe this issue has been addressed yet.
They are made to replace gethostbyname[l], in a way that if $try_a is true, if it fails to get AAAA records it will fall back on trying to get A records.
Feel free to correct any errors, I realise that it is asking for *both* A and AAAA records, so this means two DNS calls.. probably would be more efficient if it checked $try_a before making the query, but this works for me so I’ll leave that up to someone else to implement in their own work.. the tip is out there now anyway..
function gethostbyname6($host, $try_a = false) // get AAAA record for $host
// if $try_a is true, if AAAA fails, it tries for A
// the first match found is returned
// otherwise returns false
function gethostbynamel6($host, $try_a = false) // get AAAA records for $host,
// if $try_a is true, if AAAA fails, it tries for A
// results are returned in an array of ips found matching type
// otherwise returns false
$dns6 = dns_get_record($host, DNS_AAAA);
if ($try_a == true) $dns4 = dns_get_record($host, DNS_A);
$dns = array_merge($dns4, $dns6);
>
else < $dns = $dns6; >
$ip6 = array();
$ip4 = array();
foreach ($dns as $record) if ($record[«type»] == «A») $ip4[] = $record[«ip»];
>
if ($record[«type»] == «AAAA») $ip6[] = $record[«ipv6»];
>
>
if (count($ip6) < 1) if ($try_a == true) if (count($ip4) < 1) return false;
>
else return $ip4;
>
>
else return false;
>
>
else return $ip6;
>
>