Chapter 3

PHP Libraries

IN THIS CHAPTER

check Getting familiar with PHP libraries

check Working with text functions

check Handling numbers

check Using dates

check Playing with images

As you start creating your dynamic web applications, you’ll often find yourself wanting to perform certain functions that require quite a bit of coding, such as manipulating data or performing complex mathematical calculations. The true test of a robust programming language is in how much work it can save you by providing prebuilt code libraries that do most of the hard coding work for you. Fortunately, PHP has an extensive set of built-in libraries that can save you lots of development time as you build your web applications! This chapter dives into the basics of using the built-in libraries in PHP.

How PHP Uses Libraries

All programming languages provide libraries of functions that help you with your coding. How many there are and how they do that differs somewhat between programming languages.

Some interpreted programming languages compile all the function libraries into a single monolithic executable program that loads into memory each time the web server runs a program that requires the interpreter. That can be a huge resource hog on your server!

PHP took a more modular approach to things. Instead of compiling all the function libraries in a single program, PHP provides them as separate loadable library files, called extensions. That way, you (or your web-hosting company) can opt to load only the extensions you need to use, saving memory on the server and hopefully improving the performance of the PHP server.

The downside to this approach is that you need to be more aware of just what PHP extensions are available and which ones you should load. This section shows you how PHP splits functions up into different extensions and how you can find the functions you need to do your work.

Exploring PHP extensions

More than 150 extensions are available in the PHP package! There are extensions to cover functions as simple as manipulating string values or as complex as interacting with online search engines. The PHP developers have classified these extensions into 27 categories. Table 3-1 shows the different categories, along with a brief description of what each category contains.

TABLE 3-1 PHP Extension Categories

Category

Description

PHP behavior

Functions that control how the PHP server operates

Audio formats

Functions that handle and manipulate audio files

Authentication

Functions that work with authentication services

Command line

Functions that interact with the server command-line environment

Compression

Functions that compress and archive files and folders

Credit card

Functions that process credit card transactions

Cryptography

Functions that encrypt and decrypt data

Database

Functions that interact with database servers

Date and time

Functions that handle dates and times

File system

Functions that interact with the server file system

GUI

Functions that work with user interface features

Human language

Functions that work with character sets

Image processing

Functions that create and manipulate images

Mail

Functions that interact with mail servers

Mathematical

Functions that perform complex mathematical operations

Non-text MIME

Functions that handle binary data in MIME messages

Process control

Functions that interact with processes on the server

Other

Miscellaneous functions that manipulate data

Other services

Functions that interact with network services

Search engine

Functions that interact with online search engines

Session

Functions that handle browser sessions

Text

Functions that manipulate and process text

Variable

Functions that work with complex objects and data structures

Web services

Functions that interact with web service servers and clients

Windows

Functions that access Microsoft Windows features on Windows servers

XML

Functions that handle and manipulate data in XML format

Each category contains multiple extensions that are available for you to load and use in your PHP programs. There are far too many PHP extensions to list them all individually here. For a full and current list of the PHP extensions, go to the PHP online documentation at www.php.net/manual/en/funcref.php.

Examining the PHP extensions

You can view which extensions are actively installed in your specific PHP server environment by using the special phpinfo() function. Just include that as a single line in a PHP program. When you run the program, the phpinfo() function displays a table showing detailed information about the PHP server, including which PHP extensions are currently installed.

Follow these steps to determine which PHP extensions are installed in your PHP server environment.

  1. Open your favorite text editor, program editor, or integrated development environment (IDE) package.
  2. Type the following code:

    <!DOCTYPE html>

    <html>

    <body>

    <?php

    phpinfo();

    ?>

    </body>

    </html>

  3. Save the file as extensions.php in the DocumentRoot folder for your web server.

    For XAMPP on Windows, that's c:\xampp\htdocs; for XAMPP on macOS, it’s /Applications/XAMPP/htdocs.

  4. Open the XAMPP Control Panel, and then start the Apache web server.
  5. Open your browser, and enter the following URL:

    http://localhost:8080/extensions.php

    You may need to change the TCP port in the URL to match your web server.

  6. Examine the output generated by the phpinfo() function, looking for which extensions are installed on your system.
  7. Close the browser when you're done.

