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>
Keywords
Related Questions
- What are some best practices for handling SQL queries with PHP to ensure successful data insertion?
- What are the potential pitfalls of relying on register_globals = on in PHP scripts and why is it discouraged by providers?
- In the context of MVC architecture in PHP, what are the best practices for structuring controllers and views to ensure scalability and maintainability in web development projects?