How can IP addresses be blocked in PHP to prevent DDoS attacks?

To prevent DDoS attacks by blocking IP addresses in PHP, you can create a function that checks the incoming IP address against a list of known malicious IPs and denies access if a match is found. This can help mitigate the impact of DDoS attacks by blocking malicious traffic at the server level.

function blockIP($ip) {
    $blacklist = array("192.168.1.1", "10.0.0.1"); // List of known malicious IPs
    if (in_array($ip, $blacklist)) {
        header("HTTP/1.1 403 Forbidden");
        exit();
    }
}

$visitorIP = $_SERVER['REMOTE_ADDR'];
blockIP($visitorIP);