What are some methods to automatically redirect visitors based on their location using PHP?

One method to automatically redirect visitors based on their location using PHP is to use a geo-location API to determine the visitor's location and then redirect them accordingly. This can be achieved by retrieving the visitor's IP address, sending it to a geo-location API, and then using the returned location data to redirect the visitor to a specific page.

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$geo_data = json_decode(file_get_contents("http://ip-api.com/json/{$ip}"));

if($geo_data->country == 'United States'){
    header('Location: us_page.php');
} elseif($geo_data->country == 'Canada'){
    header('Location: ca_page.php');
} else {
    header('Location: default_page.php');
}
?>