How can IP address verification be implemented to prevent cookie stealing in PHP scripts?

To prevent cookie stealing in PHP scripts, IP address verification can be implemented by comparing the IP address of the user making the request with the IP address stored in the session. This helps ensure that the request is coming from the same user who originally set the cookie.

// Start the session
session_start();

// Get the user's IP address
$user_ip = $_SERVER['REMOTE_ADDR'];

// Check if the stored IP address matches the user's IP address
if(isset($_SESSION['user_ip']) && $_SESSION['user_ip'] !== $user_ip){
    // Invalid IP address, destroy the session and redirect
    session_destroy();
    header('Location: login.php');
    exit;
}

// Store the user's IP address in the session
$_SESSION['user_ip'] = $user_ip;