Captcha image not loading? - php

How do I get this to load? Right now, it's not showing any image at all... I'm not really that great at creating captcha's because I usually never do this.
captcha.php:
<?php
$string = '';
for ($i = 0; $i < 5; $i++) {
// this numbers refer to numbers of the ascii table (lower case)
$string .= chr(rand(97, 122));
}
$image = imagecreatetruecolor(170, 60);
$color = imagecolorallocate($image, 200, 100, 90); // red
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, ASSETPATH."arial.ttf", $string);
header("Content-type: image/png");
imagepng($image);
?>
register.php:
<?php echo '<img src="'.ASSETPATH.'img/captcha.php" />'; ?>
My asset path IS correct because I'm using it elsewhere and it loads perfectly fine. Is the MVC format of this project messing it up somehow??

How about using one of the captcha services like recaptcha?

Judging by your use of this constant ASSETPATH both for you image URI as well as the fontfile path in imagettftext I can only assume you have your fontfile stored in the same path as that of your image?
If this is not the case, or the file could not be opened there, PHP will throw a Warning of imagettftext(): Invalid font filename. If display_errors is set to On in your php.ini (you can check phpinfo to verify this) this means the error message will be sent to the output stream along with your image data (i.e. corrupting the image data and cause your browser not to display the image). This would also prevent the headers from being modify since the error would have occurred before your call to header.
However, if display_errors is not turned on and PHP could not find the fontfile you supplied or it could not be open for any reason (e.g. permissions) the result will be a blank 170x60 PNG image.
If I test your code locally it proves to work as expected, as long as I supply PHP with the correct absolute path to my truetype font file.
For example, I have some truetype fonts on my system stored at /usr/share/fonts/truetype/, which is definitely not in my webroot as I don't normally keep my font files there. Note, also, that my PHP user has sufficient permissions to read from this path.
Now, if I supply PHP with the correct absolute path to the truetype font file that I would like to use I get the following image using your code...
$string = '';
for ($i = 0; $i < 5; $i++) {
// this numbers refer to numbers of the ascii table (lower case)
$string .= chr(rand(97, 122));
}
$image = imagecreatetruecolor(170, 60);
$color = imagecolorallocate($image, 200, 100, 90); // red
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-ExtraLight.ttf', $string);
header("Content-type: image/png");
imagepng($image);
What you should try to do in order to debug this further is run the PHP script that generates the image by itself, with display_errors turned on and error_reporting set to -1 and if it is indeed the case that your font file is the problem you will see this in your error_log or in the error output displayed during testing that script with display_errors on.

Related

PHP gd library displsys black screen with white box instead of image

