-
-
Save JoshuaGoode/f9efd25bb46fe0dc4fe8c9c855fe4479 to your computer and use it in GitHub Desktop.
GEOGRAPHIC ACCESS RESTRICTION
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * GEOGRAPHIC ACCESS RESTRICTION | |
| * | |
| * This segment of code is designed to restrict access to the website based on the geographic location of the user. | |
| * It checks the server API to ensure that the geographic checks are only applied in web contexts, not CLI or FPM. | |
| * Allowed countries are defined in the $allowedCountries array. Requests from other countries are blocked with a 404 response. | |
| * | |
| * Dependencies: Requires server variables set by the GeoIP module. | |
| * | |
| * @author Joshua Goode, Automattic | |
| * @date 2024-04-29 | |
| * @version 1.0.0 | |
| */ | |
| // Array of allowed country codes | |
| $allowedCountries = ['US', 'CA', 'UK']; | |
| // Get the current server API | |
| $api = php_sapi_name(); | |
| // Bypass geo checks for non-web server APIs | |
| if ($api == 'fpm-fcgi' || $api == 'cli') { | |
| return; // Early exit for CLI or FPM contexts | |
| } | |
| // Retrieve the country code or default to blocking access | |
| $countryCode = $_SERVER['GEOIP_COUNTRY_CODE'] ?? 'Unknown'; // Using null coalescing operator for clarity | |
| // Block access if the country code is not allowed | |
| if (!in_array($countryCode, $allowedCountries)) { | |
| header('HTTP/1.1 404 Not Found', true, 404); | |
| exit; | |
| } | |
| // End of Geographic Access Restriction code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment