Hello all,

I run simply php scripts on my site that allows people to leave comments, for example here on my ANTM page.

I have been trying to incorporate a captcha which works well speperately but I just cannot get it into the comment.php file.

The captcha works if I just post the following on a html/php page:

<formname="signupform"method="post"action="<?=$_SERVER["PHP_SELF"]?>">
Please sign up for our website:
<br>
<br>
Name: 
 
<formname="signupform"method="post"action="<?=$_SERVER["PHP_SELF"]?>">
 
<? insertSecurityImage("security_refid") ?>
<br>
Enter what you see: 
<inputname="security_try"type="text"id="security_try"size="20"maxlength="10">
(can't see? try reloading page) 
<br>
<br>
<inputtype="submit"name="Submit"value="Signup!">
</form>

However, I want to include it in the comment form in its php file which looks like this:

<formname=\"submitcomment\"method=\"post\"action=\"comment/submitcomment.php\"onSubmit=\" return form_Validator(this)\">
<tablewidth=\"100%\">
<tr>
<thcolspan=\"2\"><h3class=\"formtitle\">Leave your comment:</h3></th>
</tr>
<tr>
 
<thscope=\"row\"><pclass=\"req\">Name:</p></th>
<td><inputclass=\"form\"tabindex=\"1\"id=\"name\"name=\"name\" /></td>
</tr>
<tr>
<thscope=\"row\"><pclass=\"opt\">Email:</p></th>
<td><inputclass=\"form\"tabindex=\"2\"id=\"email\"name=\"email\" /></td>
</tr>
<tr>
 
<thscope=\"row\"><pclass=\"opt\">URL:</p></th>
<td><inputclass=\"form\"tabindex=\"3\"id=\"url\"name=\"url\" /></td>
</tr>
<trvalign=\"top\">
<thscope=\"row\"><pclass=\"req\">Comments:</p><br /></th>
<td><textareaclass=\"formtext\"tabindex=\"4\"id=\"message\"name=\"message\"rows=\"10\"cols=\"50\"></textarea></td>
</tr>
 
<tr>
<td>[B][I]&nbsp[/I][/B];</td>
<td><inputtype=\"submit\"name=\"post\"class=\"submit\"value=\"Submit Comment\" /><br />
<p>Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted. </p>
 
 
 
</td>
</tr>
 
 
 
</table>
<inputtype=\"hidden\"name=\"tuturl\"value=\"$tuturl\" />
<inputtype=\"hidden\"name=\"tutid2\"value=\"$tutid2\" />
</form>

I thought that just adding a new line and inserting the relevant part would work, but it just won't! I have tried this for days now and would be really grateful if someone knew how to do it? :eek:

Can u post the code wherein you actually merged the two so we could get a clear picture of how you inserted the captcha code into your comment.php script. It's hard to see where you might have gone wrong if we can't see the actual code.

Thank you very much for your reply.

I have given up on that particular script, and tried to install the captcha used by the author of my comment script (see here), which is the standard captcha v. 0.9.

I think my trouble is the integration because the captcha works seperately but I think the issue might be calling up php commands within the form that is in itself contained in a php file.

I am going to include and attach (1) test.php and (2)inc_rate.php (3) captcha.php.
I am trying to replicate the incorporation of captche in inc_rate.php

I have bolded and italiced my additions in the <form> part of inc_rate.php. Unfortunately, I get no more than a black bar as you can see on my .html page. :rolleyes:

This is the test.php where the captcha works in a simple form:

<html>
<head>
<title>captcha.php testing</title>
<style>
html {
border-left: 30pxsolid#222222;
}
input,textarea {
background: #333333;
color: #dddddd;
border: 2pxsolid#555555;
}
.captcha {
border: 2pxdashed: #331111;
background: #110000;
padding: 5px;
}
form {
border: 1pxdashed#551111;
padding: 2px;
}
</style>
</head>
<bodybgcolor="#000000"text="#ffffff">
<h1>CAPTCHA Test</h1>
<?php
define("CAPTCHA_INVERSE", 1);
include"captcha.php";
?>

<formaction="_test.1.php">
(we have an example input &lt;form&gt; here)<br>
<textareacols=50rows=3><?php
$res = captcha::check();
if (isset($res)) {
if ($res) {
$msg = "SUCCESS!!";
}
else {
$msg = "FAILED.";
}
for ($n=0; $n<5; $n++) {
echo"$msg\n";
}
}
?></textarea>
<br>
<br>
<?php
echocaptcha::form();
?>
<br>
<inputtype="submit"value="Test &amp; Save">
</form>

<br>
<br>

This is just an example. It's function-less form, which appears over
and over again. You'd typically also want to provide a more senseful
error message, if captcha::test() fails.

<br>
<br>

</body>
</html>

The following is my comment script php file - inc_rate.php:

<?
//PleasesetthefollowingvariablesforyourMySQLdatabase:
//PleasesetthefollowingvariablesforyourMySQLdatabase:
//itishighlyrecommendedthatyourestrictaccessfortheuserforsecurityreasons
//itonlyneeds"INSERT"privileges

$db_hostname = "localhost"; //usually"localhost be default"
$db_username = "wa4398_3"; //yourusername
$db_pass = "XXXXXXXXX"; //thepasswordforyouruser
$db_name = "wa4398_db3"; //thenameofthedatabase


/*MYSQLDATABASECONNECTION/ TRACKINGFUNCTIONS
--------------------------------------*/
// connecttodatabase
$dbh = mysql_connect ($db_hostname, $db_username, $db_pass) ordie ('Icannotconnecttothedatabasebecause: ' . mysql_error());
mysql_select_db ($db_name);



//forsecurity, htmlisnotallowed, sobbcodeisusedforformatting

//START3rdPARTYCODE: Ididnotwritethis
/************************************************/
/* BBCodev1.0a */
/* Date: 03/2003 */
/* */
/* Asimpleandeffectivescriptthat */
/* allowsyoutoimplementbbcodetype */
/* behaviouronyourphpwebsite. */
/* */
/* Contact: bbcode@netgem.freeserve.co.uk */
/* */
/* Usage: */
/* */
/* Putthefollowinglineatthetopof */
/* thepageyouwanttohavethebbocde */
/* in...(assumesbothpagesareinthe */
/* folder */
/* */
/* include("bbCode.php"); */
/* */
/* Passthetexttothefunction: */
/* */
/* $mytext = BBCode("This is my BBCODE"); */
/* or */
/* $mytext = "This is my text"; */
/* $mytext = BBCode($mytext); */
/* */
/* echo $mytext; */
/* */
/************************************************/
?>
<styletype="text/css">
<!--
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
}

.bold {
font-weight: bold;
}

.italics {
font-style: italic;
}

.underline {
text-decoration: underline;
}

.strikethrough {
text-decoration: line-through;
}

.overline {
text-decoration: overline;
}

.sized {
text-size:
}

.quotecodeheader {
font-family: Verdana, arial, helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
}

.codebody {
background-color: #FFFFFF;
font-family: Couriernew, courier, mono;
font-size: 12px;
color: #006600;
border: 1pxsolid#BFBFBF;
}

.quotebody {
background-color: #FFFFFF;
font-family: Couriernew, courier, mono;
font-size: 12px;
color: #660002;
border: 1pxsolid#BFBFBF;
}

.listbullet {
list-style-type: disc;
list-style-position: inside;
}

.listdecimal {
list-style-type: decimal;
list-style-position: inside;
}

.listlowerroman {
list-style-type: lower-roman;
list-style-position: inside;
}

.listupperroman {
list-style-type: upper-roman;
list-style-position: inside;
}

.listloweralpha {
list-style-type: lower-alpha;
list-style-position: inside;
}

.listupperalpha {
list-style-type: upper-alpha;
list-style-position: inside;
}
-->
</style>









<?php
//Localcopy

functionBBCode($Text)
{
// ReplaceanyhtmlbracketswithHTMLEntitiestopreventexecutingHTMLorscript
// Don'tusestrip_tagsherebecauseitbreaks [url] searchbyreplacing & withamp
$Text = str_replace("<", "&lt;", $Text);
$Text = str_replace(">", "&gt;", $Text);



// SetuptheparametersforaURLsearchstring
$URLSearchString = " a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'";
// SetuptheparametersforaMAILsearchstring
$MAILSearchString = $URLSearchString . " a-zA-Z0-9\.@";

//NonBBURLSearch
//$Text = eregi_replace("([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\" target=\"_blank\" target=\"_new\">\\1://\\2\\3</a>", $Text);
//$Text = eregi_replace("(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))", "<a href=\"mailto:\\1\" target=\"_new\">\\1</a>", $Text);
if (substr($Text,0, 7) == "http://"){
$Text = eregi_replace("([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\">\\1://\\2\\3</a>", $Text);
// Convertnewlinecharstohtml<br /> tags
$Text = nl2br($Text);
} else {
// Perform URL Search
$Text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/", '<ahref="javascript:go(\'$1\',\'new\')">$1</a>', $Text);
$Text = preg_replace("(\[url\=([$URLSearchString]*)\](.+?)\[/url\])", '<ahref="javascript:go(\'$1\',\'new\')">$2</a>', $Text);
//$Text = preg_replace("(\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[/url\])", '<ahref="$1"target="_blank">$2</a>', $Text);
// Convert new line chars to html <br /> tags
$Text = nl2br($Text);
}
// Perform MAIL Search
$Text = preg_replace("(\[mail\]([$MAILSearchString]*)\[/mail\])", '<ahref="mailto:$1">$1</a>', $Text);
$Text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.+?)\[\/mail\]/", '<ahref="mailto:$1">$2</a>', $Text);

// Check for bold text
$Text = preg_replace("(\[b\](.+?)\[\/b])is",'<spanclass="bold">$1</span>',$Text);

// Check for Italics text
$Text = preg_replace("(\[i\](.+?)\[\/i\])is",'<spanclass="italics">$1</span>',$Text);

// Check for Underline text
$Text = preg_replace("(\[u\](.+?)\[\/u\])is",'<spanclass="underline">$1</span>',$Text);

// Check for strike-through text
$Text = preg_replace("(\[s\](.+?)\[\/s\])is",'<spanclass="strikethrough">$1</span>',$Text);

