Home > database >  How do I check if entered captcha code is valid in php?
How do I check if entered captcha code is valid in php?

Time:05-09

I have a registration form with a captcha code I want to know how I can check if entered captcha code is valid or not.

if valid finish the registration process if not display an error message.

I made an example but I get this error like the image below:

Error that I get

register.php

<?php

require_once "db.php";
session_start();

if (isset($_SESSION["user_id"])) {
    header("location: acceuil.php");
}

$error = false;

if (isset($_POST["register_user"])) {
    $name = mysqli_real_escape_string($con, $_POST["name"]);
    $email = mysqli_real_escape_string($con, $_POST["email"]);
    $password = mysqli_real_escape_string($con, $_POST["password"]);
    $confirm_password = mysqli_real_escape_string($con, $_POST["confirm_password"]);

    if (!preg_match("/^[a-zA-Z ] $/", $name)) {
        $error = true;
        $uname_error = "Le nom ne doit contenir que des alphabets et des espaces !";
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = true;
        $email_error = "Veuillez saisir une adresse e-mail valide !";
    }

    if (strlen($password) < 6) {
        $error = true;
        $password_error = "Le mot de passe doit comporter au moins 6 caractères !";
    }

    if ($password != $confirm_password) {
        $error = true;
        $cpassword_error = "Le mot de passe et la confirmation du mot de passe ne correspondent pas !";
    }
    
if(sha1($_POST['verif_code']) == $_SESSION['verif_code']) { 
    $captcha = $_POST['verif_code'];
} else { 
    $error = true;
    $error_message = "The captcha code you entered does not match. Please try again.";
}

    // Check the database to make sure
    // a user does not already exist with the same name and/or email
    $query = "SELECT * FROM users WHERE name='$name' OR email='$email' LIMIT 1";
    $result = mysqli_query($con, $query);
    $user = mysqli_fetch_assoc($result);

    if ($user) {
        if ($user["name"] === $name) {
            $error_message = "Ce nom est déjà utilisé !";
        }

        if ($user["email"] === $email) {
            $error_message = "Cet e-mail est déjà utilisé !";
        }
    } else {
        // Finally, register user if there are no errors in the form
        if (mysqli_query($con, "INSERT INTO users(name, email, password) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
            $success_message = "Votre compte a été créé avec succès.";
            // header("Refresh:2 ; URL=auth.php");
        } else {
            $error_message = "Oups! quelque chose ne va pas lors de l'inscription! Veuillez réessayer plus tard!";
        }
    }
}

?>

<!DOCTYPE html>
<!--[if lt IE 7]><html  lang="en"> <![endif]-->
<!--[if IE 7]><html  lang="en"> <![endif]-->
<!--[if IE 8]><html  lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
<html lang="en">
    <!--<![endif]-->
    <head>
        <!-- Required meta tags -->
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="description" content="Project Description" />
        <meta name="author" content="Project Author" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
        <title>Inscription</title>
        <!-- CSS Libraries -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
        <!-- Google Fonts -->
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" />
        <style>
            body {
                font-family: "Poppins", sans-serif;
            }
        </style>
    </head>
    <body >
        <div >
            
<?php
if (isset($success_message)) {
    echo "<div class='alert alert-success'><i class='fas fa-check-circle me-1'></i> " . $success_message . "</div>";
}

if (isset($error_message)) {
    echo "<div class='alert alert-danger'><i class='fas fa-exclamation-triangle me-1'></i> " . $error_message . "</div>";
}
?>
            
            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" autocomplete="off">
                <fieldset>
                    <legend >Connectez-vous et profitez de nos meilleur produits</legend>
                    <div >
                        <label for="name" ><i ></i> Name <sup >*</sup></label>
                        <div >
                            <input type="text" id="name"  name="name" value="<?php if($error) echo $name; ?>" autofocus required />
                            <?php if (isset($uname_error)) echo "<div class='text-danger mt-3'><i class='fas fa-exclamation-triangle me-1'></i> ". $uname_error ."</div>"; ?>
                        </div>
                    </div>
                    <div >
                        <label for="email" ><i ></i> E-mail <sup >*</sup></label>
                        <div >
                            <input type="email" id="email"  name="email" value="<?php if($error) echo $email; ?>" required />
                            <?php if (isset($email_error)) echo "<div class='text-danger mt-3'><i class='fas fa-exclamation-triangle me-1'></i> ". $email_error ."</div>"; ?>
                        </div>
                    </div>
                    <div >
                        <label for="password" ><i ></i> Mot de passe <sup >*</sup></label>
                        <div >
                            <input type="password" id="password"  name="password" value="" required />
                            <?php if (isset($password_error)) echo "<div class='text-danger mt-3'><i class='fas fa-exclamation-triangle me-1'></i> ". $password_error ."</div>"; ?>
                        </div>
                    </div>
                    <div >
                        <label for="confirm_password" ><i ></i> Retapez votre MdP <sup >*</sup></label>
                        <div >
                            <input type="password" id="confirm_password"  name="confirm_password" value="" required />
                            <?php if (isset($cpassword_error)) echo "<div class='text-danger mt-3'><i class='fas fa-exclamation-triangle me-1'></i> ". $cpassword_error ."</div>"; ?>
                        </div>
                    </div>
                    <div >
                        <img src="captcha/verif_code_gen.php"  alt="code de vérification" />
                        <div >
                            <input type="text"  name="verif_code" value="" required />
                            <?php if (isset($captcha_error)) echo "<div class='text-danger mt-3'><i class='fas fa-exclamation-triangle me-1'></i> ". $captcha_error ."</div>"; ?>
                        </div>
                    </div>
                    <div >
                        <button type="submit"  name="register_user">S'inscrire<i ></i></button>
                    </div>
                </fieldset>
            </form>
            <p>
                Already a member? <a href="auth.php">Sign in</a>
            </p>
        </div>
        <!-- JS Libraries -->
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    </body>
</html>

captcha/verif_code_gen.php

<?php
session_start();
header("Content-type: image/png");
$_img = imagecreatefrompng("fond_verif_img.png");
$avant_plan = imagecolorallocate($_img, 255, 255, 255);
$nombre = mt_rand(100000, 999999);
$_SESSION["alert_nbr"] = $nombre;
imagestring($_img, 5, 18, 8, $nombre, $avant_plan);
imagepng($_img);
?>

captcha.php

<?php
   session_start();
   $code=rand(1000,9999);
   $_SESSION["code"]=$code;
   $image = imagecreatetruecolor(50, 24);
   $background = imagecolorallocate($image, 245, 73, 73); 
   $forground = imagecolorallocate($image, 255, 255, 255);
   imagefill($image, 0, 0, $background);
   imagestring($image, 5, 5, 5,  $code, $forground);
  header("Cache-Control: no-cache, must-revalidate");
  header('Content-type: image/png');
  imagepng($image);
  imagedestroy($image);
?>

How do I fix this issue?

CodePudding user response:

Many things.

You're using different variable names in each script.

  • In register.php you're comparing the POST variable to $_SESSION['verif_code']
  • In captcha/verif_code_gen.php you call it $_SESSION["alert_nbr"]
  • In captcha.php you call it $_SESSION["code"]

Second, why are you creating a random number twice? Let's do some cleaning up and simplify:

In register.php:

After error = false insert this

$error = false;

$_SESSION["captcha_code"] = mt_rand(100000, 999999);

Change the following lines to:

if($_POST['verif_code']) != $_SESSION['captcha_code']) { 
    $error = true;
    $error_message = "The captcha code you entered does not match. Please try again.";
}

Then captcha/verif_code_gen.php should be:

session_start();
header("Content-type: image/png");
$_img = imagecreatefrompng("fond_verif_img.png");
$avant_plan = imagecolorallocate($_img, 255, 255, 255);
$nombre = $_SESSION["captcha_code"];
imagestring($_img, 5, 18, 8, $nombre, $avant_plan);
imagepng($_img);

Now you don't need captcha.php

  • Related