15 best PHP Libraries for Developers

PHP is widely used server side scripting language. Every day lots of useful libraries released with help of composer and github they are easy to find and use. PHP Library allows developers to take full advantage of Object Oriented Programming in PHP. In this article we collect a list of 15 best PHP Libraries for Developers. That will help to developers to do number of things easily with less efforts.

1. ImageWorkshop — Image Manipulation with Layers

PHP Image Workshop is an open source class using GD library that helps you to manage images with PHP.with this you can create thumbnails or pasting watermarks and also to do more complex tasks multiple superimpositions, image positioning.

Example:

// We initialize the norway layer from the picture norway.jpg

$norwayLayer=ImageWorkshop::initFromPath(‘/path/to/images/norway.jpg’);

// We initialize the watermark layer from the picture watermark.png

$watermarkLayer=ImageWorkshop::initFromPath(‘/path/to/images/watermark.png’);

// This is the generated image !

$image=$norwayLayer->getResult();

header(‘Content-type: image/jpeg’);

imagejpeg($image,null,95);// We choose to show a JPG with a quality of 95%

exit;

2. PHP Error — error messages,Syntax highlighting

PHP Error is an open source PHP library for converting the standard PHP error messages -that are usually faced during the development process- into better ones.It integrates tightly into any PHP environment (works on all cases, only in development environment, only in some projects, etc.) and displays the errors with syntax highlighting.

Example:

<?php

// place at start of site

require(‘php_error.php’);

\php_error\reportErrors();

// wordpress

// open the ‘functions.php’ file in your WordPress theme

require(‘php_error.php’);

\php_error\reportErrors();

// codeigniter

// place php_error.php in your application folder.

require(__DIR__.’/../php_error.php’);

\php_error\reportErrors(array(

‘application_folders’=>’application’,

‘ignore_folders’=>’system’

));

3. Validation — Input Validation Engine

The most awesome validation engine ever created for PHP is Validation

Example:

useRespect\Validation\Validator asv;

// Simple Validation

$number=123;

v::numeric()->validate($number);//true

// Chained Validation

$usernameValidator=v::alnum()->noWhitespace()->length(1,15);

$usernameValidator->validate(‘alganet’);//true

// Validating Object Attributes

$user=newstdClass;

$user->name=’Alexandre’;

$user->birthdate=’1987–07–01';

// Validate its attributes in a single chain:

$userValidator=v::attribute(‘name’,v::string()->length(1,32))

->attribute(‘birthdate’,v::date()->minimumAge(18));

$userValidator->validate($user);//true

4. phpfastcache : The PHP high-performance object caching system ever.

phpFastCache is a high-performance, distributed object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

Example:

<?php

// In your config file

include(“phpfastcache.php”);

// phpFastCache::setup(“storage”,”redis”); default global for everywhere.

// phpFastCache support “redis”, “cookie”, “apc”, “memcache”, “memcached”, “wincache” ,”files”, “sqlite” and “xcache”

// You don’t need to change your code when you change your caching system, blank will use default global:

$cache=phpFastCache();

// $cache = phpFastCache(“memcache”);

// In your Class, Functions, PHP Pages

// try to get from Cache first. product_page = YOUR Identity Keyword

$products=$cache->get(“product_page”);

if($products==null){

$products=YOUR DB QUERIES||GET_PRODUCTS_FUNCTION;

// set products in to cache in 600 seconds = 10 minutes and 0 = never expired

$cache->set(“product_page”,$products,600);

// Output Your Contents $products HERE

// LOOP | echo $products

5. Omnipay- Payment Processing Library

Omnipay is a payment processing library for PHP. It has been designed based on ideas from Active Merchant, plus experience implementing dozens of gateways for CI Merchant.

Example:

useOmnipay\CreditCard;

useOmnipay\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());

6. 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:

Example:

$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();

7. PHP CPP Library — for developing PHP extensions.

The PHP-CPP library is a C++ library for developing PHP extensions. It offers a collection of well documented and easy-to-use classes that can be used and extended to build native extensions for PHP.

Example:

//Native c++ function

Php::Value hello_world()

return”hello world!”;

// With PHP-CPP you can export this function to PHP with only one single C++ method call:

extension.add(“hello_world”,hello_world);

//Working with parameters and return values is just as easy:

Php::Value my_plus(Php::Parameters&params)

returnparams[0]+params[1];

//The method call to export the above C++ function:

extension.add(“my_plus”,my_plus,{

Php::ByVal(“a”,Php::numericType),

Php::ByVal(“b”,Php::numericType)

});

8. Mustache.php -simple, logic-less template engine

Mustache.php “logic-less” because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some with nothing, and others with a series of values. The Benefit of Mustache.php is that you can reuse your templates in both client and server side

$m=newMustache_Engine;

echo$m->render(‘Hello {{planet}}’,array(‘planet’=>’World!’));// “Hello World!”

9.Geocoder-powerful abstraction layer for geocoding manipulations

Geocoder is a PHP library which helps you build geo-aware applications by providing a powerful abstraction layer for geocoding manipulations.

Example:

<?php

$geocoder=new\Geocoder\ProviderAggregator();

