21 PHP Libraries You Should Know About

21 PHP Libraries You Should Know About
by Janeth Kent Date: 24-07-2013 php libraries coding developers programming web development

The aim of the Standard PHP Library-or SPL is to provide a standard library of interfaces which allows developers to take full advantage of object-oriented programming in PHP.

Therefore in this article we have collected 21 of the best PHP Libraries which will assist and help developers to simplify their work and serve their development tasks.

1. Dispatch – Micro Framework

Dispatch is a PHP micro-framework. It's very small (22 functions at the moment) and very straightforward to use. No classes, no namespaces. Dispatch requires at least PHP 5.4 to work.

You can define URL rules and methods to better organize your application. This is perfect for APIs, simple sites or prototypes:

// include the library  include 'dispatch.php';    
// define your routes  get('/greet', function () {      
// render a view      render('greet-form');  
});    
// post handler  post('/greet', function () {      
$name = from($_POST, 'name');     
 // render a view while passing some locals      
render('greet-show', array('name' => $name));  
});    
// serve your site  dispatch();

2. Klein – Lightning fast router for PHP

Klein  is a lightning fast router for PHP 5.3+

Here is an example:

respond('/[:name]', function ($request) 
{      
echo 'Hello ' . $request->name;  
});

You can also subscribe to specific HTTP methods and use regexes as paths:

respond('GET', '/posts', $callback);  
respond('POST', '/posts/create', $callback);  
respond('PUT', '/posts/[i:id]', $callback);  
respond('DELETE', '/posts/[i:id]', $callback);    
// To match multiple request methods:  
respond(array('POST','GET'), $route, $callback);    
// Or you might want to handle the requests in the same place  
respond('/posts/[create|edit:action]?/[i:id]?', 
function ($request, $response) {      
switch ($request->action) {          
// do something      
}  
});

3. Ham – Routing Library with Caching

Ham is also a lightweight routing framework but it utilizes caching for even more speed gains.

It's a PHP Microframework for use with whatever you like. Basically just a fast router with nice syntax, and a cache singleton. Will add more things as I go, like perhaps an extension system, autoloader and some other stuff to make developing in PHP less irritating than it currently is.

Routes are converted to regex and cached so this process does not need to happen every request. Furthermore, the resolved route for a given URI is also cached so on most requests thare is no regex matching involved.

There is also now the ability to mount apps on routes within apps, so one could make an administrator app, then mount it on the main app at /admin.

4. Assetic – Asset Management

Assetic  is an asset management framework for PHP.. It combines and minifies your CSS/JS assets. Here is how it is used:

use Assetic\Asset\AssetCollection;  
use Assetic\Asset\FileAsset;  
use Assetic\Asset\GlobAsset;    
$js = new AssetCollection(array(new GlobAsset('/path/to/js/*'),
new FileAsset('/path/to/another.js'),  ));    
// the code is merged when the asset is dumped  
echo $js->dump();

5. ImageWorkshop – Image Manipulation with Layers

ImageWorkshop   is an open source class using GD library that helps you to manage images with PHP.

This class is thought like photo editing software (Photoshop, GIMP...): you can superimpose many layers or even layer groups, each layer having a background image.

An ImageWorkshopLayer object could be 2 different things depending on how you want to use it:

  • a layer: this is a rectangle which has a transparent background image by default and where you can paste images (from your hard drive or an upload form...) on its background.
  • a group layer: a layer that includes multiple sublayers at different level in its stack, all leveled on the top of its background. If you perform an action on the group, all its sublayers (and subgroups) will be affected !

Understand that an ImageWorkshop object is a layer AND a group at the same time, unlike Photoshop (a group doesn't have a background): it has got a background image(transparent by default) and a stack of sublayers (empty by default) on the top of its background.

When you have finished manipulating your layers, you just have to execute a method to get the merged image of all layer backgrounds !

// We initialize the italy layer from the picture italy.jpg  
$italyLayer = ImageWorkshop::initFromPath
('/path/to/images/italy.jpg');    
 // We initialize the watermark layer from the picture watermark.png  
$watermarkLayer = ImageWorkshop::initFromPath('/path/to/images/watermark.png');     
$image = $italyLayer->getResult(); 
// This is the generated image !     
header('Content-type: image/jpeg');  
imagejpeg($image, null, 95); 
// We choose to show a JPG with a quality of 95%  exit;

6. Snappy – Snapshot/PDF Library

Snappy  is a PHP5 library allowing thumbnail, snapshot or PDF generation from a url or a html page. It uses the excellent webkit-based wkhtmltopdf and wkhtmltoimage available on OSX, linux, windows like this:

require_once '/path/to/snappy/src/autoload.php';     
use Knp\Snappy\Pdf;     
// Initialize the library with the  
// path to the wkhtmltopdf binary:  
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');     
// Display the resulting pdf in the browser  
// by setting the Content-type header to pdf:     
header('Content-Type: application/pdf');  
header('Content-Disposition: attachment; filename="file.pdf"');     echo $snappy->getOutput('http://www.github.com');

Keep in mind that calling external binaries might not be allowed by your hosting provider.

7. Idiorm – Lightweight ORM Library

Idiorm is a lightweight nearly-zero-configuration object-relational mapper and fluent query builder for PHP5.

Tested on PHP 5.2.0+ - may work on earlier versions with PDO and the correct database drivers.

Released under a BSD license.

Features:

  • Makes simple queries and simple CRUD operations completely painless.
  • Gets out of the way when more complex SQL is required.
  • Built on top of PDO.
  • Uses prepared statements throughout to protect against SQL injection attacks.
  • Requires no model classes, no XML configuration and no code generation: works out of the box, given only a connection string.
  • Consists of one main class called ORM. Additional classes are prefixed with Idiorm. Minimal global namespace pollution.
  • Database agnostic. Currently supports SQLite, MySQL, Firebird and PostgreSQL. May support others, please give it a try!
  • Supports collections of models with method chaining to filter or apply actions to multiple results at once.
  • Multiple connections supported

8. Underscore – PHP’s Utility Belt

Underscore  is a PHP port of the popular Underscore.js library. In addition to porting Underscore's functionality, Underscore.php includes matching unit tests. Underscore.php requires PHP 5.3 or greater.

Underscore.php is hosted on GitHub and open sourced under the MIT license.

Examples:

__::each(array(1, 2, 3), function($num) { echo $num . ','; }); // 1,2,3,    
$multiplier = 2; 
 __::each(array(1, 2, 3), function($num, $index) use ($multiplier) {    
echo $index . '=' . ($num * $multiplier) . ',';  });  
// prints: 0=2,1=4,2=6,    
__::reduce(array(1, 2, 3), function($memo, $num) { return $memo + $num; }, 0); // 6    
__::find(array(1, 2, 3, 4), function($num) { return $num % 2 === 0; }); // 2    
__::filter(array(1, 2, 3, 4), function($num) { return $num % 2 === 0; }); // array(2, 4)

The library also has support for chaining, which makes it even more powerful.

9. Requests – Easy HTTP Requests

Requests  is a HTTP library written in PHP, for human beings. It is roughly based on the API from the excellent Requests Python library. Requests is ISC Licensed (similar to the new BSD license) and has no dependencies.

Despite PHP's use as a language for the web, its tools for sending HTTP requests are severely lacking. cURL has an interesting API, to say the least, and you can't always rely on it being available. Sockets provide only low level access, and require you to build most of the HTTP response parsing yourself.

$headers = array('Accept' => 'application/json');  
$options = array('auth' => array('user', 'pass'));  
$request = Requests::get('https://api.github.com/gists', $headers, $options);    
var_dump($request->status_code);  // int(200)    
var_dump($request->headers['content-type']);  
// string(31) "application/json; charset=utf-8"    
var_dump($request->body);  // string(26891) "[…]"

With this library, you can send HEAD, GET, POST, PUT, DELETE and PATCH HTTP requests, add files and parameters with arrays, and access all the response data.

10. Buzz – Simple HTTP Request Library

Buzz  is a lightweight PHP 5.3 library for issuing HTTP requests. Here is an example:

$request = new Buzz\Message\Request('HEAD', '/', 'http://google.com'); 
$response = new Buzz\Message\Response();    
$client = new Buzz\Client\FileGetContents();  
$client->send($request, $response);    
echo $request;  echo $response;

11. Goutte – Web Scraping Library

Goutte Goutte is a screen scraping and web crawling library for PHP.

Goutte provides a nice API to crawl websites and extract data from the HTML/XML responses. Goutte works with PHP 5.3.3 or later.

12. Carbon – DateTime Library

Carbon is a simple API extension for DateTime with PHP 5.3+. For example:

printf("Right now is %s", Carbon::now()->toDateTimeString());  
printf("Right now in Vancouver is %s", 
Carbon::now('America/Vancouver'));  //implicit __toString()  
$tomorrow = Carbon::now()->addDay();  
$lastWeek = Carbon::now()->subWeek();  
$nextSummerOlympics = Carbon::createFromDate(2012)->addYears(4);    
$officialDate = Carbon::now()->toRFC2822String();    
$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;    
$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');    
$worldWillEnd = Carbon::createFromDate(2012, 12, 21, 'GMT');    
// comparisons are always done in UTC  
if (Carbon::now()->gte($worldWillEnd)) {     
die();  
}    
if (Carbon::now()->isWeekend()) {     echo 'Party!';  }    
echo Carbon::now()->subMinutes(2)->diffForHumans(); 
// '2 minutes ago'    
// ... but also does 'from now', 'after' and 'before'  
// rolling up to seconds, minutes, hours, days, months, years    
$daysSinceEpoch = Carbon::createFromTimeStamp(0)->diffInDays();

13. Ubench – Micro Benchmarking Library

Ubench is a micro library for benchmarking your PHP code. It monitors execution time and memory usage.

14. Validation – Input Validation Engine

Validation is the most awesome validation engine ever created for PHP.

  • Fluent/Chained builders like v::numeric()->positive()->between(1, 256)->validate($myNumber) (more samples below)
  • Informative, awesome exceptions
  • More than 30 fully tested validators

15. Filterus – Filtering Library

Filterus is another filtering library, but it can not only validate, but also filter input to match a preset pattern.

Each filter class has two primary methods:

  • $filter->filter($var) - returns a modified version of $var filtered to the options. If it cannot be safely modified, a default vlaue will be returned.
  • $filter->validate($var) - Returns a boolean identifying if the value is valid.

16. Faker – Fake Data Generator

Faker  is a PHP library that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.

Faker is heavily inspired by Perl's Data::Faker, and by ruby's Faker.

Faker requires PHP >= 5.3.3.

17. Mustache.php – Elegant Templating Library

Mustache is a popular templating language that has implementations in practically every programming languages. This gives you the benefit that you can reuse your templates in both client and server side. Mustache.php is an implementation that uses – you guessed it – PHP:

$m = new Mustache_Engine;  
echo $m->render('Hello {{planet}}', 
array('planet' => 'World!')); 
// "Hello World!"

18. Gaufrette – File System Abstraction Layer

Gaufrette  is a PHP5 library that provides a filesystem abstraction layer.

This project is under intensive development but we do not want to break BC.

Imagine you have to manage a lot of medias in a PHP project. Lets see how to take this situation in your advantage using Gaufrette.

The filesystem abstraction layer permits you to develop your application without the need to know were all those medias will be stored and how.

Another advantage of this is the possibility to update the files location without any impact on the code apart from the definition of your filesystem. In example, if your project grows up very fast and if your server reaches its limits, you can easily move your medias in an Amazon S3 server or any other solution.

19. Omnipay – Payment Processing Library

Omnipay is a payment processing library for PHP. It has a clear and consistent API and supports dozens of gateways. With this library, you only need to learn one API and work with a variety of payment processors. Here is an example:

use Omnipay\CreditCard;  
use Omnipay\GatewayFactory;    
$gateway = GatewayFactory::create('Stripe');  
$gateway->setApiKey('abc123');    
$formData = ['number' => '4111111111111111', 'expiryMonth' => 6, 'expiryYear' => 2016];  
$response = $gateway->purchase(['amount' => 1000, 'card' => $formData]);    
if ($response->isSuccessful()) {     
// payment was successful: update database      
print_r($response);  } elseif ($response->isRedirect()) {      
// redirect to offsite payment gateway      
$response->redirect();  } else {      
// payment failed: display message to customer      
exit($response->getMessage());  }

Using the same consistent API makes it easy to support multiple payment processors or to switch as the need arises.

20. Upload – For Handling File Uploads

Upload is a library that simplifies file uploading and validation. When a form is submitted, the library can check the type of file and size:

$storage = new \Upload\Storage\FileSystem('/path/to/directory');  
$file = new \Upload\File('foo', $storage);    
// Validate file upload  $file->addValidations(array(      
// Ensure file is of type "image/png"      
new \Upload\Validation\Mimetype('image/png'),        
// Ensure file is no larger than 5M (use "B", "K", M", or "G")      new \Upload\Validation\Size('5M')  ));    // Try to upload file  try {      // Success!      $file->upload();  } catch (\Exception $e) {      // Fail!      $errors = $file->getErrors();  }

This will save you lots of tedious code.

21. HTMLPurifier – HTML XSS Protection

HTMLPurifier (on github) is a standards-compliant HTML filter library written in PHP. HTML Purifier will not only remove all malicious code (better known asXSS) with a thoroughly audited, secure yet permissive whitelist, it will also make sure your documents are standards compliant, something only achievable with a comprehensive knowledge of W3C's specifications.

 

 
by Janeth Kent Date: 24-07-2013 php libraries coding developers programming web development hits : 16823  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN AND DEVELOPMENT.

 
 
 

Related Posts

Examine the 10 key PHP functions I use frequently

PHP never ceases to surprise me with its built-in capabilities. These are a few of the functions I find most fascinating.   1. Levenshtein This function uses the Levenshtein algorithm to calculate the…

How to Track Flight Status in real-time using the Flight Tracker API

The Flight Tracker API provides developers with the ability to access real-time flight status, which is extremely useful for integrating historical tracking or live queries of air traffic into your…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

How to make your own custom cursor for your website

When I started browsing different and original websites to learn from them, one of the first things that caught my attention was that some of them had their own cursors,…

8 benefits of having a website for your business

At this moment, the Internet is a phenomenon that is sweeping the world. It has been able to interconnect millions of users all over the planet. People have made the…

Open source web design tools alternatives

There are many prototyping tools, user interface design tools or vector graphics applications. But most of them are paid or closed source. So here I will show you several open…

How to create a .onion domain for your website

The dark web, a hidden network accessed through the Tor browser, offers enhanced privacy and anonymity for websites. To establish a presence on the dark web, you can create a…

PHP - The Singleton Pattern

The Singleton Pattern is one of the GoF (Gang of Four) Patterns. This particular pattern provides a method for limiting the number of instances of an object to just one.…

How to access webcam and grab an image using HTML5 and Javascript

We often use webcams to broadcast video in real time via our computer. This broadcast can be viewed, saved and even shared via the Internet. As a rule, we need…

How to Send Email from an HTML Contact Form

In today’s article we will write about how to make a working form that upon hitting that submit button will be functional and send the email (to you as a…

Looping through a matrix with JavaScript

We were already talking about how to multiply arrays in JavaScript and we realised that we had not explained something as simple as traversing an array with Javascript. So we…

How to multiply matrices in JavaScript

It may seem strange to want to know how to multiply matrices in JavaScript. But we will see some examples where it is useful to know how to perform this…

Clicky