They're Playing Our Song
The PlaySound.php script (Listing Two) uses PHP to dynamically form an MP3 stream by concatenating shorter MP3 files. The PHP header() function writes out the content-type as MPEG. Then, I start the stream with a short introduction that simply says, "Please enter these four numbers." This is the Intro.mp3 file, which starts the stream.
The script then retrieves the four numbers from the $_SESSION array. The numbers are stored in the array as a single string, so the script pulls the string apart, storing the numbers in a filename array. Then, for each number, the corresponding MP3 file is added to the stream. This is the section where you may want to include some additional words.
Finally, the stream is printed to standard out and, thanks to the content-type header, is interpreted by the browser to be an MP3 file. Naturally, there are many different ways to play audio on the Web. I chose MP3 because it's easy to concatenate separate files due to the fact that there is no header information to be concerned with as there is with .wav files. You may want to experiment with different file types for your own CAPTCHA, perhaps Flash for example.
<?php session_start(); header('Content-type: audio/x-mpeg'); /* put an intro in first */ $thisFile = "Intro.mp3"; $fh = fopen($thisFile, 'r'); $allAudio = fread($fh, filesize($thisFile)); fclose($fh); /* add the numbers to the file */ $str = $_SESSION['captchaAnswer']; /* this works under PHP4, can use str_split() here instead in PHP5 */ $fileName = array(); for ($i = 0; $i < strlen($str); $i++) $fileName[] = substr($str,$i,1); foreach ($fileName as $fileNumer) { $thisFile = $fileNumer . ".mp3"; $fh = fopen($thisFile, 'r'); $allAudio .= fread($fh, filesize($thisFile)); fclose($fh); } /* output the resulting MP3 */ print $allAudio; ?>
The last file, CaptchaSubmit.php (Listing Three) serves to check user input and outputs a simple message to indicate success or failure. CheckAnswer() first checks to see if anything was posted at all and if the PHP session is set. Then, it checks the user posted answer against the challenge initialized in the index.htm file, returning True or False (1 or 0) as is appropriate.
<?php session_start(); header('Content-type: text/html'); // true if correct answer function CheckAnswer() { if (!isset($_POST['userAnswer']) || !isset($_SESSION['captchaAnswer'])) return 0; else if ($_POST['userAnswer'] == $_SESSION['captchaAnswer']) return 1; return 0; } print "<html><head></head><body>"; print $_POST['userAnswer']; if(CheckAnswer()) print " is correct."; else print " is not correct, please go back and try again."; print"</body><html>"; ?>
You will want to replace the lower half of this script, that outputs success or failure, with your own success criteria, probably a redirect back to your blog or other media page.