Skip to content

Commit 709f251

Browse files
fix user ip not found
1 parent 6eccfeb commit 709f251

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

ip-to-county-for-cf7.php

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
* Plugin Name: CF7 Country Detector
44
* Plugin URI: https://github.com/builderhall/CF7-Country-Detector
55
* Description: Captures user IP location when a Contact Form 7 form is submitted.
6-
* Version: 1.0
6+
* Version: 1.1
77
* License: GPLv3 or later
88
* Author: Builder Hall Ltd.
99
* Author URI: https://builderhall.com
@@ -20,25 +20,29 @@ function capture_user_ip_location($contact_form) {
2020
if ($submission) {
2121

2222
// Get user's IP address
23-
if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
24-
$user_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
23+
$user_ip = '';
24+
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
25+
$ip_array = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
26+
$user_ip = trim($ip_array[0]);
2527
} else {
2628
$user_ip = $_SERVER['REMOTE_ADDR'];
2729
}
2830

2931
// Get user's IP location using
3032
$ip_info = json_decode(file_get_contents("https://ipinfo.io/{$user_ip}/json"));
3133

32-
// Extract relevant location information
33-
$location = isset($ip_info->city) ? $ip_info->city . ', ' : '';
34-
$location .= isset($ip_info->region) ? $ip_info->region . ', ' : '';
35-
$location .= isset($ip_info->country) ? $ip_info->country : '';
34+
// Extract relevant location information if available
35+
if ($ip_info && isset($ip_info->city, $ip_info->region, $ip_info->country)) {
36+
$location = "{$ip_info->city}, {$ip_info->region}, {$ip_info->country}";
37+
} else {
38+
$location = 'Location data not available';
39+
}
3640

3741
// Add the location to the Contact Form 7 email body
3842
$mail = $contact_form->prop('mail');
39-
$mail['body'] .= "\nUser Location: {$location}";
43+
$mail['body'] .= "\nUser Location: {$location}";
4044

4145
// Update the mail properties
4246
$contact_form->set_properties(array('mail' => $mail));
4347
}
44-
}
48+
}

0 commit comments

Comments
 (0)