Figure 3-1 shows the results from the XAMPP package running on a Windows workstation.

image

FIGURE 3-1: The output from the phpinfo() function.

As you scroll through the listing generated by the phpinfo() function, you'll see separate sections devoted to the different extensions and the configuration settings that control how they operate. Most likely, your PHP server has quite a few (if not all) of the extensions already activated. If any are missing, you can usually activate them yourself. That’s covered in the next section.

Including extensions

Most PHP server environments include all the extension library files in the PHP server build, but they may not activate all of them to help save memory as the PHP server runs. If you find yourself needing to activate a specific PHP extension, you can easily do that from the PHP configuration file.

The first step is to find the php.ini configuration file for your PHP server environment. The easiest way to do that is from the output of the phpinfo() function.

If you followed the steps in the previous exercise, you can view the output of the phpinfo() function in your browser. In that output, look for the line in the top section for Loaded Configuration File. That shows the path to the configuration file the PHP server is using.

Using your system's file manager program (File Explorer for Windows, Finder for Mac), navigate to the folder where the php.ini file is stored, and then double-click the file to open it with a text editor.

Look for the section labeled Dynamic Extensions within the php.ini configuration file. This is where the configuration file defines the extensions to install. Each extension is referenced by a single line. For Windows systems, it looks like this:

extension=name.dll

For Mac and Unix/Linux systems, it looks like this:

extension=name.so