I am pretty new to PHP and currently using XAMPP. I wanted to create a captcha image using the gd library but then I noticed that all I got was a black screen with a little white box outline at the middle. This is the output in spite of any code used. I have tried different code samples from different websites to no avail. I have confirmed that the gd library has been enabled. I have uninstalled and reinstalled xampp. I have also searched related questions but none of the suggested solutions works for me.
here is my code
session_start();
// Set some important CAPTCHA constants
define('CAPTCHA_NUMCHARS', 6); // number of characters in pass-phrase
define('CAPTCHA_WIDTH', 100); // width of image
define('CAPTCHA_HEIGHT', 25); // height of image
// Generate the random pass-phrase
$pass_phrase = "";
for ($i = 0; $i < CAPTCHA_NUMCHARS; $i++) {
$pass_phrase .= chr(rand(97, 122));
}
// Store the encrypted pass-phrase in a session variable
$_SESSION['pass_phrase'] = SHA1($pass_phrase);
// Create the image
$img = imagecreatetruecolor(CAPTCHA_WIDTH, CAPTCHA_HEIGHT);
$bg_color = imagecolorallocate($img, 255, 255, 255); // white
$text_color = imagecolorallocate($img, 0, 0, 0); // black
$graphic_color = imagecolorallocate($img, 64, 64, 64); // dark gray
// Fill the background
imagefilledrectangle($img, 0, 0, CAPTCHA_WIDTH, CAPTCHA_HEIGHT, $bg_color);
// Draw some random lines
for ($i = 0; $i < 5; $i++) {
imageline($img, 0, rand() % CAPTCHA_HEIGHT, CAPTCHA_WIDTH, rand() %
CAPTCHA_HEIGHT,
$graphic_color);
}
// Sprinkle in some random dots
for ($i = 0; $i < 50; $i++) {
imagesetpixel($img, rand() % CAPTCHA_WIDTH, rand() % CAPTCHA_HEIGHT,
$graphic_color);
}
// Draw the pass-phrase string
imagettftext($img, 18, 0, 5, CAPTCHA_HEIGHT - 5, $text_color, 'Courier New Bold.ttf', $pass_phrase);
// Output the image as a PNG using a header
header("Content-type: image/png");
imagepng($img);
// Clean up
imagedestroy($img);
?>
Edit:
I have been able to pinpoint the problem to the header(Content-type) line.
Still haven't figured the solution yet.
After hours of scouring different forums. I have come to understand the problem better. The problem is not with gd library but rather the header(Content-type) line
When I decide to create an image file rather than sending the image through a header. The correctly displays.
Once I figured that out, finding the solution became easier as now I am looking for the solution in the right place.
The problem is that my PHP script is emitting a UTF-8 byte order mark (EF BB BF) before outputting the PNG image content.
The solution that worked for me was to place ob_clean() before header line.
For more explanation see the link below.
https://stackoverflow.com/a/22565248/10349485
I used and pieced together different solutions from different forums to better understand and to arrive at this solution but the link above was my final destination.
I am not deleting the question even though there are other similar questions because of the amount of trouble it took me to get and understand this problem, also because the answers there didn't work for me. Hopefully, this helps someone in the future avoid the trouble I went through.
from many days i'm also face this problem but this solution work for me
use __DIR__ with your font file path like that
`$font_path = __DIR__ .'/font.ttf';`

PHP imagettftext() - nothing is displaying

Trying to display a font using the GD library. There is indeed an image there, it's just that theres nothing displaying.
PHP:
header('Content-Type: image/png');
$font = $_GET['font'];
// Create the image
$image = imagecreatetruecolor(400, 30);
// Create some colors
$white = imagecolorallocate($image, 255, 255, 255);
$grey = imagecolorallocate($image, 128, 128, 128);
$black = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, 399, 29, $white);
// The text to draw
$text = 'The Quick Brown Fox Jumps over the Lazy Dog';
$font = '/Aller/' . $font;
// Add the text
imagettftext($image, 20, 0, 10, 20, $black, $font, $text);
imagepng($image);
HTML:
<img src="fontgen.php?font=Aller_Rg.ttf" alt="" />
The font resides in fonts/Aller/Aller_Rg.tff
What am I doing wrong?
The problem seems to be the $font variable. From the documentation:
Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.
When using versions of the GD library lower than 2.0.18, a space character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: Warning: Could not find/open font. For these affected versions, the only solution is moving the font to a path which does not contain spaces.
In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.
<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));
// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>
You also said that the font resides in fonts/Aller/ directory. Whereas, in your script, there is no reference to the fonts directory.
The code is all correct except this part
$font = '/Aller/' . $font;
It tries the absolute path '/Aller/Aller_Rg.tff' not 'Aller/Aller_Rg.tff'
Changing it to $font = 'Aller/' . $font; should work.
Also you should check the error log, it should mention Invalid font filename
When in doubt remove header('Content-Type: image/png'); for debugging.

imagettftext() not working