// Check for over-line text
$Text = preg_replace("(\[o\](.+?)\[\/o\])is",'<spanclass="overline">$1</span>',$Text);

// Check for colored text
$Text = preg_replace("(\[color=(.+?)\](.+?)\[\/color\])is","<spanstyle=\"color: $1\">$2</span>",$Text);

// Check for sized text
$Text = preg_replace("(\[size=(.+?)\](.+?)\[\/size\])is","<spanstyle=\"font-size: $1px\">$2</span>",$Text);

// Check for list text
$Text = preg_replace("/\[list\](.+?)\[\/list\]/is", '<ulclass="listbullet">$1</ul>' ,$Text);
$Text = preg_replace("/\[list=1\](.+?)\[\/list\]/is", '<ulclass="listdecimal">$1</ul>' ,$Text);
$Text = preg_replace("/\[list=i\](.+?)\[\/list\]/s", '<ulclass="listlowerroman">$1</ul>' ,$Text);
$Text = preg_replace("/\[list=I\](.+?)\[\/list\]/s", '<ulclass="listupperroman">$1</ul>' ,$Text);
$Text = preg_replace("/\[list=a\](.+?)\[\/list\]/s", '<ulclass="listloweralpha">$1</ul>' ,$Text);
$Text = preg_replace("/\[list=A\](.+?)\[\/list\]/s", '<ulclass="listupperalpha">$1</ul>' ,$Text);
$Text = str_replace("
[*]", "<li>", $Text);

// Check for font change text
$Text = preg_replace("(\(.+?)\[\/font\])","<spanstyle=\"font-family: $1;\">$2</span>",$Text);

// Declare the format for [code] layout
$CodeLayout = '<tablewidth="90%"border="0"align="center"cellpadding="0"cellspacing="0">
<tr>
<tdclass="quotecodeheader"> Code:</td>
</tr>
<tr>
<tdclass="codebody">$1</td>
</tr>
</table>';
// Check for [code] text
$Text = preg_replace("/\[code\](.+?)\[\/code\]/is","$CodeLayout", $Text);

// Declare the format for [quote] layout
$QuoteLayout = '<tablewidth="90%"border="0"align="center"cellpadding="0"cellspacing="0">
<tr>
<tdclass="quotecodeheader"> Quote:</td>
</tr>
<tr>
<tdclass="quotebody">$1</td>
</tr>
</table>';

// Check for [code] text

$Text = preg_replace("/\[quote\](.+?)\[\/quote\]/is","$QuoteLayout", $Text);

// Images
// [img]pathtoimage[/img]
$Text = preg_replace("/\[img\](.+?)\[\/img\]/", '<imgsrc="$1">', $Text);

// [img=widthxheight]image source[/img]
$Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.+?)\[\/img\]/", '<imgsrc="$3"height="$2"width="$1">', $Text);

return $Text;
}


//END 3rd PARTY CODE

//quick script to make the data look nice
function formatDate($val)
{
list($date, $time) = explode(" ", $val);
list($year, $month, $day) = explode("-", $date);
list($hour, $minute, $second) = explode (":", $time);
return date("l, m.j.y @ H:ia", mktime($hour, $minute, $second, $month, $day, $year));
}



function getComments($tutid){
//creates a function that can easily be called from any page

//create the css code to make the form look good. You can edit this to change colors, etc:
echo "
<style>
/*COMMENTS
*------------------------------------*/

.postedby {
padding: 00018px;
background: url(images/abullet.gif) no-repeat04px;
}

h3.formtitle {
margin : 0px0px0px0px;
border-bottom: 1pxdotted#ccc;
padding-bottom: 8px;
}

.commentbody {
border-top: 1pxdotted#ccc;
}

/*gray box*/
.submitcomment, #submitcomment, #currentcomments, #rating, .textad {
background-color: #F5F5F5;
border: 1pxdotted#ccc;
padding: 5px;
padding: 5px;
margin: 20px0px0px0px;
}


/*FORMS
*------------------------------------*/

.form {
background-color: #FAFAFA;
border: solid1px#C6C6C6;
padding: 2px;
}

.formtext {
background-color: #FAFAFA;
border: solid1px#C6C6C6;
padding: 2px;
border-bottom: 1pxdotted#ccc
}

.form:hover, .formtext:hover {
background: white;
}

.form:focus, .formtext:focus {
background: white;
border: solid1px#000000;
}

.submit {
background-color: #D3D3D3;
border: solid1px#C6C6C6;
border-right: solid1px#9A9A9A;
border-bottom: solid1px#9A9A9A;
}

.submit:hover, .submit:focus {
background: #EDEDED;
}

html {
border-left: 30pxsolid#222222;
}
input,textarea {
background: #333333;
color: #dddddd;
border: 2pxsolid#555555;
}
.captcha {
border: 2pxdashed: #331111;
background: #110000;
padding: 5px;
}
form {
border: 1pxdashed#551111;
padding: 2px;
}
</style>


