ItWorksOnLocal
ItWorksOnLocal

Reputation: 167

the php code is not working for creating captcha

I am trying to display some random numbers as image in php. Actually im on my way to develop captcha in php, i know these are just random numbers but first i thought i should make a basic random number image so i looked for it and created the below code, but its not working, its not displaying aything except for the alt text that i had put in the img tag. Can someone please point out whats the error in the given code. Thanyou!!!

generator.php

<?php
session_start();
header("Content-type: image/jpeg");
$text=$_SESSION['text']=rand(10000,99999);
$image_width= 100;
$image_height= 40;
$font_size= 30;
$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,'Sans-serif',$text);
imagejpeg($image);
?>

captcha.php

<?php

?>
<html>
<head>
</head>
<body>
<h1>Captcha PHP </h1>
<img src="generator.php" alt="There is something wrong"/>
</body>
</html>

Upvotes: 2

Views: 1905

Answers (1)

Funk Forty Niner
Funk Forty Niner

Reputation: 74232

The problem here is that you do not have the font available to be loaded.

You should be seeing:

Warning: imagettftext(): Could not find/open font in...

as a notice as it did for me while testing your code. If not displayed, check your logs.

Download the "Sans-serif" font or "Arial" from any popular fonts website.

You would first declare it as:

$font = 'arial.ttf'; // I used this as an example

then modify your existing line to:

imagettftext($image,$font_size,0,15,30,$text_color,$font,$text);

Sidenote: You may need to increase the width of the image, or reduce the font size, as it did cut off a bit on the right.

I found the "Arial.ttf" file here to test:

http://www.font-police.com/affiche.php?a=classique&b=sans-serif&c=arial.ttf

Direct link:

Download it (to test) and upload it to your server so that it resides inside the same folder as your .php files.

N.B.: These are example links and working at the time of this posting.

Should they cease to exist in the future, simply find another font source, there are many out there.

Upvotes: 3

Related Questions