What is the purpose of CAPTCHA in PHP and how can it be implemented for form submissions?

CAPTCHA is used in PHP to prevent automated bots from submitting forms on websites. It presents users with a challenge, such as typing in distorted text or selecting images, to verify that they are human. This helps to reduce spam submissions and protect the website from malicious activities.

<?php
session_start();

if(isset($_POST['submit'])){
    $captcha = $_POST['captcha'];
    if($captcha == $_SESSION['captcha']){
        // Form submission code here
    } else {
        echo "CAPTCHA verification failed. Please try again.";
    }
}

// Generate CAPTCHA code
$captchaCode = substr(md5(rand()), 0, 6);
$_SESSION['captcha'] = $captchaCode;
?>

<form method="post" action="">
    <label for="captcha">Enter the code shown above:</label><br>
    <img src="captcha_image.php" alt="CAPTCHA Image"><br>
    <input type="text" id="captcha" name="captcha"><br>
    <input type="submit" name="submit" value="Submit">
</form>