Dienstag, 26 August 2025

Top 5 diese Woche

Ähnliche Tutorials

Formular & Captcha

Ein einfaches Formular mit einem simplen Captcha (Rechenaufgabe) und Validierung

<?php
session_start();

// Captcha generieren
if(!isset($_SESSION['captcha'])){
    $_SESSION['captcha'] = rand(1,9) + rand(1,9); // einfache Addition
}

$error = '';
$success = '';

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $name = trim($_POST['name'] ?? '');
    $message = trim($_POST['message'] ?? '');
    $captcha = trim($_POST['captcha'] ?? '');

    if(!$name || !$message){
        $error = 'Bitte Name und Nachricht ausfüllen.';
    } elseif($captcha != $_SESSION['captcha']){
        $error = 'Captcha falsch. Bitte erneut versuchen.';
    } else {
        // Erfolgreiche Eingabe
        $success = 'Danke für deine Nachricht!';
        // Hier könntest du die Nachricht z.B. speichern
        $_SESSION['captcha'] = rand(1,9) + rand(1,9); // neues Captcha
    }
}
?>

<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>Formular mit Captcha</title>
</head>
<body>
<?php if($error): ?>
<p style="color:red;"><?php echo htmlspecialchars($error); ?></p>
<?php endif; ?>

<?php if($success): ?>
<p style="color:green;"><?php echo htmlspecialchars($success); ?></p>
<?php endif; ?>

<form method="post">
    <label>Name:</label><br>
    <input type="text" name="name"><br><br>

    <label>Nachricht:</label><br>
    <textarea name="message"></textarea><br><br>

    <label>Captcha: Was ist <?php echo $_SESSION['captcha'] - rand(1,9); ?> + ?</label><br>
    <input type="text" name="captcha"><br><br>

    <button type="submit">Absenden</button>
</form>
</body>
</html>
Vorheriges Tutorial
Nächstes Tutorial

Hier etwas für dich dabei?