[ Team LiB ] |
![]() ![]() |
Converting IP Addresses and HostnamesEven if your server does not provide you with a $_SERVER['REMOTE_HOST'] variable, you will probably know the IP address of a visitor from the $_SERVER['REMOTE_ADDR'] environment variable. You can use this in conjunction with the function gethostbyaddr() to get the user's hostname. gethostbyaddr() requires a string representing an IP address and returns the equivalent hostname. If an error occurs, it returns the IP address it was given. Listing 14.5 creates a script that uses gethostbyaddr() to acquire the user's hostname if the $REMOTE_HOST variable is unavailable. Listing 14.5 Using gethostbyaddr() to Get a Hostname1: <!DOCTYPE html PUBLIC 2: "-//W3C//DTD XHTML 1.0 Strict//EN" 3: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 4: <html> 5: <head> 6: <title>Listing 14.5 Using gethostbyaddr() to get a host name</title> 7: </head> 8: <body> 9: <div> 10: <?php 11: if ( ! empty( $_SERVER['REMOTE_HOST'] ) ) { 12: print "Hello visitor at ".$_SERVER['REMOTE_HOST']; 13: } else if ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) { 14: print "Hello visitor at "; 15: print gethostbyaddr( $_SERVER['REMOTE_ADDR'] ); 16: } else { 17: print "Hello you, wherever you are"; 18: } 19: ?> 20: </div> 21: </body> 22: </html> If we have access to the $_SERVER['REMOTE_HOST'] element, we simply print this to the browser on line 12. Otherwise, if we have access to the $_SERVER['REMOTE_ADDR'] element, we attempt to acquire the user's hostname using gethostbyaddr() on line 15. If all else fails, we print a generic welcome message on line 17. To attempt to convert a hostname to an IP address, you can use gethostbyname(). This function requires a hostname as its argument. It returns an IP address or, if an error occurs, the hostname you provided. ![]() |
[ Team LiB ] |
![]() ![]() |