";
//fetch all comments from database where the tutorial number is the one you are asking for
$commentquery = mysql_query("SELECT * FROM comments WHERE tutorialid='$tutid' ORDER BY date DESC") or die(mysql_error()); 
//find the number of comments
$commentNum = mysql_num_rows($commentquery);
//create a headline
echo "<divid=\"currentcomments\"class=\"submitcomment\"><h3class=\"formtitle\">Current Comments</h3>\n";
echo $commentNum . " comments so far (<ahref=\"#post\">post your own</a>)\n";
//for each comment in the database in the right category number...
while($commentrow = mysql_fetch_row($commentquery)){
//for security, parse through the bbcode script
//the number corresponds to the column (the message is always stored in column 4
//COUTING STARTS at 0!!!
$commentbb = BBCode($commentrow[4]);
//create the right date format
$commentDate = formatDate($commentrow[6]);

echo "<divclass=\"commentbody\"id=\"$commentrow[0]\">\n
<p>$commentbb</p>\n
<pclass=\"postedby\">Posted by ";
if($commentrow[3]){
echo "<ahref=\"$commentrow[3]\">$commentrow[2]</a> ";
} else {
echo "$commentrow[2] ";
}
echo "on $commentDate | #$commentrow[0]</p>\n
\n</div>";

}
echo "</div>";
}

