PHP में server का IP address प्राप्त करने के कई तरीके हैं, संदर्भ के आधार पर।
विधि 1: $_SERVER Superglobal (Web Context)
<?php // सबसे आम - सर्वर का IP जहां स्क्रिप्ट चल रही है $serverIp = $_SERVER['SERVER_ADDR']; // सर्वर पोर्ट $serverPort = $_SERVER['SERVER_PORT']; echo "Server IP: $serverIp"; echo "Server Port: $serverPort";
विधि 2: gethostname() + gethostbyname() (CLI/Standalone Scripts)
<?php // PHP 5.3+ के लिए $hostname = gethostname(); $ipAddress = gethostbyname($hostname); echo "Hostname: $hostname"; echo "IP Address: $ipAddress";
विधि 3: सभी Network Interfaces प्राप्त करें
<?php
function getAllServerIps() {
$ips = [];
// Linux/Unix
if (function_exists('exec')) {
exec("hostname -I", $output);
if (!empty($output[0])) {
$ips = array_merge($ips, explode(' ', trim($output[0])));
}
}
// Windows
if (empty($ips) && function_exists('exec')) {
exec("ipconfig", $output);
foreach ($output as $line) {
if (preg_match('/IPv4 Address.*: (\d+\.\d+\.\d+\.\d+)/', $line, $matches)) {
$ips[] = $matches[1];
}
}
}
// Fallback
if (empty($ips)) {
$ips[] = $_SERVER['SERVER_ADDR'] ?? gethostbyname(gethostname());
}
return array_unique($ips);
}
print_r(getAllServerIps());
विधि 4: Public IP पता करें (External Service)
<?php
function getPublicIp() {
$services = [
'https://api.ipify.org',
'https://ifconfig.me/ip',
'https://icanhazip.com',
'https://ident.me'
];
foreach ($services as $service) {
$ip = @file_get_contents($service);
if ($ip && filter_var(trim($ip), FILTER_VALIDATE_IP)) {
return trim($ip);
}
}
return false;
}
echo "Public IP: " . (getPublicIp() ?? 'निर्धारित नहीं कर सके');
कौन सी विधि कब उपयोग करें?
| संदर्भ | अनुशंसित विधि |
|---|---|
| Web request (Apache/Nginx) | $_SERVER['SERVER_ADDR'] |
| CLI script / Cron job | gethostbyname(gethostname()) |
| Docker container | gethostbyname(gethostname()) या container metadata |
| Load balancer के पीछे | $_SERVER['HTTP_X_FORWARDED_FOR'] (वैधता के साथ) |
| Public IP चाहिए | External API service |
Load Balancer/Proxy के पीछे Real IP
function getRealClientIp() {
$headers = [
'HTTP_CF_CONNECTING_IP', // Cloudflare
'HTTP_X_FORWARDED_FOR', // Standard proxy
'HTTP_X_REAL_IP', // Nginx proxy
'HTTP_CLIENT_IP', // Some proxies
'REMOTE_ADDR' // Direct connection
];
foreach ($headers as $header) {
if (!empty($_SERVER[$header])) {
// X-Forwarded-For में multiple IPs हो सकते हैं, पहला लें
$ips = explode(',', $_SERVER[$header]);
return trim($ips[0]);
}
}
return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
}