PHP Libraries
Most programming languages, including PHP, have modularized collections of code, classes, and functions. These collections are usually referred to as a code library or extension.
Don’t re-create the wheel! There are PHP libraries that exist to perform very specific functionality that you can easily use to extend the applications you’re building.
Lots of WordPress is written in PHP, which means that as a WordPress developer, you can utilize any PHP libraries available to you or even build your own. Check out the PHP.net Function Reference for an organized list of some common PHP libraries.
The WordPress plugin repository has more than a few plugins that interact with various libraries and external services, so any time you are looking for custom WordPress functionality, you might want to begin at the WordPress plugin repository. Of course, if you don’t find exactly what you are looking for in a plugin, you may need to write your own custom plugin or piggyback off of an existing one.
We’ve mentioned GitHub more than a few times, but it is a great place to find the functionality you’re looking for. Another good resource for code can be other PHP-based open source projects like Drupal, Laravel, Joomla, and/or Magento. Maybe the functionality you need doesn’t exist as a WordPress plugin but does exist as a Drupal module: take the code and make it work with WordPress.
Let’s review some cool PHP libraries that offer extended functionality and that you can easily integrate with WordPress.
Note
Depending on your web-hosting environment, you might not be able to use some PHP libraries. Some PHP libraries are wrappers for their underlying software, which needs to be installed on your web server. If you do not have access to configure your web server, you will not be able to use them.
Image Generation and Manipulation
Think of Photoshop for your code, which can be useful for building things like mindless meme generators, among other more productive things. Image generation and manipulation can be very useful for a number of things:
Resizing and scaling images
Comparing images
Copying images
Converting images to various image formats
Changing colors within an image
Converting text to images and overlaying text on images
Combining multiple images
Creating animated images
Applying custom image filters (yes, just like Instagram)
Blurring and sharpening images
Adding borders and frames to images
Dynamically creating charts or graph images based on data
Rendering 3D images
As you can imagine, there are many use cases for these capabilities given that you can pretty much do anything with any images programmatically. Some PHP image-manipulation libraries are better than others depending on what you are using them for.
By default, WordPress uses one of the two most popular PHP image-manipulation libraries to power image-manipulation features of WordPress and in the media library. First, WordPress checks whether the Imagick library is available; if not, then it checks to see if the GD library is available. If neither is available, you get an error message when you try to use WordPress image-manipulation functions. When WordPress crops an image, rotates an image, or does anything to manipulate an image, it is using one of these two libraries in the background.
You can easily check if Imagick or GD is being used on your WordPress installation by executing the following code in your theme functions.php file:
<?
php
// Don't do this on a production site that you care about.
function
bwawwp_image_library_check
(){
if
(
extension_loaded
(
'imagick'
)
)
{
$imagick
=
new
Imagick
();
print_r
(
$imagick
->
queryFormats
()
);
}
else
{
echo
'No ImageMagick!'
;
}
if
(
extension_loaded
(
'gd'
)
)
{
print_r
(
gd_info
()
);
}
else
{
echo
'No GD!'
;
}
exit
();
}
add_action
(
"init"
,
"bwawwp_image_library_check"
);
Depending on which library is being used, you could easily start writing code to use that library.
GD
GD is probably the most popular image-manipulation PHP library and usually comes compiled with default installations of PHP. GD tends to be a little bit faster than Imagick when dealing with larger images and it is generally less of a server resource hog. GD is a great tool and can get you where you need to go most of the time, but Imagick has more features and functionality.
Imagick
One of the most powerful image-manipulation tools and our personal favorite—though we wish someone would update its website to use WordPress—Imagick can be used to manipulate image files programmatically in just about any way you can imagine. You can install Imagick on your server and run it through the command line via the shell_exec()
or exec()
PHP functions, or you can use the Imagick PHP library as a wrapper for the underlying software. The Imagick library is not bundled with PHP by default and you must install it separately along with the Imagick software itself.
Justin Sternberg made some really easy-to-use methods using Imagick for overlaying any text on any image and then saving the separate image as an attachment against a WordPress post. This can be very useful if you require all the images on your web application to be watermarked with your URL, so if anybody hijacks your images, at least they have your web address embedded into them. Check out Justin’s code at WordPress-Image-Watermark.
Zebra_Image
Zebra_Image is a super-lightweight and easy-to-use PHP library for image manipulation. This is a great alternative to Imagick, if Imagick is overkill, you can’t install Imagick on your web server, or you only need to perform some basic image-manipulation tasks like resizing, cropping, rotating, flipping, and/or sharpening images. This single-file PHP library requires only the GD extension, which usually comes precompiled with PHP.
Imagine
Somewhere between Imagick and Zebra_Image is probably Imagine. This object-oriented PHP library is very powerful, and you can use it to do almost any kind of image manipulation. Like Zebra_Image, Imagine is also a GD-based PHP library.
Dynamic Dummy Image Generator
The Dynamic Dummy Image Generator isn’t a PHP library, but it’s a great little tool that we wanted to mention that can help your WordPress website development efforts. You know when your client never provided you with the images they promised you three weeks ago? Using Dummy Image, you can dynamically create any sized images from a URL.
Snappy
Now this is cool! With Snappy, you can automatically create an image and/or a PDF from any URL or HTML page. Think of all the cool things you can do by autogenerating an image of any website you want.
PDF Generation
Programmatic PDF document generation and manipulation can be very useful. For instance, you may have been to a school or municipal website that has a ton of PDF documents with content (lunch menus, calendar, upcoming events, event registration, reading lists, meeting agendas/minutes, handbooks, reports, guides, etc.) that should probably be on the actual website and not in a PDF document. One key reason schools and municipalities use PDFs (besides “this is how we’ve always done it”) is that PDFs are easy to physically distribute, via email lists or hard copy. Although physical distribution can be a good thing, there are some disadvantages to having your content only in PDF format:
PDFs are not ADA compliant. This can open organizations to a lawsuit if they don’t make that content accessible.
PDFs are not mobile friendly. Even though you can see them on a mobile device, it is like looking at a nonresponsive website, one that you have to pinch and zoom to see what you want.
If you do have your content on both a web page and a PDF and need to make an update, you have to do it twice.
What if every web page on your website needed to have a downloadable PDF of it available? What if you have a bunch of online stats and reporting data from which you need to generate PDF documents? What if a calendar of events is constantly being updated, and you need to manually update a PDF and distribute it each time it changed? We can solve these and similar problems with code to streamline processes and save a ton of time and money. Let’s talk about some PHP libraries we like to use for automatically generating PDFs.
Snappy
We mentioned Snappy earlier, but we wanted to reiterate how cool and easy it is to generate PDFs of a web page via a provided URL or HTML. You can even generate a multiple-page PDF document by passing in multiple URLs. Want a detailed PDF document of your entire website? Just loop all of your pages and pass them into Snappy!
Snappy uses two popular open source HTML-to-PDF and HTML-to-image command-line tools: wkhtmltopdf and wkhtmltoimage. You can download and install the necessary binary files and easily install them on your server with Composer: A Dependency Manager for PHP.
FPDF
The F in FPDF stands for “free”! This is a great lightweight alternative to PDFlib if you are not generating too many PDF documents and they are not too complex. You can use FPDF to generate dynamic PDF documents with just PHP: it does not depend on other PHP libraries except for Zlib to enable compression and GD for GIF support, which both usually come precompiled with PHP. Some of the main functions of FDPF include the following:
__construct
Constructor
AcceptPageBreak
Accept or not automatic page break
AddFont
Add a new font
AddLink
Create an internal link
AddPage
Add a new page
AliasNbPages
Define an alias for number of pages
Cell
Print a cell
Close
Terminate the document
Error
Fatal error
Footer
Page footer
GetPageHeight
Get current page height
GetPageWidth
Get current page width
GetStringWidth
Compute string length
GetX
Get current x position
GetY
Get current y position
Header
Page header
Image
Output an image
Line
Draw a line
Link
Put a link
Ln
Line break
MultiCell
Print text with line breaks
Output
Save or send the document
PageNo
Page number
Rect
Draw a rectangle
SetAuthor
Set the document author
SetAutoPageBreak
Set the automatic page-breaking mode
SetCompression
Turn compression on or off
SetCreator
Set document creator
SetDisplayMode
Set display mode
SetDrawColor
Set drawing color
SetFillColor
Set filling color
SetFont
Set font
SetFontSize
Set font size
SetKeywords
Associate keywords with document
SetLeftMargin
Set left margin
SetLineWidth
Set line width
SetLink
Set internal link destination
SetMargins
Set margins
SetRightMargin
Set right margin
SetSubject
Set document subject
SetTextColor
Set text color
SetTitle
Set document title
SetTopMargin
Set top margin
SetX
Set current x position
SetXY
Set current x and y positions
SetY
Set current y position and optionally reset x
Text
Print a string
Write
Print flowing text
Other PDF-generation PHP libraries
Depending on your specific needs you may want to do a Google search for some of these and look them over in more detail:
wkhtmltopdf
mPDF
Dompdf
TCPDF
HTML2PdF
Geolocation and Geotargeting
There are many geolocation services available that do different things, like telling you the approximate location of a provided IP address or an approximate longitude and latitude based on a provided GPS location or WiFi network. If you have access to your visitors’ location, you can do so many cool things, including the following:
Restrict access to websites or specific web pages based on location.
Serve content on a website based on location like geotargeted ads.
Track a person or item location in near real time.
Find the closest location of something based on a provided location.
Maybe a school wants to add an extra layer of security for its web application and wants to give access to the login page to only people from within the same town or state as the school. This type of security feature might be necessary only if you want to lock down your application to a particular geographical location or locations, but it could greatly reduce the amount of potential hacking attempts. Instead of only allowing access to your web application, you could also lock out particular locations—for example, China. Maybe depending on your application, you know that anyone visiting from China should not have access.
Maybe a state website using WordPress wants to be able to show its visitors schools in the area when the website first loads. Suppose that “schools” is a CPT with address information stored as post meta. You also can achieve this by getting the end users’ location and doing a meta query to match schools in their area.
MaxMind GeoIP
MaxMind GeoIP gets data from a user’s IP address, such as their location and internet provider. MaxMind is a great service because it has a very extensive API and a free downloadable database.
You can download the PHP library with all of the functionality from the MaxMind website. To utilize its API, download and install the code from GitHub.
Geocoder PHP
Geocoder PHP is a PHP library that will assist you in building geo-aware web and mobile applications. Unlike MaxMind, which is its own geolocation provider, Geocoder PHP allows you to choose from multiple geolocation providers, including MaxMind. This PHP library makes calling and fetching geolocation data from various geolocation providers streamlined and consistent. To use the Geocoder PHP library, you need to choose a provider and an HTTP client/adapter. The following providers are currently available to this PHP library, and you can add your own if need be:
Algolia Places
ArcGIS Online
Bing Maps
FreeGeoIp
Geocode Earth
GeoIP
GeoIP2
Geonames
GeoPlugin
Google Maps
Google Maps Places
GraphHopper
Here
HostIp
IpInfo
IpInfoDB
ipstack
LocationIQ
Mapbox
MapQuest
MaxMind
MaxMind Binary
Nominatim
OpenCage
Pelias
Photon
PickPoint
TomTom
Yandex
Web-hosting geolocation
Some web hosts have geotargeting services baked into their platforms to offer you geolocation information like a site visitor’s continent, country, state/region, or city. You can use this data to display different content to visitors based on their location.
For instance, on top of WP Engine’s hosting services, it has an additional geolocation service that integrates with its platform’s custom WordPress caching system via a custom WordPress plugin. It stores cached visitor information in buckets that can be accessed via preset PHP variables and WordPress shortcodes. This is probably one of the fastest ways to integrate geolocation data with your website, but you must already be hosted with WP Engine.
File Compression and Archiving
You can imagine several use cases for being able to zip and unzip files programmatically, but most of the time you’ll be doing either of these two things:
WordPress core uses file decompression when you install a plugin. When you upload your own plugin or install one from the WordPress plugin repository, WordPress locates the ZIP file and unzips it into the wp-content/plugins directory on your WordPress installation.
At AppPresser.com, we depend on programmatically zipping and unzipping files heavily within our platform. In our App Builder UI, we offer file upload fields in which a user can upload a ZIP file of all their mobile app image resources that they could use locally within their mobile app. Our server-side PHP code receives the ZIP file, decompresses it, and moves all the files into a local directory within that app project directory. When an app is ready to be compiled, we automatically zip up all the source files in that app project directory and send it to PhoneGap Build to be compiled. The end result is all of the image resources originally uploaded in a single ZIP file are loaded locally from within the compiled mobile app.
We once worked on a large platform migration from a proprietary CMS to a WordPress Multisite network. The sites that we were migrating from were powered by individual MySQL databases. We were provided with an SFTP account that had all the websites to be migrated as individual ZIP files. Each ZIP file had a .sql export of that website’s database along with all of the source files and resources for that individual site. There were more than 8,000 sites to migrate, meaning more than 8,000 ZIP files to decompress and run custom migration scripts on to move all the data to WordPress. We were able to automate the entire migration process by programmatically looping through all the ZIP files in that SFTP account and unzipping them with PHP ZipArchive.
The PHP ZipArchive class has a ton of functionality to help you compress and decompress any of your files, and it’s usually baked into PHP by default. You can either compress files one at a time or just point to an entire directory to be compressed at once. The ZipArchive::open
method is the main function for opening a new ZIP archive for reading, writing, or modifying. It accepts a filename
parameter, which is a directory path and filename of the ZIP archive to open, and an optional flag
parameter that accepts one of four modes:
OVERWRITE
Overwrites the files in the specified archive if they already exists.
CREATE
Creates a new archive if it does not already exist.
EXCL
Used to check whether an archive already exists.
CHECKCONS
Used to perform additional consistency checks on the archive and give an error if they fail.
Compressing individual files into an archive
Here is some basic code for adding files to a ZIP archive that you create one file at a time. As you can imagine, you could write some code to loop through any files you want, adding them to your new ZIP file however you want:
<?
php
// First create a ZipArchive Instance
$zip
=
new
ZipArchive
();
// Use the open() method to create a zip file on the server
$zip
->
open
(
'compressed-dir-path/messenlehner-kids.zip'
,
ZipArchive
::
CREATE
);
// Use the addFile() method to add a file to your zip
$zip
->
addFile
(
'some-dir-path/index.html'
,
'index.html'
);
// You can also add files to subdirectories within the zip
$zip
->
addFile
(
'some-dir-path/dalya.png'
,
'images/dalya.png'
);
$zip
->
addFile
(
'some-dir-path/brian.png'
,
'images/brian.png'
);
$zip
->
addFile
(
'some-dir-path/nina.mp4'
,
'videos/nina.png'
);
// You can also change a file name while you are adding it to the zip
$zip
->
addFile
(
'some-dir-path/CWM.png'
,
'images/cam.png'
);
$zip
->
addFile
(
'some-dir-path/babyA.png'
,
'images/aksel.png'
);
// Call the close() method to finish and save your new zip
$zip
->
close
();
?>
Compressing multiple files into an archive
ZipArchive has functions for retrieving various files from provided directory paths so you can add files to your ZIP archive file in bulk instead of one by one:
addGlob()
This method allows you to identify files of defined file types.
addPattern()-
This method allows you to use regular expressions to identify files in a directory based on any pattern in their filename.
Following is an example using both the addGlob()
and addPattern()
methods to add all .png and .jpg images and .mp4 videos from provided directories into a ZIP file:
<?
php
// First create a ZipArchive Instance
$zip
=
new
ZipArchive
();
// Use the open() method to create a zip file on the server
$zip
->
open
(
'compressed-dir-path/messenlehner-kids.zip'
,
ZipArchive
::
CREATE
);
// Set options array to add the directory 'videos' to the zip file
$options
=
array
(
'add_path'
=>
'videos/'
,
'remove_all_path'
=>
TRUE
);
// Add 'mp4' files from a given directory to the 'videos' directory in the
zip
file
$zip
->
addGlob
(
'some-dir-path/*.mp4'
,
0
,
$options
);
// Set options array to add the directory 'images' to the zip file
$options
=
array
(
'add_path'
=>
'images/'
,
'remove_all_path'
=>
TRUE
);
// Add both 'jpg' and 'png' files from a given directory to the 'images'
directory
in
the
zip
file
$zip
->
addGlob
(
'some-other-dir-path/*.{jpg, png}'
,
GLOB_BRACE
,
$options
);
// You can also use regular expressions to get any files from a given directory
$zip
->
addPattern
(
'/\.(?:jpg|png)$/'
,
'another-dir-path'
,
$options
);
// Call the close() method to finish and save your new zip
$zip
->
close
();
?>
Extracting files from an archive
To automatically unzip a compressed archive file, you can use the extractTo()
method, which accepts two parameters:
destination
Where the files in the ZIP are being unzipped and saved to.
entries
The files you want to extract from the ZIP. You can grab one file at a time, an array of files, or, if you want to extract all the files in the ZIP, you can exclude this parameter:
<?
php
// How to extract files from a zip file on your server
$zip
=
new
ZipArchive
();
$zip
->
open
(
'compressed-dir-path/messenlehner-kids.zip'
,
ZipArchive
::
CREATE
);
// Use the extractTo() method to extract files in a zip on the server
// Extracts one file
$zip
->
extractTo
(
'uncompressed-dir-path/'
,
'images/aksel.png'
);
// Extracts files in an array
$zip
->
extractTo
(
'uncompressed-dir-path/'
,
array
(
'images/cam.png'
,
'images/nina.png'
)
);
// Extracts all files in the zip
$zip
->
extractTo
(
'uncompressed-dir-path/'
);
$zip
->
close
();
?>
Other compression and archive PHP libraries
By default WordPress depends on ZipArchive for any file compression/decompression. WordPress actually first checks to see whether ZipArchive is available; if not, it falls back to another popular PHP library called PclZip. There are also some other compression and archive PHP libraries that you can use if you like:
Following are some PHP libraries to make your life as a developer just a little bit easier. There are a ton of great tools out there, but here are a few goodies.
PHPUnit
If you haven’t heard about unit testing, you should look into it. It’s a great method for regression testing your code and for automatically locating bugs/errors within your code. Think of it as writing code to automate the testing of your code. With PHPUnit you can set up specific unit tests to be performed on particular functions within your code to verify that those functions are doing everything they are supposed to be doing. We can’t iterate enough how important unit testing can be when you have multiple hands in the cookie jar. Give your clients and yourself more peace of mind by running unit tests before deploying any code updates to a production environment.
Tip
You can and should charge extra for incorporating unit testing into your development process.
phpDocumentor
Every good developer knows that they should always provide good comments and additional documentation so any other developers looking at their code can easily figure out what is going on. This practice is also good for you if you’re looking at old code that you maybe wrote years ago, amiright? At the very least you should always leave good comments in your code. phpDocumentor is a great tool for automatically generating documentation from your code comments.
Faker
Faker is a great PHP library for automatically generating dummy content that can be used to populate a database, populate fake WordPress users, display fake content on a website you are building before you have real content, generating an XML feed, populating custom API endpoints, unit testing, or whatever you want to use it for. You can use the following formatters to make fake data, or you can create your own formatters using functions already defined in the Base
class:
Base
Lorem Ipsum Text
Person
Address
Phone Number
Company Real
Text Date and Time
Internet User Agent
Payment
Color
File
Image
Uuid
Barcode
Miscellaneous Biased
Html Lorem
Goutte, a PHP-based website scraper
Don’t have access to a website data source and need to migrate it to WordPress? Need product data from multiple websites with no data feeds? Page scraping can be a great solution to some of your problems, but it can also be very time-consuming to programmatically find the patterns you are looking for within a web page (hopefully there is some consistency) and then parse that web page HTML markup based on the patterns to extract the data you need. If you are scraping content from multiple web pages, this can be a very daunting task.
Goutte is an awesome tool for screen scraping just about any data from any provided HTML markup, and you also can use it to parse XML. Goutte makes it easy for you to parse or crawl the data returned from an HTTP request using predefined methods that will easily assist you in identifying and extracting any HTML elements. Here are some of the cool things you can easily do with Goutte:
Extract links from content.
Extract images from content.
Extract titles out of heading tags.
Extract content out of <div>
tags by their ID or class name.
Extract sibling, parent, or child elements of an ordered or unordered list.
Extract any content from within any HTML tags.
Extract specific nodes from XML.
Automatically click links.
Automatically submit web forms.
Automatically log into website (if you have a correct username and password).
Whoops, for user-friendly PHP errors
Whoops is a PHP library available as a Composer package that allows you to handle errors and exceptions in your code more elegantly. You can completely customize your PHP errors to include more helpful information than just the default PHP error message, which can sometimes be difficult to decipher. This is a great tool for managing and displaying errors to aid you in your troubleshooting efforts.