Geoplugin API在线服务器失效求助:本地正常线上无数据
Hey there, let's break down why your code runs smoothly locally but breaks when deployed to an online server. I'll walk through common issues and practical fixes tailored to your code:
1. First: Add Detailed Error Logging to Diagnose Exact Issues
Right now, your error alerts are generic—you can't tell if the problem is with IP detection, the geolocation API request, or server restrictions. Let's add logging to get specific details:
// Enable error logging to a file error_reporting(E_ALL); ini_set('log_errors', 1); ini_set('error_log', 'geolocation_errors.log'); // ... rest of your existing code ... // Update the file_get_contents failure block if($query === false){ $last_error = error_get_last(); error_log("Geoplugin request failed: " . $last_error['message']); echo "<script type='text/javascript'>alert('حدث خطأ ما والرجاء المحاولة في ما بعد')</script>"; echo "<script> window.location.assign('../index.php?gettingdata=failed');</script>"; }
This will create a geolocation_errors.log file on your server with precise info (like "allow_url_fopen is disabled" or "connection timed out") to pinpoint the issue.
2. Fix IP Detection for Servers Behind Proxies/CDNs
Online servers often use proxies or CDNs (like Cloudflare), so HTTP_X_FORWARDED_FOR might return a comma-separated list of IPs. Your current code returns the entire string, which breaks the geolocation request. Update your get_ip() function:
function get_ip(){ // Handle proxies/CDNs properly if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){ // Split the IP list and validate each entry $ip_list = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); foreach($ip_list as $ip){ $clean_ip = trim($ip); if(filter_var($clean_ip, FILTER_VALIDATE_IP)){ return $clean_ip; } } } // Fallback to other IP headers if(isset($_SERVER['HTTP_CLIENT_IP']) && filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)){ return $_SERVER['HTTP_CLIENT_IP']; } return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''; }
Also, ensure your server/CDN is configured to pass the real visitor IP to your PHP app (for example, Cloudflare requires enabling "True Client IP" in your dashboard).
3. Replace file_get_contents with cURL (More Reliable for Remote Requests)
Many online servers disable allow_url_fopen for security reasons. cURL is a more robust alternative for remote API calls:
if($ip){ $geoplugin_url = 'http://www.geoplugin.net/php.gp?ip=' . $ip; // Initialize cURL $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $geoplugin_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Timeout after 10 seconds to avoid hangs $response = curl_exec($ch); $curl_error = curl_error($ch); curl_close($ch); // Handle cURL errors if($curl_error){ error_log("cURL Error: " . $curl_error); echo "<script type='text/javascript'>alert('حدث خطأ ما والرجاء المحاولة في ما بعد')</script>"; echo "<script> window.location.assign('../index.php?gettingdata=failed');</script>"; } else { $query = unserialize($response); // Validate the API response if($query && isset($query['geoplugin_countryName'])){ // Your existing code to extract variables and redirect $country = $query['geoplugin_countryName']; $countrycode = $query['geoplugin_countryCode']; $city = $query['geoplugin_city']; $regionname = $query['geoplugin_regionName']; $lat = $query['geoplugin_latitude']; $long = $query['geoplugin_longitude']; $timezone = $query['geoplugin_timezone']; echo "<script> window.location.assign('../".$page.".php?IP=".$ip."&country=".$country."&countrycode=".$countrycode."&city=".$city."&latitude=".$lat."&longtitude=".$long."&timez=".$timezone."®ionName=".$regionname."&gettingdata=success');</script>"; } else { error_log("Invalid response from Geoplugin: " . $response); echo "<script type='text/javascript'>alert('حدث خطأ ما والرجاء المحاولة في ما بعد')</script>"; echo "<script> window.location.assign('../index.php?gettingdata=failed');</script>"; } } }
4. Check for Geoplugin Access Restrictions
Sometimes online server IPs get blocked by Geoplugin (especially if you're making too many requests). If you have SSH access to your server, test the API directly from the command line:
curl http://www.geoplugin.net/php.gp?ip=8.8.8.8
If this returns an error, you may need to reach out to Geoplugin support or switch to a free alternative like IPinfo or MaxMind.
5. Sanitize User Input to Boost Security
Your code uses $_GET['page'] directly in the redirect, which is a security risk (open to XSS or path traversal attacks). Sanitize it first:
// Only allow valid page names (prevents malicious input) $page = isset($_GET['page']) ? basename($_GET['page']) : 'index';
内容的提问来源于stack exchange,提问作者Mohammad hamad