function submitComments($tutid2,$tuturl){
//a javascript script to make sure all the required fields are filled in
?>
<script language="javascript">

function form_Validator(form)
{

if (form.name.value == "")
{
alert("Please enter your name.");
form.name.focus();
return (false);
}

if (form.message.value == "")
{
alert("Please enter your message.");
form.message.focus();
return (false);
}

return (true);
    }
//-->
</script>



<?php
//createtheformtosubmitcomments
//youcanaddmorefields, butmakesureyouaddthemtothedbtableandthepage, submitcomment.php
echo"
<aname=\"post\"></a>
<divid=\"submitcomment\"class=\"submitcomment\">

<?php
define(\"CAPTCHA_INVERSE\", 1);
include \"captcha.php\";
?>


<formname=\"submitcomment\"method=\"post\"action=\"submitcomment.php\"onSubmit=\" return form_Validator(this)\">
<tablewidth=\"100%\">
<tr>
<thcolspan=\"2\"><h3class=\"formtitle\">Leave your comment:</h3></th>
</tr>
<tr>

<thscope=\"row\"><pclass=\"req\">Name:</p></th>
<td><inputclass=\"form\"tabindex=\"1\"id=\"name\"name=\"name\" /></td>
</tr>
<tr>
<thscope=\"row\"><pclass=\"opt\">Email:</p></th>
<td><inputclass=\"form\"tabindex=\"2\"id=\"email\"name=\"email\" /></td>
</tr>
<tr>

<thscope=\"row\"><pclass=\"opt\">URL:</p></th>
<td><inputclass=\"form\"tabindex=\"3\"id=\"url\"name=\"url\" /></td>
</tr>
<trvalign=\"top\">
<thscope=\"row\"><pclass=\"req\">Comments:</p><br /></th>
<td><textareaclass=\"formtext\"tabindex=\"4\"id=\"message\"name=\"message\"rows=\"10\"cols=\"50\"></textarea></td>
</tr>

<tr><tdwidth=\"50\">&nbsp;</td><tdstyle=\"width: 200px; display: block;\"><divclass=\"captcha\">
<?php
echocaptcha::form();
?>
</div></td></tr>


Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted. </p></tr>







<inputtype=\"hidden\"name=\"tuturl\"value=\"$tuturl\" />
<inputtype=\"hidden\"name=\"tutid2\"value=\"$tutid2\" />
</form>



</div>
";
}
?>

Edited 3 Years Ago by Dani: Formatting fixed

Attachments
<?php
/*
   Does emit a CAPTCHA graphic and form fields, which allows to tell real
   people from bots.
   Though a textual description is generated as well, this sort of access
   restriction will knock out visually impaired users, and frustrate all
   others anyhow. Therefore this should only be used as last resort for
   defending against spambots. Because of the readable text and the used
   colorspaces this is a weak implementation, not completely OCR-secure.

   captcha::form() will return a html string to be inserted into textarea/
   [save] <forms> and alike. User input is veryfied with captcha::check().
   You should leave the sample COLLEGE.ttf next to this script, else you
   have to define the _FONT_DIR constant correctly. Use only 1 font type.
   
   Creates temporary files, which however get purged automatically after
   four hours.

   Public Domain, available via http://freshmeat.net/p/captchaphp
*/


#-- config
define("EWIKI_FONT_DIR", dirname(__FILE__));  // which fonts to use
define("CAPTCHA_INVERSE", 0);                 // white or black(=1)
define("CAPTCHA_TIMEOUT", 5000);              // in seconds (=max 4 hours)
define("CAPTCHA_MAXSIZE", 4500);              // preferred image size
define("CAPTCHA_COOKIE", "captcha_solved");   // to unlock captcha protection
define("CAPTCHA_DATA_URLS", 0);               // RFC2397-URLs exclude MSIE users
define("CAPTCHA_TEMP_DIR", "/tmp/captcha");
define("CAPTCHA_BASE_URL", "http://$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]/" . substr(realpath(__FILE__), strlen($_SERVER["DOCUMENT_ROOT"])));


/* static - (you could instantiate it, but...) */
class captcha {


   /* gets parameter from $_REQUEST[] array (POST vars) and so can
      verify input, @returns boolean
   */
   function check() {
      $to = (int)(time()/1000000);
      if ($_COOKIE[CAPTCHA_COOKIE] == $to) {
         return(true);
      }
      if (($hash = $_REQUEST["captcha_hash"])
      and ($pw = trim($_REQUEST["captcha_input"]))) {
         $r = (captcha::hash($pw)==$hash) || (captcha::hash($pw,-1)==$hash);
         if ($r) {
            setcookie(CAPTCHA_COOKIE, $to, time()+1000000);
         }
         return($r);
      }
   }

   
   /* yields <input> fields html string (no complete form), with captcha
      image already embedded as data:-URI
   */
   function form($title="&rarr; retype that here", $more="<small>Enter the correct letters and numbers from the image into the text box. This small test serves as access restriction against malicious bots. Simply reload the page if this graphic is too hard to read.</small>") {

      #-- stop if user already verified
      if ($_COOKIE[CAPTCHA_COOKIE] == (int)(time()/1000000)) {
         return "";
      }

      #-- prepare image text
      $pw = captcha::mkpass();
      $hash = captcha::hash($pw);
      $alt = htmlentities(captcha::textual_riddle($pw));

      #-- image
      $img = captcha::image($pw, 200, 60, CAPTCHA_INVERSE, CAPTCHA_MAXSIZE);
      if (CAPTCHA_DATA_URLS && !strpos("MSIE", $_SERVER["HTTP_USER_AGENT"])) {
         $img_fn = "data:image/jpeg;base64," . base64_encode($img);
      }
      else {
         $img_fn = CAPTCHA_BASE_URL . "?_tcf=" . captcha::store_image($img);
      }
      
      #-- emit html form
      $html = 
        '<table border="0" summary="captcha input"><tr>'
      . '<td><img name="captcha_image" id="captcha_image" src="' .$img_fn. '" height="60" width="200" alt="'.$alt. '" /></td>'
      . '<td>'.$title. '<br/><input name="captcha_hash" type="hidden" value="'.$hash. '" />'
      . '<input name="captcha_input" type="text" size="7" maxlength="16" style="height:46px; font-size:34px; font-weight:450;" />'
      . '</td><td>'.$more.'</td>'
      . '</tr></table>';
      $html = "<div class=\"captcha\">$html</div>";
      return($html);
   }


   /* generates alternative (non-graphic), human-understandable
      representation of the passphrase
   */
   function textual_riddle($phrase) {
      $symbols0 = '"\'-/_:';
      $symbols1 = array("\n,", "\n;", ";", "\n&", "\n-", ",", ",", "\nand then", "\nfollowed by", "\nand", "\nand not a\n\"".chr(65+rand(0,26))."\",\nbut");
      $s = "Guess the letters and numbers\n(passphrase riddle)\n--\n";
      for ($p=0; $p<strlen($phrase); $p++) {
         $c = $phrase[$p];
         $add = "";
         #-- asis
         if (!rand(0,3)) {
            $i = $symbols0[rand(0,strlen($symbols0)-1)];
            $add = "$i$c$i";
         }
         #-- letter
         elseif ($c >= 'A') {
            $type = ($c >= 'a' ? "small " : "");
            do {
               $n = rand(-3,3);
               $c2 = chr((ord($c) & 0x5F) + $n);
            }
            while (($c2 < 'A') || ($c2 > 'Z'));
            if ($n < 0) {
               $n = -$n;
               $add .= "$type'$c2' +$n letters";
            }
            else {
               $add .= "$n chars before $type$c2";
            }
         }
         #-- number
         else {
            $add = "???";
            $n = (int) $c;
            do {
               do { $x = rand(1, 10); } while (!$x);
               $op = rand(0,11);
               if ($op <= 2) {
                  $add = "($add * $x)"; $n *= $x;
               }
               elseif ($op == 3) {
                  $x = 2 * rand(1,2);
                  $add = "($add / $x)"; $n /= $x;
               }
               elseif ($sel % 2) {
                  $add = "($add + $x)"; $n += $x;
               }
               else {
                  $add = "($add - $x)"; $n -= $x;
               }
            }
            while (rand(0,1));
            $add .= " = $n";
         }
         $s .= "$add";
         $s .= $symbols1[rand(0,count($symbols1)-1)] . "\n";
      }
      return($s);
   }


   /* returns jpeg file stream with unscannable letters encoded
      in front of colorful disturbing background
   */
   function image($phrase, $width=200, $height=60, $inverse=0, $maxsize=0xFFFFF) {
   
      #-- initialize in-memory image with gd library
      srand(microtime()*21017);
      $img = imagecreatetruecolor($width, $height);
      $R = $inverse ? 0xFF : 0x00;
      imagefilledrectangle($img, 0,0, $width,$height, captcha::random_color($img, 222^$R, 255^$R));
      $c1 = rand(150^$R, 185^$R);
      $c2 = rand(195^$R, 230^$R);
      
      #-- configuration
      $fonts = array(
        // "COLLEGE.ttf",
      );
      $fonts += glob(EWIKI_FONT_DIR."/*.ttf");
      
      #-- encolour bg
      $wd = 20;
      $x = 0;
      while ($x < $width) {
         imagefilledrectangle($img, $x, 0, $x+=$wd, $height, captcha::random_color($img, 222^$R, 255^$R));
         $wd += max(10, rand(0, 20) - 10);
      }

      #-- make interesting background I, lines
      $wd = 4;
      $w1 = 0;
      $w2 = 0;
      for ($x=0; $x<$width; $x+=(int)$wd) {
         if ($x < $width) {   // verical
            imageline($img, $x+$w1, 0, $x+$w2, $height-1, captcha::random_color($img,$c1,$c2));
         }
         if ($x < $height) {  // horizontally ("y")
            imageline($img, 0, $x-$w2, $width-1, $x-$w1, captcha::random_color($img,$c1,$c2));
         }
         $wd += rand(0,8) - 4;
         if ($wd < 1) { $wd = 2; }
         $w1 += rand(0,8) - 4;
         $w2 += rand(0,8) - 4;
         if (($x > $height) && ($y > $height)) {
            break;
         }
      }
      
      #-- more disturbing II, random letters
      $limit = rand(30,90);
      for ($n=0; $n<$limit; $n++) {
         $letter = "";
         do {
            $letter .= chr(rand(31,125)); // random symbol
         } while (rand(0,1));
         $size = rand(5, $height/2);
         $half = (int) ($size / 2);
         $x = rand(-$half, $width+$half);
         $y = rand(+$half, $height);
         $rotation = rand(60, 300);
         $c1  = captcha::random_color($img, 130^$R, 240^$R);
         $font = $fonts[rand(0, count($fonts)-1)];
         imagettftext($img, $size, $rotation, $x, $y, $c1, $font, $letter);
      }

      #-- add the real text to it
      $len = strlen($phrase);
      $w1 = 10;
      $w2 = $width / ($len+1);
      for ($p=0; $p<$len; $p++) {
         $letter = $phrase[$p];
         $size = rand(18, $height/2.2);
         $half = (int) $size / 2;
         $rotation = rand(-33, 33);
         $y = rand($size+3, $height-3);
         $x = $w1 + $w2*$p;
         $w1 += rand(-$width/90, $width/40);  // @BUG: last char could be +30 pixel outside of image
         $font = $fonts[rand(0, count($fonts)-1)];
         $r=rand(30,99); $g=rand(30,99); $b=rand(30,99); // two colors for shadow
         $c1  = imagecolorallocate($img, $r*1^$R, $g*1^$R, $b*1^$R);
         $c2  = imagecolorallocate($img, $r*2^$R, $g*2^$R, $b*2^$R);
         imagettftext($img, $size, $rotation, $x+1, $y, $c2, $font, $letter);
         imagettftext($img, $size, $rotation, $x, $y-1, $c1, $font, $letter);
      }

      #-- let JFIF stream be generated
      $quality = 67;
      $s = array();
      do {
         ob_start(); ob_implicit_flush(0);
         imagejpeg($img, "", (int)$quality);
         $jpeg = ob_get_contents(); ob_end_clean();
         $size = strlen($jpeg);
         $s_debug[] = ((int)($quality*10)/10) . "%=$size";
         $quality = $quality * ($maxsize/$size) * 0.93 - 1.7;  // -($quality/7.222)*
      }
      while (($size > $maxsize) && ($quality >= 16));
      imagedestroy($img);
#print_r($s_debug);
      return($jpeg);
   }


   /* helper code */
   function random_color($img, $a,$b) {
      return imagecolorallocate($img, rand($a,$b), rand($a,$b), rand($a,$b));
   }
   
   
   /* creates temporary file, returns basename */
   function store_image($data) {
      $dir = CAPTCHA_TEMP_DIR;
      $id = md5($data);
   
      #-- create temp dir
      if (!file_exists($dir)) {
         mkdir($dir) && chmod($dir, 0777);
      }
      
      #-- remove stale files
      if ($dh = opendir($dir)) {
         $t_kill = time() - CAPTCHA_TIMEOUT;
         while($fn = readdir($dh)) if ($fn[0] != ".") {
            if (filemtime("$dir/$fn") < $t_kill) {
               unlink("$dir/$fn");
            }
         }
      }
      
      #-- store file
      fwrite($f = fopen("$dir/$id", "wb"), $data) && fclose($f);
      return($id);
   }

   /* sends it */
   function get_image
<?
//Please set the following variables for your MySQL database:
//Please set the following variables for your MySQL database:
//it is highly recommended that you restrict access for the user for security reasons
//it only needs "INSERT" privileges

$db_hostname = "localhost";  //usually "localhost be default"
$db_username = "wa4398_3";  //your user name
$db_pass = "XXXXXXXX";  //the password for your user
$db_name = "wa4398_db3";  //the name of the database


/*MYSQL DATABASE CONNECTION/ TRACKING FUNCTIONS
--------------------------------------*/
// connect to database
$dbh = mysql_connect ($db_hostname, $db_username, $db_pass) or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ($db_name);



//for security, html is not allowed, so bbcode is used for formatting

//START 3rd PARTY CODE:  I did not write this
/************************************************/
/*              BBCode v1.0a                    */
/*              Date: 03/2003                   */
/*                                              */
/*      A simple and effective script that      */
/*      allows you to implement bbcode type     */
/*      behaviour on your php website.          */
/*                                              */
/*      Contact: bbcode@netgem.freeserve.co.uk  */
/*                                              */
/*      Usage:                                  */
/*                                              */
/*      Put the following line at the top of    */
/*      the page you want to have the bbocde    */
/*      in...(assumes both pages are in the     */
/*      folder                                  */
/*                                              */
/*      include("bbCode.php");                  */
/*                                              */
/*      Pass the text to the function:          */
/*                                              */
/*      $mytext = BBCode("This is my BBCODE");  */
/*      or                                      */
/*      $mytext = "This is my text";            */
/*      $mytext = BBCode($mytext);              */
/*                                              */
/*      echo $mytext;                           */
/*                                              */
/************************************************/
?>
<style type="text/css">
<!--
body    {
        font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 12px;
}

.bold {
        font-weight: bold;
}

.italics {
        font-style: italic;
}

.underline {
        text-decoration: underline;
}

.strikethrough {
        text-decoration: line-through;
}

.overline {
        text-decoration: overline;
}

.sized {
        text-size:
}

.quotecodeheader {
        font-family: Verdana, arial, helvetica, sans-serif;
        font-size: 12px;
        font-weight: bold;
}

.codebody {
        background-color: #FFFFFF;
    font-family: Courier new, courier, mono;
    font-size: 12px;
    color: #006600;
    border: 1px solid #BFBFBF;
}

.quotebody {
        background-color: #FFFFFF;
    font-family: Courier new, courier, mono;
    font-size: 12px;
    color: #660002;
        border: 1px solid #BFBFBF;
}

.listbullet {
        list-style-type: disc;
        list-style-position: inside;
}

.listdecimal {
        list-style-type: decimal;
        list-style-position: inside;
}

.listlowerroman {
        list-style-type: lower-roman;
        list-style-position: inside;
}

.listupperroman {
        list-style-type: upper-roman;
        list-style-position: inside;
}

.listloweralpha {
        list-style-type: lower-alpha;
        list-style-position: inside;
}

.listupperalpha {
        list-style-type: upper-alpha;
        list-style-position: inside;
}
-->
</style>









<?php
        //Local copy

        function BBCode($Text)
            {
                // Replace any html brackets with HTML Entities to prevent executing HTML or script
            // Don't use strip_tags here because it breaks [url] search by replacing & with amp
            $Text = str_replace("<", "&lt;", $Text);
            $Text = str_replace(">", "&gt;", $Text);



            // Set up the parameters for a URL search string
            $URLSearchString = " a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'";
            // Set up the parameters for a MAIL search string
            $MAILSearchString = $URLSearchString . " a-zA-Z0-9\.@";

                        //Non BB URL Search
                        //$Text = eregi_replace("([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\" target=\"_blank\" target=\"_new\">\\1://\\2\\3</a>", $Text);
                //$Text = eregi_replace("(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))", "<a href=\"mailto:\\1\" target=\"_new\">\\1</a>", $Text);
                if (substr($Text,0, 7) == "http://"){
            $Text = eregi_replace("([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\">\\1://\\2\\3</a>", $Text);
                 // Convert new line chars to html <br /> tags
            $Text = nl2br($Text);
                        } else {
            // Perform URL Search
            $Text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/", '<a href="javascript:go(\'$1\',\'new\')">$1</a>', $Text);
            $Text = preg_replace("(\[url\=([$URLSearchString]*)\](.+?)\[/url\])", '<a href="javascript:go(\'$1\',\'new\')">$2</a>', $Text);
                        //$Text = preg_replace("(\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[/url\])", '<a href="$1" target="_blank">$2</a>', $Text);
                         // Convert new line chars to html <br /> tags
            $Text = nl2br($Text);
                        }
            // Perform MAIL Search
            $Text = preg_replace("(\[mail\]([$MAILSearchString]*)\[/mail\])", '<a href="mailto:$1">$1</a>', $Text);
            $Text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.+?)\[\/mail\]/", '<a href="mailto:$1">$2</a>', $Text);

            // Check for bold text
            $Text = preg_replace("(\[b\](.+?)\[\/b])is",'<span class="bold">$1</span>',$Text);

            // Check for Italics text
            $Text = preg_replace("(\[i\](.+?)\[\/i\])is",'<span class="italics">$1</span>',$Text);

            // Check for Underline text
            $Text = preg_replace("(\[u\](.+?)\[\/u\])is",'<span class="underline">$1</span>',$Text);

            // Check for strike-through text
            $Text = preg_replace("(\[s\](.+?)\[\/s\])is",'<span class="strikethrough">$1</span>',$Text);

            // Check for over-line text
            $Text = preg_replace("(\[o\](.+?)\[\/o\])is",'<span class="overline">$1</span>',$Text);

            // Check for colored text
            $Text = preg_replace("(\[color=(.+?)\](.+?)\[\/color\])is","<span style=\"color: $1\">$2</span>",$Text);

            // Check for sized text
            $Text = preg_replace("(\[size=(.+?)\](.+?)\[\/size\])is","<span style=\"font-size: $1px\">$2</span>",$Text);

            // Check for list text
            $Text = preg_replace("/\[list\](.+?)\[\/list\]/is", '<ul class="listbullet">$1</ul>' ,$Text);
            $Text = preg_replace("/\[list=1\](.+?)\[\/list\]/is", '<ul class="listdecimal">$1</ul>' ,$Text);
            $Text = preg_replace("/\[list=i\](.+?)\[\/list\]/s", '<ul class="listlowerroman">$1</ul>' ,$Text);
            $Text = preg_replace("/\[list=I\](.+?)\[\/list\]/s", '<ul class="listupperroman">$1</ul>' ,$Text);
            $Text = preg_replace("/\[list=a\](.+?)\[\/list\]/s", '<ul class="listloweralpha">$1</ul>' ,$Text);
            $Text = preg_replace("/\[list=A\](.+?)\[\/list\]/s", '<ul class="listupperalpha">$1</ul>' ,$Text);
            $Text = str_replace("[*]", "<li>", $Text);

            // Check for font change text
            $Text = preg_replace("(\[font=(.+?)\](.+?)\[\/font\])","<span style=\"font-family: $1;\">$2</span>",$Text);

            // Declare the format for [code] layout
            $CodeLayout = '<table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td class="quotecodeheader"> Code:</td>
                                </tr>
                                <tr>
                                    <td class="codebody">$1</td>
                                </tr>
                           </table>';
            // Check for [code] text
            $Text = preg_replace("/\[code\](.+?)\[\/code\]/is","$CodeLayout", $Text);

            // Declare the format for [quote] layout
            $QuoteLayout = '<table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td class="quotecodeheader"> Quote:</td>
                                </tr>
                                <tr>
                                    <td class="quotebody">$1</td>
                                </tr>
                           </table>';

            // Check for [code] text
            $Text = preg_replace("/\[quote\](.+?)\[\/quote\]/is","$QuoteLayout", $Text);

            // Images
            // [img]pathtoimage[/img]
            $Text = preg_replace("/\[img\](.+?)\[\/img\]/", '<img src="$1">', $Text);

            // [img=widthxheight]image source[/img]
            $Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.+?)\[\/img\]/", '<img src="$3" height="$2" width="$1">', $Text);

                return $Text;
                }


