1

my code: save this file as captcha.php

    <?php
ob_start();
session_start();
if(!isset($_POST['submit'])){
    echo "<form method=\"post\" action=\"captcha.php\">\n";
    echo "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\">\n";
    echo "<tr><td>Type The Letters You See Below Into the Box</td></tr>\n";
    echo "<tr><td align=\"center\"><img src=\"image.php\"></td></tr>\n";
    echo "<tr><td align=\"center\"><input type=\"text\" name=\"image\"></td></tr>\n";
    echo "<tr><td align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Check CAPTCHA\"></td></tr>\n";
    echo "</table></form>\n";
}else {
    $image = $_POST['image'];
    if ($image == $_SESSION['string'])
    {
        echo "<b>Great success!</b>\n";
    }
    else 
    {
        echo "<em>Failure!</em>\n";
    }
}
ob_end_flush();
?> 

save this file as image.php

<?php

session_start();
$img = imagecreatetruecolor(118,80);

$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);
$red = imagecolorallocate($img, 255, 0, 0);
$grey = imagecolorallocate($img,150, 150, 150);
$pink = imagecolorallocate($img, 200, 0, 150);
$yellow = imagecolorallocate($img, 255, 246, 0);

function randomString($length){
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $str = "";
    $i = 0;

        while($i <= $length){
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $str = $str . $tmp;
            $i++;
        }
    return $str;
}

for($i=1;$i<=rand(1,5);$i++){
    $color = (rand(1,2) == 1) ? $pink : $red;
    imageline($img,rand(6,90),rand(6,40), rand(6,90)+6,rand(6,40)+6, $color);
}

imagefill($img, 0, 0, $yellow);

$string = randomString(rand(4,6));
$_SESSION['string'] = $string;

imagettftext($img, 20, 10, 10, 52, $black, "calibri.ttf", $string);
imagettftext($img, 20, 10, 12, 53, $grey, "calibri.ttf", $string);

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);

?>

go to this address http://www.cufonfonts.com/en/font/12048/calibri and download the font and save it in the same root folder as the to .php files we just created.

NOTE!! THIS WILL WORK ON LOCALHOST BUT IM HAVING A PROBLEM WITH THE image.php file SHOWING UP LIKE THIS -> ����JFIF��>CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), default quality ��C $.' ",#(7),01444'9=82<.342��C 2!!22222222222222222222222222222222222222222222222222��x"�����}!1AQa"q2���#B��R��$3br� .

THIS ONLY HAPPENS WHEN I TRY AND ADD IT TO THE CMS I CREATED. ALL I NEED TO KNOW IS WHY THIS IS HAPPENING I HAVE A FEELING ITS GOT SOMETHING TO DO WITH "header("Content-type: image/png");" although i could be way wrong. please help me. by the way im am trying to add a email form and have the captcha evaluate it

this is the form i am trying to insert the code into: you can save it as form.php

<?php
$query = mysql_query("SELECT * FROM forms where id = '$formid'");

echo '<h2>'.mysql_result($query, 0, "title").'</h2>';

if(mysql_result($query, 0, "description") != "") {
    echo '<p>'.mysql_result($query, 0, "description").'</p>';
} 
error_reporting(E_ERROR);