/*create watermark*/
// Create the image
$im = imagecreate(460, 50);
// Create some colors
$grey = imagecolorallocate($im, 230, 231, 232);
$dark_grey = imagecolorallocate($im, 128, 130, 133);
// The text to draw
$text = "foobar";
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));
$font = 'Tondu_beta';
// Add the text
imagettftext($im, 15, 0, 15, 35, $dark_grey, $font, $text);
$wm_w = imagesx($im); //get width
$wm_h = imagesy($im); //get height
$wmresource = $im; //watermark resource
//imagejpeg($wmresource);
/*end watermark*/
The font file is Tondu_Beta.ttf. The code above worked just fine in my local machine, but it only gave me grey box after uploading to live server. What's wrong here? Thanks ^^
UPDATE: I remember it gave me this error: Could not find/open font bla.bla..bla...
try using
"./Tondu_beta.ttf"
worked for me when both font and php file were in root directory
The error is self-explanatory. Your live server doesn't have the font in question (Tondu_Beta.ttf) installed. Install the font onto your server, or choose a font your server does have.
Straight from the doc:
fontfile
The path to the TrueType font you wish to use.
Depending on which version of the GD library PHP is using, when fontfile does not begin with a leading / then .ttf will be appended to the filename and the library will attempt to search for that filename along a library-defined font path.
When using versions of the GD library lower than 2.0.18, a space character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: Warning: Could not find/open font. For these affected versions, the only solution is moving the font to a path which does not contain spaces.
In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.
<?php
// Set the enviroment variable for GD
putenv('GDFONTPATH=' . realpath('.'));
// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>

PHP Dynamic Image Has Undesired Border

I'm having some problems with a project I'm doing using Google Maps.
I have the map functionality all figured out, and it works great. I want to add dynamically generated icons to the map, and I've figured out how to do that as well using PHP to dynamically add the text I want to the icon image.
However, the icon is changed beyond the text I want added. The border around the original is made much thicker when there is nothing in the PHP code that should be doing anything like that. The image I've attached to this post shows the two icons. The top icon is the original, and the bottom one has the text added to it by my PHP script. Notice the thicker border.
Here's my PHP code:
<?php
// GETS THE NUMBER TO ADD TO THE ICON
$number = $_GET['number'];
// THE SOURCE OF THE ICON THAT I WANT TO ADD THE TEXT TO
$src = $_GET['src'];
header ("Content-type: image/png");
$font = 4;
$im = imagecreatefrompng($src);
// POSITION THE TEXT TO THE PREFERRED LOCATION
$x = 5 ;
$y = 2;
$textColor = imagecolorallocate ($im, 0, 0,0);
imagestring ($im, $font, $x, $y, $number, $textColor);
imagepng($im);
?>
Keep in mind that all of this is working, except the image is changed beyond just adding the text. The icons look much nicer without the really thick border.
I don't know for sure if this is the case but something like this can be caused if your initial image used transparency at the margin to get an effect of rounded corners. if you want to keep the transparency from the initial image you need to research other functions also. something like this should help:
imagealphablending( $im, false );
imagesavealpha( $im, true );
*right after imagecreatefrompng

How to combine image and text on the fly in php

i want to combine text and image on the fly to create a jpg widget. I want to do this for a fundraising website, i will need to update the image once a day so it reflect the updated fundraising progress bar. The reason why i want a jpg (image) widget is because it is much more friendly to add to blogs, website etc.
you can do it with gd
//open up the image you want to put text over
$im = imagecreatefromjpeg($imagePath);
//The numbers are the RGB values of the color you want to use
$black = ImageColorAllocate($im, 255, 255, 255);
//The canvas's (0,0) position is the upper left corner
//So this is how far down and to the right the text should start
$start_x = 10;
$start_y = 20;
//This writes your text on the image in 12 point using verdana.ttf
//For the type of effects you quoted, you'll want to use a truetype font
//And not one of GD's built in fonts. Just upload the ttf file from your
//c: windows fonts directory to your web server to use it.
Imagettftext($im, 12, 0, $start_x, $start_y, $black, 'verdana.ttf', 'text to write');
//Creates the jpeg image and sends it to the browser
//100 is the jpeg quality percentage
Imagejpeg($im, '', 100);
ImageDestroy($im);
I'd suggest you look into Imagemagick.
http://php.net/manual/en/book.imagick.php

Categories