How can white-listing be implemented in PHP to enhance security and prevent unauthorized access?
White-listing can be implemented in PHP by creating an array of allowed IP addresses and then checking incoming requests against this list. If the request IP address is not in the white-list, access can be denied by returning a 403 Forbidden response. This helps enhance security by only allowing access to known and trusted IP addresses.
// Define an array of allowed IP addresses
$allowed_ips = array('192.168.1.1', '10.0.0.1');
// Get the client's IP address
$client_ip = $_SERVER['REMOTE_ADDR'];
// Check if the client's IP is in the white-list
if (!in_array($client_ip, $allowed_ips)) {
http_response_code(403);
die("Access Forbidden");
}