$geocoder->registerProviders([

new\Geocoder\Provider\GoogleMaps(

$adapter,$locale,$region,$useSsl

new\Geocoder\Provider\GoogleMapsBusiness(

$adapter,’<CLIENT_ID>’,’<PRIVATE_KEY>’,$locale,$region,$useSsl

new\Geocoder\Provider\Yandex(

$adapter,$locale,$toponym

new\Geocoder\Provider\MaxMind(

$adapter,’<MAXMIND_API_KEY>’,$service,$useSsl

new\Geocoder\Provider\ArcGISOnline(

$adapter,$sourceCountry,$useSsl

]);

$geocoder->registerProvider(

new\Geocoder\Provider\Nominatim(

$adapter,’http://your.nominatim.server',$locale

$geocoder

->using(‘google_maps’)

->geocode(‘…’);

$geocoder

->limit(10)

->reverse($lat,$lng);

10. PHP-PasswordLib- library for generating and validating passwords

PHP-PasswordLib aims to be an all-inclusive cryptographic library for all cryptographic needs. It is meant to be easy to install and use, yet extensible and powerful enough for even the most experienced developer.

<?php

$lib=newPasswordLib\PasswordLib();

$hash=$lib->createPasswordHash($password);

$boolean=$lib->verifyPasswordHash($password,$hash);

11. HTMLPurifier — XSS Protection

HTML Purifieris a standards-compliant HTML filter library written in PHP.HTML Purifier protects your code from XSS attacks by using a combination of robust whitelists and agressive parsing

Example:

<?php

require_once’/path/to/HTMLPurifier.auto.php’;

$config=HTMLPurifier_Config::createDefault();

$purifier=newHTMLPurifier($config);

$clean_html=$purifier->purify($dirty_html);

12.Faker — generates fake data

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 this will generate fake data.

<?php

// require the Faker autoloader

require_once’/path/to/Faker/src/autoload.php’;

// use the factory to create a Faker\Generator instance

$faker=Faker\Factory::create();

// generate data by accessing properties

echo$faker->name;// ‘Lucy Cechtelar’;

echo$faker->address;

// “426 Jordy Lodge

// Cartwrightshire, SC 88120–6700"

echo$faker->text;

// Sint velit eveniet. Rerum atque repellat voluptatem quia …

13.Snappy- For thumbnail, snapshot or PDF generation from a url or a html page

Snappy is a PHP5 library allowing thumbnail, snapshot or PDF generation from a url or a html page.

<?php

require_once’/path/to/snappy/src/autoload.php’;

useKnp\Snappy\Pdf;

$snappy=newPdf(‘/usr/local/bin/wkhtmltopdf’);

// or you can do it in two steps

$snappy=newPdf();

$snappy->setBinary(‘/usr/local/bin/wkhtmltopdf’);

// Display the resulting pdf in the browser

// by setting the Content-type header to pdf

$snappy=newPdf(‘/usr/local/bin/wkhtmltopdf’);

header(‘Content-Type: application/pdf’);

header(‘Content-Disposition: attachment; filename=”file.pdf”’);

echo$snappy->getOutput(‘http://www.github.com');

// Merge multiple urls into one pdf

// by sending an array of urls to getOutput()

$snappy=newPdf(‘/usr/local/bin/wkhtmltopdf’);

header(‘Content-Type: application/pdf’);

header(‘Content-Disposition: attachment; filename=”file.pdf”’);

echo$snappy->getOutput(array(‘http://www.github.com','http://www.knplabs.com','http://www.php.net'));

// .. or simply save the PDF to a file

$snappy=newPdf(‘/usr/local/bin/wkhtmltopdf’);

$snappy->generateFromHtml(‘<h1>Bill</h1><p>You owe me money, dude.</p>’,’/tmp/bill-123.pdf’);

// Pass options to snappy

// Type wkhtmltopdf -H to see the list of options

$snappy=newPdf(‘/usr/local/bin/wkhtmltopdf’);

$snappy->setOption(‘disable-javascript’,true);

$snappy->setOption(‘no-background’,true);

$snappy->setOption(‘allow’,array(‘/path1’,’/path2'));

$snappy->setOption(‘cookie’,array(‘key’=>’value’,’key2'=>’value2'));

$snappy->setOption(‘cover’,’pathToCover.html’);

// .. or pass a cover as html

$snappy->setOption(‘cover’,’<h1>Bill cover</h1>’);

$snappy->setOption(‘toc’,true);

14. Colorjizz-manipulating and converting colors

Colorjizz is a tiny library that can convert between different color formats and do simple color arithmetic

//ColorJizz can convert to and from any of the supported color formats:

<?php

useMischiefCollective\ColorJizz\Formats\Hex;

$red_hex=newHex(0xFF0000);

$red_cmyk=$hex->toCMYK();

echoget_class($red_cmyk);// MischiefCollective\ColorJizz\Formats\CMYK

echo$red_cmyk;// 0,1,1,0

Opauth — multi-provider authentication framework for PHP

Opauth is an open source PHP library that removes the inconsistencies between providers and offers a standardized method for dealing with them. Currently, 3 providers are almost plug ‘n’ play: Google, Twitter + Facebook and there are more to come. Also, there is support for dealing with any other Opauth provider.

I hope you find the list handy and useful for your development tasks, if you are aware of any other useful php libraries, then please provide us your feedback by dropping a comment below. Enjoy !!


Originally published at phplesson.com on May 7, 2015.

Like what you read? Give Rohit Gilbile a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.