?>
<form action="plugins/form_send.php" method="post" enctype="multipart/form-data" class="ajax" name="formplugin" id="form_<?php echo $formid; ?>">
<input name="formid" id="formid" type="hidden" value="<?php echo $formid; ?>" />
  <p><span class="required">*</span> = required fields.</p>
  <table border="0" cellspacing="5" cellpadding="5">
    <?php 
    $field_labels_col = mysql_result($query, 0, "field_label");
    $field_labels = array();
    $field_labels =(explode('|', $field_labels_col));

    $field_types_col = mysql_result($query, 0, "field_type");
    $field_types = array();
    $field_types =(explode('|', $field_types_col));

    $field_option1_col = mysql_result($query, 0, "field_option1");
    $field_option1 = array();
    $field_option1 =(explode('|', $field_option1_col));

    $field_option2_col = mysql_result($query, 0, "field_option2");
    $field_option2 = array();
    $field_option2 =(explode('|', $field_option2_col));

    $field_validtype_col = mysql_result($query, 0, "field_validtype");
    $field_validtype = array();
    $field_validtype =(explode('|', $field_validtype_col));

    $i = 0;
    while (array_key_exists($i, $field_labels))
    {
    if(!isset($title)) { $title = ''; }
    if($title != $field_labels[$i]) {

    if(isset($field_labels[$i])) { $title = $field_labels[$i]; }
    if(isset($title)) { $stripped = urlify($title); }
    if(isset($field_types[$i])) { $type = $field_types[$i]; }
    if(isset($field_option1[$i])) { $option1 = $field_option1[$i]; }
    if(isset($field_option2[$i])) { $option2 = $field_option2[$i]; }
    if(isset($field_validtype[$i])) { $valid = $field_validtype[$i]; }

    echo '<tr>';
      echo '<td align="left" valign="top">'.$title.'</td>';
      echo '<td align="left" valign="top">';

        // -- INPUT FIELDS --
        if($type == "input") {
            echo '<input name="'.$stripped.'" type="text" id="'.$stripped.'" size="'.$option1.'" maxlength="'.$option2.'" />';
            if($valid != '') { echo '<span class="required">*</span>'; }
        }

        // -- TEXT AREAS --
        if($type == "textarea") {
            echo '<textarea name="'.$stripped.'" cols="'.$option1.'" rows="size="'.$option2.'"" id="'.$stripped.'"></textarea>';
        }

        // -- DROP DOWNS --
        if($type == "dropdown") {
            echo '<select name="'.$stripped.'" id="'.$stripped.'">';
                $l = 0;
                while (array_key_exists($l, $field_labels))
                {
                $thisoption = $field_option1[$l];
                $thistitle = $field_labels[$l];
                if($thistitle == $title) {
                echo '<option value="'.$thisoption.'">'.$thisoption.'</option>';
                }
                $l++;
                }
            echo'</select>';
        }

        // -- RADIO BUTTONS --
        if($type == "radiobutton") {
            $l = 0;
            while (array_key_exists($l, $field_labels))
            {
            $thisoption = $field_option1[$l];
            $thistitle = $field_labels[$l];
            $thisstripped = urlify($field_labels[$l]);
            if($thistitle == $title) {
              echo '<label><input type="radio" name="'.$thistitle.'" id="'.$thisstripped.'" value="'.$option1.'">'.$thisoption.'</label><br />';
            }
            $l++;
            }
        }

        // -- SIMPLE YES / NO --
        if($type == "yesno") {
            echo '<label><input type="radio" name="'.$stripped.'" id="'.$stripped.'" value="Yes">Yes</label>';
            echo '<label><input type="radio" name="'.$stripped.'" id="'.$stripped.'" value="No">No</label>';
        }

        // -- FILE UPLOADS --
        if($type == "fileupload") {
            echo '<input type="file" name="'.$stripped.'" id="'.$stripped.'" size="10"> (2mb limit)';
        }

      echo '</td>';
    echo '</tr>';
    }
    $i++;
    }
?>
    <tr id="comment-div"><td colspan="2"><input name="user-comment" size="3" value="" /></td></tr>

    <tr>
        <td colspan="2">
            <?php if(mysql_result($query, 0, "submit_text") != "") { ?>
                <p><br /><?php echo mysql_result($query, 0, "submit_text"); ?></p>
            <?php } ?>
            <div id="result"><strong>Loading... please wait.</strong></div>
            <!-- <input type="submit" name="button" id="button" value="<?php echo mysql_result($query, 0, "submit_button"); ?>" /> -->



        </td>
    </tr>
  </table>
</form>
Cœur
  • 37,241
  • 25
  • 195
  • 267
Code
  • 438
  • 1
  • 5
  • 17
  • move header to the very first line of code and see how it goes. It looks like your browser doesn't pick up the header. – Tymoteusz Paul Feb 18 '14 at 11:06
  • Also try to catch `imagejpeg()`'s data using output buffering and then echo it at the end of a script. – Tomasz Kowalczyk Feb 18 '14 at 11:07
  • I have tested it is working fine in my local. – Sohil Desai Feb 18 '14 at 11:07
  • Then there is something different there! Even a " " in front of image content may make it unreadable by browser, and it's likely that he got something like that there. – Tymoteusz Paul Feb 18 '14 at 11:09
  • You can test this on http://phpfiddle.org/ I did this and it is working fine? In which program are you trying to run it? – STP38 Feb 18 '14 at 11:10
  • check your gd is enabled or not. – Sohil Desai Feb 18 '14 at 11:10
  • it works fine on local yes but when i put it into my cms it does not display – Code Feb 18 '14 at 11:11
  • guys check my code on http://phpfiddle.org/ Link id : btf-i1a is the link id, see if you can figure out where im going wrong – Code Feb 18 '14 at 12:47
  • +1 i fixed my problem, all i needed to do was set the dir root name to a variable so i could work with is easily and i saved the ttf font file to my root folder in the cms as well as i moved my image.php file to the root and then added my captcha as my plugin and pulled the image.php as well as the font ttf file from root. Thanks TEAM!!!! – Code Feb 25 '14 at 21:08

3 Answers3

1

I guess the code you posted is not the whole file: try to remove all the content before and after <?php and ?> tags. You could even remove the final tag ?> (it is a style convention adopted by many, because of this very issue).

