Search code examples
phpimageimage-processinggdimagettftext

imagettftext is saying that the font file name is invalid


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.


Solution

  • 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.