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