This affects every other file you are executing: every space, newline or other content outside the PHP tags or echoed by PHP is added to the image content, and ends up with the image corruption. Also PHP notices and warnings are an issue.

For clarity, the executed files format must be:

<?php // nothing before this line
// no other PHP tags till the end
... // PHP code with no echo calls
// no closing tag

In your code, you do:

header( "Content-type: image/png" );
# ...
echo "<img src='image/png;base64," . base64_encode( $x )."'>";

You are outputting a PNG sorrounding it with HTML, which inevitably corrupts your image content. You have to remove the HTML (echo $x) and use the image from another file, f.e. with

<img src="png_generator_script.php"/>

Or use the script as HTML page, removing

header( "Content-type: image/png" );
Community
  • 1
  • 1
mdesantis
  • 8,257
  • 4
  • 31
  • 63
  • yes i cant release the code we using in our cms, but my problem is not local, if i run the captcha the image pulls in fine and every thing works but once i add it as a plugin onto our cms it tells me failed to load the given URL for the image. plus i removed all the white spacing as well. can i give you the files code to check? – Code Feb 18 '14 at 11:25
  • So the issue is in the CMS files executed when you call the image file script. You have to ensure that the files called previously the image generation script (libraries, etc) are compliant with the format I wrote in the answer. It's a check you have to do, you can't post us all the files you have. It can be a long work – mdesantis Feb 18 '14 at 11:33
  • thanks alot man much appreciated i didnt get it to work though but ill keep digging if i come right ill post it up for you guys to see – Code Feb 18 '14 at 11:40
  • Depending on your CMS code, reformatting it could be quite tough; you could try to remove unnecessary `include`s from the image script and see if the image doesn't get corrupted, in order to spot the bad files. Good work – mdesantis Feb 18 '14 at 11:50
  • iv have added the full code to http://phpfiddle.org/ the link ID is Link id : btf-i1a. would it be possible if you could maybe have a look please – Code Feb 18 '14 at 12:45
  • Ok, please put it in the question, it isn't so big – mdesantis Feb 18 '14 at 12:56
  • is there maybe a way that i can bypass: header( "Content-type: image/png" ); with another piece of source code because this is i think where my problem sits – Code Feb 18 '14 at 15:35
  • Could you please update the question adding the right code? it's not fair to other users to have an outdated question, because they should read all the comments – mdesantis Feb 18 '14 at 16:21
1

i was faced same problem . Remove all html tag it will 100% work..

save as php file .. index.php

<?php
/**
 * PHP GD
 * create a simple image with GD library
 * 
 */
//setting the image header in order to proper display the image
header("Content-Type: image/png");
//try to create an image
$im = @imagecreate(800, 600)
    or die("Cannot Initialize new GD image stream");
//set the background color of the image
$background_color = imagecolorallocate($im, 0xFF, 0xCC, 0xDD);
//set the color for the text
$text_color = imagecolorallocate($im, 133, 14, 91);
//adf the string to the image
imagestring($im, 5, 300, 300,  "I'm a pretty picture:))", $text_color);
//outputs the image as png
imagepng($im);
//frees any memory associated with the image 
imagedestroy($im);
?>

instead of...

<html>
<head>
</head>
<body>

<?php
/**
 * PHP GD
 * create a simple image with GD library
 * 
 */
//setting the image header in order to proper display the image
header("Content-Type: image/png");
//try to create an image
$im = @imagecreate(800, 600)
    or die("Cannot Initialize new GD image stream");
//set the background color of the image
$background_color = imagecolorallocate($im, 0xFF, 0xCC, 0xDD);
//set the color for the text
$text_color = imagecolorallocate($im, 133, 14, 91);
//adf the string to the image
imagestring($im, 5, 300, 300,  "I'm a pretty picture:))", $text_color);
//outputs the image as png
imagepng($im);
//frees any memory associated with the image 
imagedestroy($im);
?>
</body>
</html>
Rabby shah
  • 103
  • 1
  • 6
0

This code is working fine. I have tested it locally on chrome & firefox.

Mandeep Singh
  • 983
  • 8
  • 9
  • check my code on phpfiddle.org Link id : btf-i1a is the link id, see if you can figure out where im going wrong – Code Feb 18 '14 at 12:48
  • When i put your code in editor on http://phpfiddle.org/ and click on Run button, it gives an image as output saying 'A simple Text String'. – Mandeep Singh Feb 18 '14 at 12:58
  • try it again i was busy modifying the code but its back to the original source code – Code Feb 18 '14 at 13:12
  • if you use 'imagestring($img, 20, 10, 10, $string, $black);' imagepng( $img); imagedestroy($img); after line 39 and comment other, It gives image as output. – Mandeep Singh Feb 18 '14 at 13:30