imagettftext is saying that the font file name is invalid

4.9k views Asked by At

I am trying to make a captcha. To make it I need to create an image. I am following this tutorial from Nettuts. To create it I need to use the function imagettftext(). But whenever I am trying to run it it is giving me an error saying

imagettftext(): Invalid font filename

My code is given below.

<?php
    session_start();  

    $string = '';  

    for ($i = 0; $i < 5; $i++) {  
        $string .= chr(rand(97, 122));  
    }  

    $_SESSION['random_code'] = $string;

    $dir = base_url('assets/fonts/asman.ttf');

    $image = imagecreatetruecolor(170, 60);  
    $color = imagecolorallocate($image, 200, 100, 90);
    $white = imagecolorallocate($image, 255, 255, 255);

    imagefilledrectangle($image, 0, 0, 200, 100, $white);  
    imagettftext($image, 30, 0, 10, 40, $color, $dir, $_SESSION['random_code']);
?>

Just in case it is relevant, I am using CodeIgniter framework but I don't want use CI captcha library.

3

There are 3 answers

1
Ivan Hušnjak On BEST ANSWER

From the php 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.

you should not use url path for that (also note that your url does not start with /)

I would suggest using absolute filesystem path when specifying font file:

$dir = '/full/path/to/assets/fonts/asman.ttf';
imagettftext($image, 30, 0, 10, 40, $color, $dir, $_SESSION['random_code']);

I'm sure CI has some function to return the application path from which you can reference to proper file.

0
Partha On

You can try this code It's work for me

   $dir = realpath('assets/fonts/asman.ttf');
0
Hannah On

I had the similar issue - using realpath() PHP function solved it.

Before :

imagettftext($img,$font_size,0,5,5,$color_text,'../fonts/courgetteregular.ttf',$captcha_string);

After :

$font = realpath("../fonts/courgetteregular.ttf"); imagettftext($img,$font_size,0,5,CAPTCHA_HEIGHT - 10,$color_text,$font,$captcha_string);

Also, commenting on the header('image/png') will help with troubleshooting.