There are a number of ways to make the forms on your website more user friendly. This article will explain one way of doing this, which eliminates a page reload and replaces it with an image generated on the server.
Submitting a Form Using an Image Tag - Handling the Name (Page 6 of 8 )
We'll be working with a person's name entered into a form. The name entered could be long, short, one word, two words or three words. We will need to work with it a little to make sure it fits in our image and is positioned properly. You may want to do a few tests with the font and font size you want to use to see how many letters comfortably fit in the image. In the code we will use this number to determine whether or not we should break up the name into multiple lines. A name like "John Smith" can probably go on one line but a name like "Amy Lynn Johnson" might not, for instance.
include("textBox.php");
$fontPath = "G-Unit.TTF";
$fontSize = 27;
$blockSize = 0;
$offset = 26;
$str = trim($_GET['name']);
function handleName($fontSize,$font,$image,$str)
{
$strArr = null;
global $blockSize;
global $offset;
$tboxes = array();
if(strlen($str) > 15)
{
$strArr = explode(" ",$str);
for($i = 0;$i < count($strArr);$i++)
{
$tboxes[$i] = new textBox($fontSize,$font,
$image,$strArr[$i],$offset);
$blockSize = $blockSize + $tboxes[$i]->h;
}
}
else
{
$tboxes[0] = new textBox($fontSize,$font,$image,$str,$offset);
}
return $tboxes;
}
The images used in this example are 400 pixels x 375 pixels. With a font size of 27 and the font I have selected, I determined that 15 characters should be the limit before the name is broken up.
If the name needs to be broken up into multiple lines, in order to center each line they will all have to be separate text blocks. The explode() function splits the name at each space. It is possible that a user would try to enter a name without spaces longer than the limit. We could handle this eventuality with the server side code, however client side validation might be a better place to catch this sort of thing.
In this example a custom PHP class handles the task of getting and storing information about each block, such as dimensions, and determining an x coordinate for horizontal centering. We will look at the code for this class in a moment.
$blockSize = $blockSize + $tboxes[$i]->h;
}
}
else
{
$tboxes[0] = new textBox($fontSize,$font,$image,$str,$offset);
}
return $tboxes;
}
If we have multiple lines of text, they will need to be centered in the image as a group. The global $blocksize is used to count up the height of each block to get a number that is the height of all the lines of text combined. This number is used to center the text vertically in the image later on.
If the text does not exceed the limit, we create just a single instance of the textBox class. The function then returns an array of all textBox objects.