<?php
function calculateTextBox($size$angle$fontfile$text) { //found on http://php.net/manual/en/function.imagettfbbox.php
    
$rect imagettfbbox($size$angle$fontfile$text);

    
$minX min(array($rect[0],$rect[2],$rect[4],$rect[6]));
    
$maxX max(array($rect[0],$rect[2],$rect[4],$rect[6]));
    
$minY min(array($rect[1],$rect[3],$rect[5],$rect[7]));
    
$maxY max(array($rect[1],$rect[3],$rect[5],$rect[7]));

    return array(
        
"left"   => abs($minX) - 1,
        
"top"    => abs($minY) - 1,
        
"width"  => $maxX $minX,
        
"height" => $maxY $minY,
        
"box"    => $rect
    
);
}

function 
imagewrapttftext($image$size$angle$x$y$color$fontfile$text) {
    if(empty(
$text)){
        return 
true// satisfied; job complete.
    
}
    for(
$i 0$relWidth $x$i strlen($text); $i++){
        
$boundingbox calculateTextBox($size$angle$fontfile$text[$i]);
        
$tallestLetter calculateTextBox($size$angle$fontfile"|");
        
$relWidth += $boundingbox['width'];
        if(
$relWidth imagesx($image)){
            
$tempString explode(" "substr($text0$i));
            
$offsetIdentifier array_pop($tempString);
            
imagettftext($image$size$angle$x$y$color$fontfileimplode(" "$tempString));
            
$newText substr($text$i strlen($offsetIdentifier), strlen($text));
            
imagewrapttftext($image$size$angle$x$y $tallestLetter['height'], $color$fontfile$newText);
            break;
        }
        if(
$i == strlen($text)-1){
            
imagettftext($image$size$angle$x$y$color$fontfile$text);
            return 
true//satisfied; job complete.
            
break;
        }
    }
}
header("Content-Type: image/png");
$im imagecreatetruecolor(500500);
$white imagecolorallocate($im255255255);
$black imagecolorallocate($im500220);
imagefill($im00$white);
$text "Once upon a midnight dreary, while I pondered, weak and weary, / Over many a quaint and curious volume of forgotten lore, / While I nodded, nearly napping, suddenly there came a tapping, / As of someone gently rapping, rapping at my chamber door.";
imagewrapttftext($im110515$black"arial.ttf"$text);
imagepng($im);
imagedestroy($im);
?>