Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Brandon Brigham
Brandon Brigham
3,716 Points

While adding a CAPTCHA to a form I don't know how to connect it to the form itself

I added a CAPTCHA to a from in php. For some reason when the code is plugged in outside of the <form> </form> elements it works but when put inside the pre-existing form it doesn't.

Is there something I need to change to the following CAPTCHA in order for it to work within a contact form?

<?php

/** Validate captcha */ if (!empty($_REQUEST['captcha'])) { if (empty($_SESSION['captcha']) || trim(strtolower($_REQUEST['captcha'])) != $_SESSION['captcha']) { $captcha_message = "Invalid captcha"; $style = "background-color: #FF606C"; } else { $captcha_message = "Valid captcha"; $style = "background-color: #CCFF99"; }

$request_captcha = htmlspecialchars($_REQUEST['captcha']);

echo <<<HTML
    <div id="result" style="$style">
    <h2>$captcha_message</h2>
    <table>
    <tr>
        <td>Session CAPTCHA:</td>
        <td>{$_SESSION['captcha']}</td>
    </tr>
    <tr>
        <td>Form CAPTCHA:</td>
        <td>$request_captcha</td>
    </tr>
    </table>
    </div>

HTML; unset($_SESSION['captcha']); }

?>

<br /><br />

<p><strong>Write the following word:</strong></p>

<form method="GET"> <img src="captcha.php" id="captcha" /><br/>

<!-- CHANGE TEXT LINK --> <a href="#" onclick=" document.getElementById('captcha').src='captcha.php?'+Math.random(); document.getElementById('captcha-form').focus();" id="change-image">Not readable? Change text.</a><br/><br/>

<input type="text" name="captcha" id="captcha-form" autocomplete="off" /><br/> <input type="submit" />

</form>