How to identify server IP address in PHP?

In PHP, you can identify the server IP address using several built-in superglobals and functions. The method depends on whether your script runs through a web server or as a standalone script.

Using $_SERVER Superglobal

When running PHP through a web server, use the $_SERVER superglobal to get server information −

<?php
    // Get server IP address
    $server_ip = $_SERVER['SERVER_ADDR'];
    echo "Server IP: " . $server_ip;
    
    // Get server port
    $server_port = $_SERVER['SERVER_PORT'];
    echo "\nServer Port: " . $server_port;
?>

The output would be −

Server IP: 192.168.1.100
Server Port: 80

Using gethostname() and gethostbyname()

For PHP version 5.3 and higher, or when running standalone scripts (not through a web server), use these functions −

<?php
    // Get hostname first
    $host_addr = gethostname();
    echo "Hostname: " . $host_addr . "<br>";
    
    // Get IP address from hostname
    $ip_addr = gethostbyname($host_addr);
    echo "IP Address: " . $ip_addr;
?>

Comparison

Method Use Case PHP Version
$_SERVER['SERVER_ADDR'] Web server environment All versions
gethostbyname() Standalone scripts 5.3+

Conclusion

Use $_SERVER['SERVER_ADDR'] for web-based applications and gethostbyname(gethostname()) for standalone PHP scripts. Both methods reliably return the server's IP address in their respective environments.

Updated on: 2026-03-15T08:30:18+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements