Php проверить есть ли host

How can I detect if the user is on localhost in PHP?

In other words, how can I tell if the person using my web application is on the server it resides on? If I remember correctly, PHPMyAdmin does something like this for security reasons.

11 Answers 11

You can use $_SERVER[‘REMOTE_ADDR’] , which contains the IP address of the client requesting it, as given by the web server.

$whitelist = array( '127.0.0.1', '::1' ); if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)) < // not valid >

Note: the original version of this answer suggested verifying the destination hostname using $_SERVER[‘HTTP_HOST’], which is unsafe because it could in some cases be spoofed by the requester.

@Pekka웃 you can just send e.g. Host: 127.0.0.1 and it would be populated in HTTP_HOST , so it’s not reliable method at all.

As a complement, as a function.

function isLocalhost($whitelist = ['127.0.0.1', '::1'])

As good practice I would recommend adding «else return false;» so that the function always returns a boolean value. Or alternately, just remove the «if» completely and instead «return in_array( $_SERVER[‘REMOTE_ADDR’], $whitelist);»

Newer OS users (Win 7, 8) may also find it necessary to include an IPV6-format remote address in their whitelist array:

$whitelist = array('127.0.0.1', "::1"); if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)) < // not valid >

I’m sorry but all these answers seem terrible to me. I would suggest rephrasing the question because in a sense all machines are «localhost».

The question should be; How do I run different code paths depending on which machine it is executed on.

In my opinion, the easiest way is to create a file called DEVMACHINE or whatever you want really and then simply check

Remember to exclude this file when uploading to the live hosting environment!

This solution is not depending on network configuration, it can not be spoofed and makes it easy to switch between running «live-code» and «dev-code».

$_SERVER[«REMOTE_ADDR»] should tell you the user’s IP. It’s spoofable, though.

Check this bounty question for a very detailed discussion.

I think what you remember with PHPMyAdmin is something different: Many MySQL Servers are configured so that they can only be accessed from localhost for security reasons.

It’s worth noting that some MySQL servers are so configured by not binding to a public interface. Similarly, if you wanted to restrict a PHP application in the same way, you should consider serving it via an apache instance bound only to an internal interface.

It doesn’t seem you should use $_SERVER[‘HTTP_HOST’] , because this is the value in http header, easily faked.

Читайте также:  Php pdo query fetch all

You may use $_SERVER[«REMOTE_ADDR»] too, this is the more secure value, but it is also possible to fake. This remote_addr is the address where Apache returns result to.

REMOTE_ADDR is possible to fake, however if you want to fake it as 127.0.0.1 or ::1 , that requires compromising the machine, at which a spoofed REMOTE_ADDR is the least of your worries. Relevant answer — stackoverflow.com/a/5092951/3774582

Used this simple PHP condition

if($_SERVER['HTTP_HOST'] == 'localhost')

I guess this works if you want to prevent people accidentally accessing it specifically through «localhost» hostname (note that «127.0.0.1» would still work), but in general it’s not safe to use HTTP_HOST, because it can be spoofed.

I used same, now i am using different port. and this condition does not work anymore. any ideas what to change?

If you want to have a whitelist / allowlist that supports static IPs and dynamic names.

$whitelist = array("localhost", "127.0.0.1", "devel-pc.ds.com", "liveserver.com"); if (!isIPWhitelisted($whitelist)) die(); 

This way you could set a list of names/IPs that will be able (for sure) to be detected. Dynamic names add more flexibility for accessing from different points.

You have two common options here, you could set a name in your local hosts file or you could just use one dynamic name provider that could be found anywhere.

This function CACHES results because gethostbyname is a very slow function.

For this pupose I’ve implemented this function:

function isIPWhitelisted($whitelist = false) < if ( isset($_SESSION) && isset($_SESSION['isipallowed']) ) < return $_SESSION['isipallowed']; >// This is the whitelist $ipchecklist = array("localhost", "127.0.0.1", "::1"); if ($whitelist) $ipchecklist = $whitelist; $iplist = false; $isipallowed = false; $filename = "resolved-ip-list.txt"; $filename = substr(md5($filename), 0, 8)."_".$filename; // Just a spoon of security or just remove this line if (file_exists($filename)) < // If cache file has less than 1 day old use it if (time() - filemtime($filename) // If file was not loaded or found -> generate ip list if (!$iplist) < $iplist = array(); $c=0; foreach ( $ipchecklist as $k =>$iptoresolve ) < // gethostbyname: It's a VERY SLOW function. We really need to cache the resolved ip list $ip = gethostbyname($iptoresolve); if ($ip != "") $iplist[$c] = $ip; $c++; >file_put_contents($filename, implode(";", $iplist)); > if (in_array($_SERVER['REMOTE_ADDR'], $iplist)) // Check if the client ip is allowed $isipallowed = true; if (isset($_SESSION)) $_SESSION['isipallowed'] = $isipallowed; return $isipallowed; > 

For better reliability you could replace the $_SERVER[‘REMOTE_ADDR’] for the get_ip_address() that @Pekka mentioned in his post as «this bounty question»

Источник

gethostbyname

Возвращает адрес IPv4 или строку, содержащую неизмененный hostname в случае возникновения ошибки.

Примеры

Пример #1 Простой пример использования gethostbyname()

$ip = gethostbyname ( ‘www.example.com’ );

Смотрите также

  • gethostbyaddr() — Получает доменное имя хоста, соответствующее переданному IP-адресу
  • gethostbynamel() — Получает список IPv4-адресов, соответствующих переданному доменному имени хоста
  • inet_pton() — Конвертирует читаемый IP-адрес в его упакованное представление in_addr
  • inet_ntop() — Конвертирует упакованный интернет-адрес в читаемый формат

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.

Читайте также:  Css запуск с параметрами

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

Читайте также:  Php get server http or https

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;
>
>

Источник

PHP. Как лучше всего проверить существует ли сайт или нет

А если домен свободен, не делегирован, не регистрирован, его просто нет. Как получить однозначный ответ что его нет. Просто может я особенный какой, но у меня все средства перечисленные в вопросе пишут мол http 200 OK любому несуществующему домену

Делал такую реализацию на PHP, вот рабочий код:

$website = «www.site.ru»
// Открываем соединение с сокетом и связываем его с переменной
$sock = fsockopen ($website, 80, $errno, $errstr);
//Если соединение не установлено, то будет ошибка
if (!$sock)
<
echo(«$errno($errstr)»);
return;
>
//Иначе проверяем доступность ресурса и записываем результат
else
<
fputs ($sock, «GET / HTTP/1.0\r\nHost: www.example.com\r\n\r\n»);
$status = substr(str_replace(«:»,»: «, fgets($sock,128)), 9);
if(substr($status,0,6)!=«200 OK»)
echo «Сайт недоступен!»
>
//Закрываем соединение
fclose ($sock);

Почти хороший способ.
«Почти» — потому что для некоторых валидных сайтов код будет не 200.
Например, www.habr.ru — 302 Moved Temporarily

DevMan

Использовать функцию gethostbyname:

Если выдаст ip, значит сайт зарегистрирован и делегирован

Если просто проверить, то curl. Написан на C. Т.е. языке более низкого уровня… Следовательно работать должен побыстрее… А вообще если вы спамом массовым не занимаетесь или не изобретаете пауков каких-нибудь или еще что-то в этом роде, пишите так как вам удобно.

Никак.
Если домен указывает на какой-либо IP и на этом IP крутится хоть какой то сайт — то по домену откроется дефолтный сайт для IP.

Ну более-менее приемлемый вариант — читать статус-код HTTP. Это позволит лишь узнать, что на данном домене крутится веб-сервер. Но на самом деле там может лежать REST backend для AJAX морды, например. Стопроцентной вероятности никакая более-менее быстрая проверка не даст.

Не совсем понятно что Вы хотите сделать. Если узнать существует ли (делегирован) домен — обратитесь CURLом на Whois-сервис, коих в интернете множество, и распарсите ответ. Если, вертится ли по адресу, указанному доменным именем, веб-сервер, CURLом дёрните это имя, и отпарсите ответ. Если отвалитесь по таймауту — нету, если ответят — что-то есть. А если жив ли в данным момент сайт — то ещё отпарсите и код ответа/ошибки.

Войдите, чтобы написать ответ

Как разложить URL path на части?

Как правильно настроить Kafka acl и sasl для нескольких пользователей?

Источник

Оцените статью