//END 3rd PARTY CODE

//quick script to make the data look nice
function formatDate($val)
  {
      list($date, $time) = explode(" ", $val);
      list($year, $month, $day) = explode("-", $date);
      list($hour, $minute, $second) = explode (":", $time);
      return date("l, m.j.y @ H:ia", mktime($hour, $minute, $second, $month, $day, $year));
  }



function getComments($tutid){
//creates a function that can easily be called
<html>
<head>
  <title>captcha.php testing</title>
  <style>
html {
   border-left: 30px solid #222222;
}
input,textarea {
   background: #333333;
   color: #dddddd;
   border: 2px solid #555555;
}
.captcha {
   border: 2px dashed: #331111;
   background: #110000;
   padding: 5px;
}
form {
   border: 1px dashed #551111;
   padding: 2px;
}
  </style>
</head>
<body bgcolor="#000000" text="#ffffff">
<h1>CAPTCHA Test</h1>
<?php
  define("CAPTCHA_INVERSE", 1);
  include "captcha.php";
?>

<form action="_test.1.php" >
(we have an example input &lt;form&gt; here)<br>
<textarea cols=50 rows=3><?php
  $res = captcha::check();
  if (isset($res)) {
     if ($res) {
        $msg = "SUCCESS!!";
     }
     else {
        $msg = "FAILED.";
     }
     for ($n=0; $n<5; $n++) {
        echo "$msg\n";
     }
  }
?></textarea>
<br>
<br>
<?php
  echo captcha::form();
?>
<br>
<input type="submit" value="Test &amp; Save">
</form>

<br>
<br>

This is just an example. It's function-less form, which appears over
and over again. You'd typically also want to provide a more senseful
error message, if captcha::test() fails.

<br>
<br>

</body>
</html>

Hi! I did a comparison between inc_rate.php and _test.1.php and the difference I saw was that _test.1.php used this code

$res = captcha::check();
  if (isset($res)) {
     if ($res) {
        $msg = "SUCCESS!!";
     }
     else {
        $msg = "FAILED.";
     }
     for ($n=0; $n<5; $n++) {
        echo "$msg\n";
     }

before captcha::form() was called. I couldn't run inc_rate.php on my localhost because I don't have your database so I couldn't really tell, but that's the only difference I see in the scripts based on what you posted.

Thanks so muc for your help! The basic problem is that the captcha does not show up.

I think there may be an issue with calling a .php file from a .html file when the .php file contains <?php ... ?> within <?php ... ?> .

Should I be concerned that the .php ends in:

";
}
?>


Still very puzzled...

Ohhh now I see... I think I had the same problem before. When you include the php file on an html document, the php script does not get executed. Try converting the html into a php script and see if it works

This article has been dead for over six months. Start a new discussion instead.