Узнать имя компьютера php

Get the client’s computer name

I am getting the client’s (website user’s) IP address. Now I’d like to go one step further by knowing the user’s computer name. So far, my research has not turned up anything to aid me in retrieving this information. Is it possible to use the user’s IP address, or some other means, to get my visitor’s computer name using PHP?

What Basically u need to do with Computer Name here? telling us the requirement of using «COMPUTER NAME» we might help u in any other way to accomplish ur goal

Ok, Basically i want to keep information of user and their computer configuration for some survey purpose. I want to know, what is the percentage of user of different Operating system with hardware configuration. I want to mention this survey in my presentation. Hope knowing user information is not an illegal matter.

8 Answers 8

gethostbyaddr($_SERVER['REMOTE_ADDR']) 

This doesn’t work in all cases. If the server is in internet and the visitor behind a router, you’ll only get the hostname of the router, but not of the visitors computer.

You can perform a reverse DNS lookup using gethostbyaddr() .

Note that this will give you the name of the host the request came from according to reverse DNS.

  • It will not give you a result if reverse DNS isn’t set up
  • It will not give you the Windows name of the computer
  • It will give you the name of the router if NAT is involved or proxy if a proxy is involved.

Not possible with plain php running on the server. It’d be a security/privacy issue to know details of the client such as computer name, mac address, contents of his drive.

You need some sort of application running on the client’s machine in order to get this.

Exactly, I don’t want to see his/her disk content or mac address. But i want to know just computer configuration(processor’s GHz, Processor’s name, RAM capacity) he/she is using(configuration) and the Operating System.

All of these are of similar importance (i.e private data, can be used to tell one user from other) and are not allowed by the http spec & implementers. You’d need some kind of signed applet or flash or activex component which would get those for you and send them to your server via http. This would definitely require the user’s consent.

You can force the browser to send the client’s computer name via NTLM to the server, which then can be read by the PHP script: stackoverflow.com/a/43842041/251719 Maybe not the most easy way, but it is possible at all.

If you’re referring to the hostname (displayed for instance by the hostname command on linux) of the computer doing the request:

That information is not included in an HTTP request. (That is, it’s impossible for PHP to figure out.)

Читайте также:  Php my admin root password

You could do a reverse DNS lookup, but that’s probably not what you want anyway.

This is all that you could get using just PHP (you may try these butIi dont think this is what you actually needed):

gethostname() gethostbyname(gethostname()) $_SERVER['HTTP_HOST'] $_SERVER['SERVER_SIGNATURE'] $_SERVER['SERVER_NAME'] $_SERVER['SERVER_ADDR'] $_SERVER['SERVER_PORT'] $_SERVER['REMOTE_ADDR'] gethostbyaddr($_SERVER['REMOTE_ADDR']) php_uname() 

The only thing you could do is try to get a DNS name for the client. «Computer Name» is a Windows made-up thing. Just call the built-in function gethostbyaddr() with the client’s IP address. However, it won’t always (hardly ever) work.

You can do this by

‘REMOTE_HOST’ — The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.

Note: Your web server must be configured to create this variable. For example in Apache you’ll need HostnameLookups On inside httpd.conf for it to exist. As David mentioned you can also use . gethostbyaddr()

Pls go thru all the comments in the url before actually using the function.

Источник

gethostname

Функция gethostname() получает стандартное имя хоста для локального компьютера.

Список параметров

У этой функции нет параметров.

Возвращаемые значения

Возвращает строку с именем хоста либо false в случае возникновения ошибки.

Примеры

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

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

  • gethostbyname() — Получает IPv4-адрес, соответствующий переданному имени хоста
  • gethostbyaddr() — Получает доменное имя хоста, соответствующее переданному IP-адресу
  • php_uname() — Возвращает информацию об операционной системе, на которой запущен PHP

User Contributed Notes 4 notes

Regarding Linux vs. macOS, that is not a difference in OS or PHP. macOS sets the hostname to .local. Open a terminal window and run `hostname` to check. The local hostname can be set on macOS under the Sharing Preferences (or Settings if Ventura 13 or newer).

Since I built a PHP app that runs on Linux Windows and MacOS I just discovered that using gethostname() behaves differently on different OSes. Linux will return «hostname» while MacOS 10.15 will return «hostname.local» . Have yet to determine how Windows behaves but the difference is worth noting. Only a few days ago I was wanting to get the LAN extension in Linux and was never able to. I was oly hable to get «hostname». In MacOS it is just there. with «hostname.local»

Источник

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.

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.

Читайте также:  Как построить диаграмму рассеивания python

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

Источник

Best way to get hostname with php

I have a php application that is installed on several servers and all of our developers laptops. I need a fast and reliable way to get the server’s hostname or some other unique and reliable system identifier. Here’s what we have thought of so far: What do you think?

Читайте также:  Concurrent calls in java

7 Answers 7

Edit: This might not be an option I suppose, depending on your environment. It’s new in PHP 5.3. php_uname(‘n’) might work as an alternative.

php_uname(‘n’) does not always equal $_SERVER[‘HOST_NAME’] The machine that you are running the script may server many different host names so don’t use this when building urls.

Aren’t hostnames unique to each machine on the same domain? As I understand this, a single machine ( or server ) would only have one hostname, because you cannot have for example two machines called iamaserver on the same domain ( iamaserver.somedomain.tld ). The only case where I can see where this is not true is if PHP is running as CGI on a separate machine from the web server.

$hostname = getenv('HOSTNAME'); if(!$hostname) $hostname = trim(`hostname`); if(!$hostname) $hostname = exec('echo $HOSTNAME'); if(!$hostname) $hostname = preg_replace('#^\w+\s+(\w+).*$#', '$1', exec('uname -a')); 
$hostname = getenv('HTTP_HOST'); 

Note that this is insecure; HTTP_HOST is controlled by the client, not the server, so relying on it is dangerous.

I am running PHP version 5.4 on shared hosting and both of these both successfully return the same results:

The accepted answer gethostname() may infact give you inaccurate value as in my case

gethostname() = my-macbook-pro (incorrect) $_SERVER['host_name'] = mysite.git (correct) 

The value from gethostname() is obvsiously wrong. Be careful with it.

Update as corrected by the comment

Host name gives you computer name, not website name, my bad. My result on local machine is

gethostname() = my-macbook-pro (which is my machine name) $_SERVER['host_name'] = mysite.git (which is my website name) 

«The value from gethostname() is obvsiously wrong.» — gethostname() returns the «local machine name», so in your case that actually looks about right? mysite.git looks like the HTTP_HOST . ( $_SERVER[‘host_name’] is not normally set.)

@MrWhite $_SERVER[‘host_name’] = null , getenv(‘HTTP_HOST’) = bool(false) , $_SERVER[‘HTTP_HOST’] = localhost:port which finally did it and wiw = what i want.

php_uname but I am not sure what hostname you want the hostname of the client or server.

plus you should use cookie based approach

Whether your webserver is Apache, NGINX or otherwise; you can set the headers which are forwarded to your PHP application. While slightly safer on its own, due to browser behavior, the Origin header is useful for this scenario.

For example, with NGINX: Add an explicit set to fastcgi_param HTTP_ORIGIN either as a hard-coded string, based on $server_name or $ssl_server_name. This is done in an NGINX server block context which will ensure host strings matched with the header, but you don’t pass the header directly to your app. Apache configs have the same information available in the virtual host configs.

This way, the string going to your app is predefined by your project. The main point is that user submitted headers will be checked against accepted values — but never passed along. The existing accepted value will be passed along instead.

Источник

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