The extension names are in the format php_name where name is the unique name assigned to the extension. For example, the extension for interacting with MySQL servers is called php_mysqli (the i is added because it's an improved version from the original MySQL extension).

warning Not all PHP server environments use extensions, so you may not see any entries for them in the php.ini configuration file. For example, the XAMPP for the macOS environment compiles all the extensions directly into the main PHP server executable.

Adding additional extensions

As you can probably guess, you can create your own PHP extensions for your own custom functions. This has become quite popular in the PHP developer world, and a clearinghouse has been created for sharing custom-made extensions with other PHP developers.

The PHP Extension Community Library (PECL) hosts a library of custom extensions shared by developers from around the world. You can access PECL at https://pecl.php.net. There, you’ll find extensions that add additional functionality to the standard PHP libraries, as well as add entirely new features, such as the html_parse extension, which provides functions to access a remote web page and parse the DOM tree elements to extract data!

Now that you know about PHP extensions, the following sections take a look at some of the more popular ones and the functions they contain that can help save you some time in your PHP coding.

Text Functions

Just about every web application needs to work with text data. There's a wealth of text processing and manipulation functions available at your fingertips within the PHP extension library. This section walks through some of the more useful ones that may come in handy as you process data in your applications. There are so many text functions provided by PHP that trying to find just what you’re looking for in the PHP online manual can be a bit overwhelming. This section breaks up the functions into categories to help simplify things a bit.

Altering string values

PHP provides a handful of functions that manipulate either the text or the text format in string values. Table 3-2 shows the string functions that can be useful when you need to manipulate string values.

TABLE 3-2 PHP String Manipulation Functions

Function

Description

addslashes

Adds an escape character (backslash) in front of single quote, double quote, backslash, and NULL characters.

chop

Removes all whitespace characters from the end of a string.

htmlentities

Converts HTML codes into HTML tags.

htmlspecialchars

Converts any HTML tags embedded in a string into HTML codes.

lcfirst

Changes the first character of the string to lowercase.

ltrim

Removes any whitespace characters from the start of a string.

money_format

Formats a monetary string value into a currency format.

nl2br

Converts newline characters to the <br> HTML tag.

number_format

Allows you to specify the format to display a number value.

rtrim

Removes all whitespace characters from the end of a string.

str_replace

Replaces the occurrences of a string with another string.

strip_tags

Removes all HTML and PHP tags from a string.

strtolower

Converts the string to lowercase.

strtoupper

Converts the string to uppercase.

trim

Removes all whitespace characters from the start and end of a string.

ucfirst

Converts the first character of the string to uppercase.

The string manipulation functions don't change the value of the original string — they just return a new string value. If you want to use the result in your program, you have to assign it to another variable:

$newvalue = trim($data);

The htmlspecialchars() and strip_tags() functions are extremely helpful if you're creating a web application that accepts data from unknown site visitors. Unfortunately, it’s all too common these days for an unseemly website to run robot scripts that scan the Internet looking for websites that allow site visitors to post comments without requiring a login. These robots then post advertisements as comments in the website, and these advertisements more often than not contain a hypertext link to a rogue website.

The htmlspecialchars() and strip_tags() functions can help block that silliness. They detect any HTML code embedded within a string value and either remove them completely (the strip_tags() function) or convert the greater-than and less-than symbols in the tag into the HTML &gt; and &lt; codes (the htmlspecialchars() function). This helps prevent your site visitors from accidentally clicking rogue hypertext links embedded within posts!

The nl2br() function comes in handy if your web application processes text files to display on the web page. If the text file contains new-line characters, those won't display on the web page, which may alter the layout of the text. If you pass the data through the nl2br() function, it converts any new-line characters in the text to HTML5 <br> tags, preserving the text layout on the web page.

Yet another useful string manipulation function you don't often see in other programming languages is the addslashes() function. This function is useful when you need to push data submitted by site visitors into a SQL database. It escapes any single or double quotes embedded within the string value, so that they don't conflict with any quotes needed to embed the string into a SQL statement to submit to the database. This little function can save you lots of trouble with handling data for your database!

Splitting strings

Another common function in string manipulation is the ability to split strings into separate substrings. This comes in handy when you’re trying to parse string values to look for words. Table 3-3 shows the PHP string splitting functions that are available.

TABLE 3-3 PHP String Splitting Functions

Function

Description

chunk_split

Splits a string value into smaller parts of a specified length.

explode

Splits a string value into an array based on one or more delimiter characters.

implode

Joins array elements into a single string value.

str_getcsv

Parses a comma-delimited string into an array.

str_split

Splits a string into an array based on a specified length.

The str_getcsv() function is extremely useful when you need to parse comma-separated data entered by site visitors, such as search terms. Follow these steps to see a demonstration of how this works:

  1. Open your editor and type the following code:

    <!DOCTYPE html>

    <html>

    <head>

    <title>String Parsing Test</title>

    <style>

    input {

    margin: 5px;

    }

    </style>

    </head>

    <body>

    <h2>String parse test</h2>

    <form action="parseoutput.php" method="post">

    <p>Enter a list of search words, separated with commas</p>

    <input type="text" name="search" size="40"><br>

    <input type="submit" value="Search">

    </form>

    </body>

    </html>

  2. Save the file as parseinput.html in the DocumentRoot folder for your web server.
  3. Open a new tab or window in your editor and type the following code:

    <!DOCTYPE html>

    <html>

    <head>

    <title>String Parse Test Results</title>

    </head>

    </body>

    <h1>Search word results</h1>

    <?php

    $search = $_POST['search'];

    $words = str_getcsv($search);

    foreach ($words as $word) {

    $term = trim($word);

    echo "<p>Search term: '$term'</p> \n";

    }

    ?>

    </body>

    </html>

  4. Save the file as parseoutput.php in the DocumentRoot folder for your web server.
  5. Ensure that your web server is still running, and then open your browser and enter the following URL:

    http://localhost:8080/parseinput.html

  6. In the text box, type a comma-separated list of words, and then click the Submit button.
  7. Observe the results in the parseoutput.php page.
  8. Close your browser window when you're done.

The parseinput.html file creates a simple HTML form that contains a single text box for you to enter search words, as shown in Figure 3-2.

image

FIGURE 3-2: The web page generated by the parseinput.php code.

Type a comma-separated list of words in the text box, and then click the Search button to send them to the parseoutput.php file. The parseoutput.php code retrieves the list of words using the standard $_POST[] array variable:

$search = $_POST['search'];

Then it uses the str_getcsv() function to parse the string and split the words into an array variable. It then uses the foreach statement to display the individual words in the web page, as shown in Figure 3-3.

image

FIGURE 3-3: The web page result from the parseoutput.php code.

The trim() function is used to remove any extra spaces or tab characters that may have been added between the search terms in the form. These are handy little functions to have in your toolbox as you code your web applications!

Testing string values

A vital function in string manipulation is the ability to test string values for specific conditions. PHP provides several string-testing functions that help with that, as shown in Table 3-4.

TABLE 3-4 PHP String-Testing Functions

Function

Description

is_bool

Returns a TRUE value if the string is a valid Boolean value.

is_float

Returns a TRUE value if the string is a valid float value.

is_int

Returns a TRUE value if the string is a valid integer value.

is_null

Returns a TRUE value if the string is a NULL value.

is_numeric

Returns a TRUE value if the string is a valid number or numeric string.

str_word_count

Returns the number of words in a string or an array of words.

strcasecmp

Performs a case-insensitive string comparison.

strcmp

Compares the binary values of two string values.

strlen

Returns the number of characters in a string.

strncmp

Compares the first n characters of two string values.

The string-testing functions provide quite a bit of information about the data you receive from your site visitors, as well as performing simple string comparisons to check data. The strcmp() function is crucial in evaluating data entered into forms in response to questions in your web applications.

tip The is_numeric() function is handy to use when testing data submitted in HTML5 forms from unknown site visitors to ensure a numeric value was submitted.

Searching strings

Yet another common string function is searching for a specific value within a string. If you just need to know if a substring value is contained within a string value, use the strpos() function. Here's the format of the strpos() function:

strpos(largestring, substring);

PHP will look for the string substring within the largestring string value. It returns the position where the substring is found inside the largestring (with position 0 being the first character of the string). If the substring is not found, it returns a FALSE value. Be careful though, because position 0 returns a numeric 0, which is different from a FALSE value! To properly test for the difference you must use the === comparison operator, which compares both the value and the data type.

Math Functions

Chapter 1 in this minibook shows the basic arithmetic operators that PHP supports. However, there are lots more advanced mathematical features that are available in the PHP extensions! This section discusses the different math functions you can add to your web applications to help save you from having to create complex code for your calculations.

Number theory

Number theory functions provide handy mathematical features, such as finding the absolute value, square root, or factorial of a number. PHP has lots of different number theory functions built in and ready for you to use in your calculations. Table 3-5 lists some of the more common ones you'll use.

TABLE 3-5 PHP Number Functions

Function

Description

abs

Returns the absolute value of a number.

ceil

Rounds a value up to the next largest integer.

floor

Rounds a value down to the next lowest integer.

fmod

Returns the floating point remainder of the division.

intdiv

Performs an integer division.

is_finite

Returns TRUE if the value is a finite number.

is_infinite

Returns TRUE if the value is infinite.

is_nan

Returns TRUE if the value is not a proper float value.

max

Returns the largest value in an array.

min

Returns the smallest value in an array.

pi

Returns a float approximation of pi.

rand

Returns a random number.

sqrt

Returns the square root of a value.

The rand() function is handy when you need to generate random numbers for applications (such as guessing games). Without any parameters, the rand() function returns a random integer value between 0 and the maximum integer value supported by the server (you can determine that using the getrandmax() function). If you need a value from a smaller range, you can specify the min and max range as parameters. The range values are inclusive, so if you specify the following, the rand() function will return a random number from 1 to 10:

$number = rand(1, 10);

warning Despite what you might think from its name, the is_nan() function does not work to test input provided by site visitors to determine if the value is a number. The is_nan() function only works for float values to determine if the float is in the correct floating point notation. Use the is_numeric() string function instead.

Calculating logs and exponents

PHP supports several logarithmic functions that can help with some of your more complex mathematical operations. Table 3-6 shows what tools you have available for that.

TABLE 3-6 PHP Logarithmic Functions

Function

Description

exp

Calculates the exponent of e.

expm1

Calculates the exponent of e minus 1.

log

Performs a standard natural logarithm.

log10

Performs a base-10 logarithm.

log1p

Calculates a log(1 + number).

pow

Calculate the base raised to a power.

Since version 5.6, PHP has included the ** operator to perform exponentiation as well as the pow() function. You can use either one in your mathematical calculations to get the same result.

Working the angles

If trigonometry is your thing, you'll be glad to know that PHP includes all the standard trig functions in the math extension. These are shown in Table 3-7.

TABLE 3-7 PHP Trigonometric Functions

Function

Description

acos

Calculates the arc cosine.

asin

Calculates the arc sine.

atan

Calculates the arc tangent.

cos

Calculates the cosine.

deg2rad

Returns the radian value of a degree.

hypot

Calculates the length of the hypotenuse of a right triangle.

rad2deg

Returns the degree value of a radian.

sin

Calculates the sine.

tan

Calculates the tangent.

All the PHP trig functions require that you specify the angle values in radians instead of degrees. If your application is working with degree units, you'll need to use the deg2rad() function to convert the values to radians before using them in your calculations.

Hyperbolic functions

Somewhat related to trigonometric functions are the hyperbolic functions. Whereas trigonometric functions are derived from circular calculations, hyperbolic functions are derived from a hyperbola calculation. Table 3-8 shows the hyperbolic functions that PHP supports.

TABLE 3-8 PHP Hyperbolic Functions

Function

Description

acosh

Returns the inverse hyperbolic cosine.

asinh

Returns the inverse hyperbolic sine.

atanh

Returns the inverse hyperbolic tangent.

cosh

Returns the hyperbolic cosine.

sinh

Returns the hyperbolic sine.

tanh

Returns the hyperbolic tangent.

Just as with the trigonometric functions, you must specify the hyperbolic function values in radian units instead of degrees.

Tracking statistics

The PHP statistics extension contains functions commonly used for statistical calculations. It uses the open-source library of C routines for Cumulative Distributions Functions, Inverses, and Other parameters (DCDFLIB) created by Barry Brown and James Lavato.

The library contains about 70 functions for calculating statistical values from beta, chi-square, f, gamma, Laplace, logistic, normal, Poisson, t, and Weinbull distributions. If you understand any of those things, this is the extension for you! Check out the available statistical functions in the PHP online manual at www.php.net/manual/en/ref.stats.php.

Date and Time Functions

Working with times and dates in web applications can be a tricky thing. If your application needs to perform date arithmetic (such as calculating when 60 days is from now), PHP has some useful functions for you! This section first walks through just how PHP handles time and dates, then shows you some functions that can help with your date calculations.

Generating dates

PHP provides the date() function for generating human-readable dates and times. The date() function takes either one or two parameters:

date(format [, timestamp])

The format parameter is required. It specifies how you want PHP to display the date and/or time values. The timestamp parameter is optional. It represents the date and time you want to display as an integer timestamp value. The timestamp value represents the date and time as the number of seconds since midnight, January 1, 1970 (it's an old Unix standard). If you omit the timestamp value, PHP assumes the current date and time.

The format is a string value that uses a complicated code to indicate how you want the time and date to appear in the output. Table 3-9 shows the format codes that are available.

TABLE 3-9 The PHP date() Function Format Codes

Code

Description

Example

a

Morning or evening as am or pm

am

A

Morning or evening as AM or PM

AM

B

The Swatch international time format

952 (for 9:52 pm)

c

The date in ISO 8601 format

2018-05-15T22:51:52+01:00

d

The day of the month as a two-digit value with leading zero if necessary

15

D

The day of the week as a three-letter abbreviation

Mon

e

Time zone identifier

America/New_York

F

The month of the year in full text

January

g

The hour of the day in 12-hour format

4

G

The hour of the day in 24-hour format

16

h

The hour of the day in 12-hour format with leading zero

04

H

The hour of the day in 24-hour format with leading zero

16

i

Minutes past the hour with leading zero

05

I

Whether the time zone is using daylight saving time

0 (for not using daylight savings time)

j

The day of the month as a number without leading zeroes

5

l

The day of the week in full text

Monday

L

Whether the year is a leap year

0 (for non-leap years)

m

The month of the year as a two-digit number with leading zero

01

M

The month of the year as a three-letter abbreviation

Jan

n

The month of the year as a number without leading zero

1

o

The year in ISO 8601 format

2018

O

The difference between the current time zone and GMT

-0500

r

The date and time in RFC822 format

Mon, 15 Jan 2018 22:56:35 +0100

s

Seconds past the minute in two-digit format with leading zero

05

S

Ordinal suffix of the date in two-letter format

th (for 15)

t

The total number of days in the date's month

31

T

The time zone setting of the server

EST

U

The date and time in Unix timestamp format

1516053508

w

The day of the week as a single digit

1

W

The week number in the year

03

y

The year in two-digit format with leading zero

18

Y

The year in four-digit format

2018

z

The day of the year as a number

78

Z

Offset for the current time zone in seconds

-18000

As you can see from the list of codes in Table 3-9, the date() function output is very flexible! For example, if you use the following format:

$today = date("l, F jS, Y");

The $today variable would display the current date as:

Thursday, January 4th, 2018

Or if you prefer, you can just use:

$today = date("m/d/Y");

To display the date as:

01/04/2018

With the date() function codes, you can display the date and time in any format you need!

warning Displaying dates in a website that can be seen internationally can be somewhat tricky. Keep in mind the differences in how the United States represents dates and how the rest of the world represents dates. To accommodate that difference, the Organization of International Standards (ISO) has created the ISO 8601 standard for displaying dates. It follows none of the common date formats, but instead, uses its own style: 2018-01-04, which represents January 4, 2018. Later in the book, when you work with dates in the MySQL server, you need to use this format to store dates in the database.

Using timestamps

The second parameter of the date() function allows you to specify a different date/time to display using a timestamp value. The problem, though, is that you most likely don't know what the timestamp value for a date is! No worries — you have the handy strtotime() function to help you out.

The strtotime() function converts a date/time string value in just about any format into a timestamp value. For example, if you want to find out what day of the week the Fourth of July is in the year 2020, just use the following code:

$timestamp = strtotime("07/04/2020");

$holiday = date("l", $timestamp);

The strtotime() function returns the value 1593820800, which is the timestamp representation for midnight on that day. You then use that as the second parameter in the date() function, and use the l (lowercase letter L) code format for the output. The output will be the day of the week, Saturday.

warning There is a looming problem with using timestamp values in your PHP code. Because the timestamp format is an old format, to remain backward-compatible, systems store the value as a 32-bit integer data type. As you can guess, at some point in the future, that value will overflow the storage capability of the integer data type. That date happens to be January 14, 2038. If your application needs to work with dates past then, you have to use some other way to handle dates.

Calculating dates

You have a couple of different ways to handle date calculations at your disposal in PHP. One method is to work with timestamp values. If you know the timestamp for the current date/time, you can add the number of seconds needed to represent another date/time.

For example, to calculate the time ten minutes from now, you'd use the following code:

$start = strtotime("07/04/2020 10:00:00");

$end = $start + (60 * 10);

$duedate = $date("H:i:s", $end);

The first line returns the timestamp value for the start date. The second line adds the number of seconds for 10 minutes (60 seconds × 10 minutes) to the date timestamp. Finally, the third line returns the resulting time.

With timestamp values, you can perform all types of calculations, adding and subtracting values from any start point. Just remember that you’re working with seconds, so you need to convert the values into the appropriate timestamp values, and add or subtract the appropriate number of seconds.

The other method for performing date calculations is to use the strtotime() function itself. The strtotime() function is extremely versatile and can recognize all sorts of common date representations. For example, if you want to find out yesterday's date, you use the following:

$yesterday = strtotime("yesterday");

And the strtotime() function will return the timestamp value for yesterday! You can also use some basic calendar math:

$duedate = strtotime("today + 120 days");

PHP will calculate that for you automatically! That saves you from having to do the calculations yourself using timestamp values.

Image-Handling Functions

These days, it’s a common requirement to work with images in your web pages. Whether vacation pictures on a blog or an online catalog of products, images have become a crucial part of most web applications.

PHP doesn’t disappoint here. The php_gd2 extension is a complete graphical manipulation library for processing images directly in your PHP applications. Instead of having to rely on an external image manipulation program such as Photoshop or GIMP, you can edit images directly in your application as you or your site visitors upload them!

Not only can you manipulate uploaded images, but the php_gd2 extension also has functions that allow you to create new images on the fly in your PHP code! To create a new image, use the imagecreatetruecolor() function. This function takes two parameters: the width and height of the new image, specified in pixels. It returns a resource variable value that you use to reference the new image as you add components to the image.

For example, to create a new image that is 80 pixels wide by 60 pixels high, use this code:

$myimage = imagecreatetruecolor(80, 60);

After creating the new image, you'll probably want to draw something in it. First, you must allocate colors to use for the background and foreground objects:

$bg = imagecolorallocate($myimage, 255, 255, 255);

$fg = imagecolorallocate($myimage, 0, 0, 0);

The imagecolorallocate() function takes four parameters. The first parameter is the image resource value returned when you create the image. The next three parameters are the color, defined by the RGB value, just as you do with CSS style colors. The value 255, 255, 255 represents white, while the 0, 0, 0 value represents black.

After allocating the colors you need, you’re ready to start drawing on your canvas. Table 3-10 covers the functions you have available for drawing lines, shapes, and even text.

TABLE 3-10 The GD2 Library Drawing Functions

Function

Description

imageline

Draws a line between two specified points, using a defined color.

imagechar

Draws an alphanumeric character using a specified font, color, and location.

imagerectangle

Draws a rectangle outline between four points using a defined color.

imagefilledrectangle

Draws a solid rectangle between four points using a defined color.

imagestring

Draws a string of characters using a specified font, color, and location.

So, to create a new image file with the words Test Image, you'd use this code:

$image = imagecreatetruecolor(80, 60);

$bc = imagecolorallocate($image, 255, 255, 255);

$fc = imagecolorallocate($image, 0, 0, 0);

imagefilledrectangle($image, 0, 0, 80, 60, $bc);

imagestring($image, 5, 20, 5, "Test", $fc);

imagestring($image, 5, 10, 20, "Image", $fc);

imagejpeg($image, "myimage.jpg");

imagedestroy($image);

You should recognize most of these image functions. The imagestring() function defines a font size followed by the X and Y coordinates of where to start the string, followed by the string, followed by the color.

The imagejpeg() function converts the referenced image object in memory to either an image on the web page or saves it to a file. I specified a filename to save the image to. The imagedestroy() function removes the image from memory to free up space. This is especially necessary when working with large images.

One of the biggest problems I often run into when using images in web applications is that they're too big to fit nicely in the spaces I allocate on the web page. If you run a web application that allows site visitors to upload their own images for posting, you never know quite what to expect. Some visitors upload tiny picture files, while others upload mega-sized images. The trick to a good web page is to standardize all the images to make them fit nicely on the web page.

Sure, you can do that by manually downloading all the images, opening them in Photoshop, resizing them, and then uploading the new images back to the web server. That works, but it’s extremely time consuming and awkward. Fortunately, the php_gd2 library has just the tool for you!

The imagecopyresampled() function allows you to resample an existing image to a new image. Resampling rebuilds the image pixel by pixel, at a different resolution, using special algorithms to maintain the picture clarity.

By resampling the image, you can make it larger or smaller. The php_gd2 extension library takes care of all the mathematical routines required to do that. Follow these steps to try that out:

  1. Open your editor and enter the following code:

    <!DOCTYPE html>

    <html>

    <head>

    <title>Image Manipulation Test</title>

    <style>

    input {

    margin: 5px;

    }

    </style>

    </head>

    <body>

    <h2>Please select an image to upload</h2>

    <form action="imageconvert.php" method="post"

    enctype="multipart/form-data">

    <input type="file" name="picture"><br>

    <input type="submit" value="Submit">

    </form>

    </body>

    </html>

  2. Save the file as imageupload.html in the DocumentRoot folder for your web server.
  3. Open a new tab or window in your editor and enter the following code:

    <!DOCTYPE html>

    <html>

    <head>

    <title>Image Manipulation Test</title>

    </head>

    <body>

    <h1>The uploaded image:</h1>

    <?php

    $file = $_FILES['picture']['tmp_name'];

    $picture = file_get_contents($file);

    $sourceImage = imagecreatefromstring($picture);

    $width = imageSX($sourceImage);

    $height = imageSY($sourceImage);

    $newheight = 400;

    $newwidth = $newheight * ($width / $height);

    $newImage = imagecreatetruecolor($newwidth, $newheight);

    $result = imagecopyresampled($newImage, $sourceImage,

    0, 0, 0, 0,

    $newwidth, $newheight, $width, $height);

    imagejpeg($newImage, "newimage.jpg");

    ?>

    <img src="newimage.jpg">

    </body>

    </html>

  4. Save the file as imageconvert.php in the DocumentRoot folder for your web server.
  5. Have an image file handy that you want to copy and convert to a different sized image.
  6. Ensure the web server is running, and then open your browser to the URL:

    http://localhost:8080/imageupload.html

  7. Click the file chooser button for the file upload text box as it appears in your browser, navigate to your image file, select it, and then click the Open button to select the name.
  8. Click the Submit button to upload the image file for converting.
  9. You should see the resized image appear on the resulting web page.
  10. Close your browser and shut down the web server when you're done.

The imageupload.html file creates a simple HMTL5 form using the file data input type. The browser will provide a method for you to select a local file to enter into the file input field, as shown in Figure 3-4 for the Chrome browser.

image

FIGURE 3-4: The output from the imageupload.html program.

The imageconvert.php code retrieves the uploaded image from the PHP server using the special $_FILES[] array variable. The $_FILES[] array provides information about files uploaded to the server within an HTML5 form. The tmp_name array element contains the name of the temporary file the server creates to store the uploaded file.

After retrieving the uploaded file, the code converts it to an editable php_gd2 library object using the imagecreatefromstring() function.

Using the uploaded image object, the code calculates the width and height of the original image using the imageSX() and imageSY() functions. Then with a little bit of algebra, the code sets the new image height to a set height, and calculates the new width required to keep the original aspect ratio of the image. This ensures that all images that appear on the web page use the same height.

With the new width and height values calculated, the code then uses the imagecopyresampled() function to copy and resample the original image to the resized image object. The imagejpeg() function saves the new image as the file newimage.jpg in the DocumentRoot folder of the web server. Finally, the code displays the new image on the web page using a standard <img> HTML5 tag, as shown in Figure 3-5.

image

FIGURE 3-5: Displaying the resampled and resized image.

Now you can resize uploaded image files on the fly, without any intervention required on your part!