Chapter 3
IN THIS CHAPTER
Getting familiar with PHP libraries
Working with text functions
Handling numbers
Using dates
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.
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.
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 |
|
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
.
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.
<!DOCTYPE html>
<html>
<body>
<?php
phpinfo();
?>
</body>
</html>
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
.
http://localhost:8080/extensions.php
You may need to change the TCP port in the URL to match your web server.
phpinfo()
function, looking for which extensions are installed on your system.Figure 3-1 shows the results from the XAMPP package running on a Windows workstation.
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.
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).
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.
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.
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 |
|
Adds an escape character (backslash) in front of single quote, double quote, backslash, and NULL characters. |
|
Removes all whitespace characters from the end of a string. |
|
Converts HTML codes into HTML tags. |
|
Converts any HTML tags embedded in a string into HTML codes. |
|
Changes the first character of the string to lowercase. |
|
Removes any whitespace characters from the start of a string. |
|
Formats a monetary string value into a currency format. |
|
Converts newline characters to the |
|
Allows you to specify the format to display a number value. |
|
Removes all whitespace characters from the end of a string. |
|
Replaces the occurrences of a string with another string. |
|
Removes all HTML and PHP tags from a string. |
|
Converts the string to lowercase. |
|
Converts the string to uppercase. |
|
Removes all whitespace characters from the start and end of a string. |
|
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 >
and <
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!
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 |
|
Splits a string value into smaller parts of a specified length. |
|
Splits a string value into an array based on one or more delimiter characters. |
|
Joins array elements into a single string value. |
|
Parses a comma-delimited string into an array. |
|
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:
<!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>
parseinput.html
in the DocumentRoot
folder for your web server.<!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>
parseoutput.php
in the DocumentRoot
folder for your web server.http://localhost:8080/parseinput.html
parseoutput.php
page.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.
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.
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!
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 |
|
Returns a |
|
Returns a |
|
Returns a |
|
Returns a |
|
Returns a |
|
Returns the number of words in a string or an array of words. |
|
Performs a case-insensitive string comparison. |
|
Compares the binary values of two string values. |
|
Returns the number of characters in a string. |
|
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.
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.
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 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 |
|
Returns the absolute value of a number. |
|
Rounds a value up to the next largest integer. |
|
Rounds a value down to the next lowest integer. |
|
Returns the floating point remainder of the division. |
|
Performs an integer division. |
|
Returns |
|
Returns |
|
Returns |
|
Returns the largest value in an array. |
|
Returns the smallest value in an array. |
|
Returns a float approximation of pi. |
|
Returns a random number. |
|
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);
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 |
|
Calculates the exponent of e. |
|
Calculates the exponent of e minus 1. |
|
Performs a standard natural logarithm. |
|
Performs a base-10 logarithm. |
|
Calculates a log(1 + number). |
|
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.
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 |
|
Calculates the arc cosine. |
|
Calculates the arc sine. |
|
Calculates the arc tangent. |
|
Calculates the cosine. |
|
Returns the radian value of a degree. |
|
Calculates the length of the hypotenuse of a right triangle. |
|
Returns the degree value of a radian. |
|
Calculates the sine. |
|
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.
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 |
|
Returns the inverse hyperbolic cosine. |
|
Returns the inverse hyperbolic sine. |
|
Returns the inverse hyperbolic tangent. |
|
Returns the hyperbolic cosine. |
|
Returns the hyperbolic sine. |
|
Returns the hyperbolic tangent. |
Just as with the trigonometric functions, you must specify the hyperbolic function values in radian units instead of degrees.
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
.
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.
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 |
|
Morning or evening as am or pm |
am |
|
Morning or evening as AM or PM |
AM |
|
The Swatch international time format |
952 (for 9:52 pm) |
|
The date in ISO 8601 format |
2018-05-15T22:51:52+01:00 |
|
The day of the month as a two-digit value with leading zero if necessary |
15 |
|
The day of the week as a three-letter abbreviation |
Mon |
|
Time zone identifier |
America/New_York |
|
The month of the year in full text |
January |
|
The hour of the day in 12-hour format |
4 |
|
The hour of the day in 24-hour format |
16 |
|
The hour of the day in 12-hour format with leading zero |
04 |
|
The hour of the day in 24-hour format with leading zero |
16 |
|
Minutes past the hour with leading zero |
05 |
|
Whether the time zone is using daylight saving time |
0 (for not using daylight savings time) |
|
The day of the month as a number without leading zeroes |
5 |
|
The day of the week in full text |
Monday |
|
Whether the year is a leap year |
0 (for non-leap years) |
|
The month of the year as a two-digit number with leading zero |
01 |
|
The month of the year as a three-letter abbreviation |
Jan |
|
The month of the year as a number without leading zero |
1 |
|
The year in ISO 8601 format |
2018 |
|
The difference between the current time zone and GMT |
-0500 |
|
The date and time in RFC822 format |
Mon, 15 Jan 2018 22:56:35 +0100 |
|
Seconds past the minute in two-digit format with leading zero |
05 |
|
Ordinal suffix of the date in two-letter format |
th (for 15) |
|
The total number of days in the date's month |
31 |
|
The time zone setting of the server |
EST |
|
The date and time in Unix timestamp format |
1516053508 |
|
The day of the week as a single digit |
1 |
|
The week number in the year |
03 |
|
The year in two-digit format with leading zero |
18 |
|
The year in four-digit format |
2018 |
|
The day of the year as a number |
78 |
|
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!
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.
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.
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 |
|
Draws a line between two specified points, using a defined color. |
|
Draws an alphanumeric character using a specified font, color, and location. |
|
Draws a rectangle outline between four points using a defined color. |
|
Draws a solid rectangle between four points using a defined color. |
|
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:
<!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>
imageupload.html
in the DocumentRoot
folder for your web server.<!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>
imageconvert.php
in the DocumentRoot
folder for your web server.http://localhost:8080/imageupload.html
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.
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.
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!