I have written a piece of code to generate images from text in PHP using GD. When I run this code on my XAMPP localhost I do not get any errors but neither do I get an image.
Generate.php
<?php
session_start() ;
header ('Content-type: image/jpeg') ;
$_SESSION['secure'] = rand(1000,9999) ;
$text=$_SESSION['secure'] ;
$font_size=30 ;
$img_height=40 ;
$img_width=100 ;
$image=imagecreate($image_width,$image_height) ;
imagecolorallocate($image,255,255,255) ;
$text_color=imagecolorallocate($image,0,0,0) ;
imagettftext($image,$font_size,0,15,30,$text_color,'captchafont.ttf',$text) ;
imagejpeg($image) ;
?>
HTML
<img src="generate.php"/>
All I get when I run this HTML file on a localhost is image not found symbol in browser.
You should change this line:
$image=imagecreate($image_width,$image_height) ;
into
$image=imagecreate($img_width,$img_height) ;
because you have defined $img_width
and $img_height
variables and not $image_width
and $image_height
You should also make sure that captchafont.ttf
exists in the correct path and is used the correct way. From manual:
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.
Small advice for testing
Comment/Remove line header ('Content-type: image/jpeg') ;
and simple run in your browser this url for example http://localhost/generate.php
to make sure no errors appear. Otherwise if this still doesn't add error_reporting(E_ALL)
at the beginning of your file. After removing all errors and warnings, you should of course remove this line and uncomment line with header
and then check if image is displayed correctly.