PHP Tips

Must Watch!



MustWatch






enable error reporting

Error reporting feature is one of the best Useful PHP trick for Developers. The best thing to cope with errors is to set the system to display errors. To set the settings you have to alter the php.ini file when you develop your site. Include these two lines in the beginning. error_reporting ( E_ALL ) ; ini_set ( 'display_errors' , 1 ) ; The following code helps you to see both types of errors whether the fatal errors that produce the dreaded white screen as warnings and notices that may be bugs to fix.

Prevents SQL injection

Security holes are the biggest cause of the bad reputation of PHP but PHP tips for website development are here. There are many ways to avoid SQL injection but the simplest one escapes any variable that we will use in the database. The code should look like this: $query_result = mysql_query ( "SELECT * FROM WHERE Ex_table ex_field = \" ".mysql_real_escape_string( $ ex_field )." \ " " ) ;

Use the _once() function with caution

PHP developers prefer using include() or function require() to call other files, libraries or classes, but using the include_eleven() and require_eleven(), are the PHP tricks for web developer. Both the functions have the same functionality but the advantage is that it prevent the files, classes or loaded libraries to be loaded again which cause duplication and undesired states in the code.

Learn to handle ternary operators

?: Ternary Operator $action = (empty($_POST['action'])) ? 'default' : $_POST['action']; // The above is identical to this if/else statement if (empty($_POST['action'])) { $action = 'default'; } else { $action = $_POST['action']; } The best PHP tips and trick for good performance is to use ternary operators as an alternative to simple IF constructions. For instance: $age = ( !empty ( $ _ GET [ 'age ] ) ? $ _ GET [ 'age' ] : 58 ) ; This would help your code to get lighter and can be nested without problems.

The code to connect with databases

try { $conn = new PDO ( "mysql: host = localhost; dbname = database ' , $ user , $ pass ) ; $conn -> setAttribute ( PDO :: ATTR_ERRMODE , PDO :: ERRMODE_EXCEPTION ) ; } Catch ( PDOException $e ) { Echo "ERROR:". $e -> getMessage ( ) ; }

Use single quotes rather than double

Just use single quote (“) other than double (” “). Trust me! it saves you a lot of time and the performance of your server.

Clean URLs quickly with.htaccess

The file.htaccess – the best yet simple way to make the URLs more simpler for human eye as well as for SEO. A hidden file that serves a lot with Apache directives. The services that this file provides are performing redirection and clean URLs do not cease to be redirected to after all. One of the best tip and trick for PHP based application improvements. RewriteEngine On RewriteRule ^ ( [ a - zA - Z0 - 9 ] + ) $ index. Php? Page = $ 1 This code is the life saver for many PHP developers that can prevent horrible URLs and make it sleek and simple, phew!

Know all the Problems of isset()

One of the PHP tricks for web developer is to understand what isset() function do. Make sure that you know at what time isset() function returns false and on which time it answers true. This function returns True if the variable is not NULL. Yes you read it not NULL. Just like so, if NULL can be a valid value of the variable,We surely have a problem sire! $foo = null ; if ( isset( $ foo ) ) // returns false And the solution is: Use get_defined_vars( ); $foo = NULL ; $vars = get_defined_vars( ); if ( array_key_exists ( 'foo' , $ vars ) ) // returns True

Use a switch instead of stringing If Statements

The useful PHP trick for Developers- use Switch instead of crazy Ifs. Advantage? The code will execute faster thus performance is increased. The usage of Switch statements allows you to go beyond the use of if-else if-else chains. switch ($color ) { case 'white' : echo "The color is White" ; break ; case 'blue' : echo "The color is Blue" ; break ; case 'green' : echo "The color is Green" ; break ; case 'black' : echo "Color is black" ; break ; }

Take up cURL

The method to retrieve a file from another server is to use the powerful way cURL, instead of using file_get_contents() function which is easy to use but come on, it's like having death on your computer. The following code is the example of the use cURL: $c = curl_init ( ) ; curl_setopt ( $c , CURLOPT_URL , $URL ) ; curl_setopt ( $c , CURLOPT_TIMEOUT , 15 ) ; curl_setopt ( $c , CURLOPT_RETURNTRANSFER , true ) ; $content = curl_exec ( $c ) ; $status = curl_getinfo ( $c , CURLINFO_HTTP_CODE ) ; curl_close ( $c ) ;

Password Encryption

Often developers ask Tips to improve the website, well here is one, PHP is always on your side and it encrypts your passwords for you. I am talking about the PHP 5.5+ versions, Just store the passwords in your database as. $enc_pass = password_hash ( $submitted_pass , PASSWORD_DEFAULT ) ; To check if password is correct or not: if ( password_verify ( $submitted_pass , $stored_pass ) ) { // User successfully authenticated }

Advanced PHP Tips to Improve Your Programming

Object-Oriented Programming (OOP) is the Rudimentary Requirement OOP is the basic requirement of PHP that every developer should know. Using OOP approaches, you can skip the replication of code and can complete the code in a much simpler way. Intrinsic Functions of PHP are Extremely Usable For example, if you want to count the numbers then you can use count(). Keep the Database Secure The first thing prior to starting any PHP project is that you should use mysl_real_escape_string() for all the database. Doing this will help you keep all the strings safe from any kind of unwelcome threats that may have some malicious code. This should be your first step to protect your database. The other vital thing is that never use $_REQUEST – instead, go with POST or GET strings for submitting the data into the database query. Always Use POST and Never GET Get method displays the address in the URL and gives simpler ways for the hacker to totally hack your entire project. Going with POST, you can face a secure journey throughout your coding and development procedure. Make a Copy Before Going for CODE Whatever it takes you to use PHP based frameworks and CMSs consider, use it over Core PHP, as it can give a better performance, a lightweight website and yes you can develop your website in PHP more faster.

10 Advanced PHP Tips

PHP programming has climbed rapidly since its humble beginnings in 1995. Since then, PHP has become the most popular programming language for Web applications. Many popular websites are powered by PHP, and an overwhelming majority of scripts and Web projects are built with the popular language. Because of PHP’s huge popularity, it has become almost impossible for Web developers not to have at least a working knowledge of PHP. This tutorial is aimed at people who are just past the beginning stages of learning PHP and are ready to roll up their sleeves and get their hands dirty with the language. Listed below are 10 excellent techniques that PHP developers should learn and use every time they program. These tips will speed up proficiency and make the code much more responsive, cleaner and more optimized for performance.

Use an SQL Injection Cheat Sheet

This particular tip is just a link to a useful resource with no discussion on how to use it. Studying various permutations of one specific attack can be useful, but your time is better spent learning how to safeguard against it. Additionally, there is much more to Web app security than SQL injection. XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgeries), for example, are at least as common and at least as dangerous. We can provide some much-needed context, but because we don’t want to focus too much on one attack, we’ll first take a step back. Every developer should be familiar with good security practices, and apps should be designed with these practices in mind. A fundamental rule is to never trust data you receive from somewhere else. Another rule is to escape data before you send it somewhere else. Combined, these rules can be simplified to make up a basic tenet of security: filter input, escape output (FIEO). The root cause of SQL injection is a failure to escape output. More specifically, it is when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. This is common in PHP apps that construct queries as follows: <?php $query = "SELECT * FROM users WHERE name = '{$_GET['name']}'"; ?> In this case, the value of $_GET[‘name’] is provided by another source, the user, but it is neither filtered nor escaped. Escaping preserves data in a new context. The emphasis on escaping output is a reminder that data used outside of your Web app needs to be escaped, else it might be misinterpreted. By contrast, filtering ensures that data is valid before it’s used. The emphasis on filtering input is a reminder that data originating outside of your Web app needs to be filtered, because it cannot be trusted. Assuming we’re using MySQL, the SQL injection vulnerability can be mitigated by escaping the name with mysql_real_escape_string(). If the name is also filtered, there is an additional layer of security. (Implementing multiple layers of security is called “defense in depth” and is a very good security practice.) The following example demonstrates filtering input and escaping output, with naming conventions used for code clarity: <?php // Initialize arrays for filtered and escaped data, respectively. $clean = array(); $sql = array(); // Filter the name. (For simplicity, we require alphabetic names.) if (ctype_alpha($_GET['name'])) { $clean['name'] = $_GET['name']; } else { // The name is invalid. Do something here. } // Escape the name. $sql['name'] = mysql_real_escape_string($clean['name']); // Construct the query. $query = "SELECT * FROM users WHERE name = '{$sql['name']}'"; ?> Although the use of naming conventions can help you keep up with what has and hasn’t been filtered, as well as what has and hasn’t been escaped, a much better approach is to use prepared statements. Luckily, with PDO, PHP developers have a universal API for data access that supports prepared statements, even if the underlying database does not. Remember, SQL injection vulnerabilities exist when the distinction between the format of an SQL query and the data used by the SQL query is not carefully maintained. With prepared statements, you can push this responsibility to the database by providing the query format and data in distinct steps: <?php // Provide the query format. $query = $db->prepare('SELECT * FROM users WHERE name = :name'); // Provide the query data and execute the query. $query->execute(array('name' => $clean['name'])); ?> The PDO manual page provides more information and examples. Prepared statements offer the strongest protection against SQL injection.

Know the Difference Between Comparison Operators

This is a good tip, but it is missing a practical example that demonstrates when a non-strict comparison can cause problems. If you use strpos() to determine whether a substring exists within a string (it returns FALSE if the substring is not found), the results can be misleading: <?php $authors = 'Chris & Sean'; if (strpos($authors, 'Chris')) { echo 'Chris is an author.'; } else { echo 'Chris is not an author.'; } ?> Because the substring Chris occurs at the very beginning of Chris & Sean, strpos() correctly returns 0, indicating the first position in the string. Because the conditional statement treats this as a Boolean, it evaluates to FALSE, and the condition fails. In other words, it looks like Chris is not an author, but he is! This can be corrected with a strict comparison: <?php if (strpos($authors, 'Chris') !== FALSE) { echo 'Chris is an author.'; } else { echo 'Chris is not an author.'; } ?>

Shortcut the else

This tip accidentally stumbles upon a useful practice, which is to always initialize variables before you use them. Consider a conditional statement that determines whether a user is an administrator based on the username: <?php if (auth($username) == 'admin') { $admin = TRUE; } else { $admin = FALSE; } ?> This seems safe enough, because it’s easy to comprehend at a glance. Imagine a slightly more elaborate example that sets variables for name and email as well, for convenience: <?php if (auth($username) == 'admin') { $name = 'Administrator'; $email = 'admin@example.org'; $admin = TRUE; } else { /* Get the name and email from the database. */ $query = $db->prepare('SELECT name, email FROM users WHERE username = :username'); $query->execute(array('username' => $clean['username'])); $result = $query->fetch(PDO::FETCH_ASSOC); $name = $result['name']; $email = $result['email']; $admin = FALSE; } ?> Because $admin is still always explicitly set to either TRUE or FALSE, all is well, but if a developer later adds an elseif, there’s an opportunity to forget: <?php if (auth($username) == 'admin') { $name = 'Administrator'; $email = 'admin@example.org'; $admin = TRUE; } elseif (auth($username) == 'mod') { $name = 'Moderator'; $email = 'mod@example.org'; $moderator = TRUE; } else { /* Get the name and email. */ $query = $db->prepare('SELECT name, email FROM users WHERE username = :username'); $query->execute(array('username' => $clean['username'])); $result = $query->fetch(PDO::FETCH_ASSOC); $name = $result['name']; $email = $result['email']; $admin = FALSE; $moderator = FALSE; } ?> If a user provides a username that triggers the elseif condition, $admin is not initialized. This can lead to unwanted behavior, or worse, a security vulnerability. Additionally, a similar situation now exists for $moderator, which is not initialized in the first condition. By first initializing $admin and $moderator, it’s easy to avoid this scenario altogether: <?php $admin = FALSE; $moderator = FALSE; if (auth($username) == 'admin') { $name = 'Administrator'; $email = 'admin@example.org'; $admin = TRUE; } elseif (auth($username) == 'mod') { $name = 'Moderator'; $email = 'mod@example.org'; $moderator = TRUE; } else { /* Get the name and email. */ $query = $db->prepare('SELECT name, email FROM users WHERE username = :username'); $query->execute(array('username' => $clean['username'])); $result = $query->fetch(PDO::FETCH_ASSOC); $name = $result['name']; $email = $result['email']; } ?> Regardless of what the rest of the code does, it’s now clear that $admin is FALSE unless it is explicitly set to something else, and the same is true for $moderator. This also hints at another good security practice, which is to fail safely. The worst that can happen as a result of not modifying $admin or $moderator in any of the conditions is that someone who is an administrator or moderator is not treated as one. If you want to shortcut something, and you’re feeling a little disappointed that our example includes an else, we have a bonus tip that might interest you. We’re not certain it can be considered a shortcut, but we hope it’s helpful nonetheless. Consider a function that determines whether a user is authorized to view a particular page: <?php function authorized($username, $page) { if (!isBlacklisted($username)) { if (isAdmin($username)) { return TRUE; } elseif (isAllowed($username, $page)) { return TRUE; } else { return FALSE; } } else { return FALSE; } } ?> This example is actually pretty simple, because there are only three rules to consider: administrators are always allowed access; those who are blacklisted are never allowed access; and isAllowed() determines whether anyone else has access. (A special case exists when an administrator is blacklisted, but that is an unlikely possibility, so we’re ignoring it here.) We use functions for the rules to keep the code simple and to focus on the logical structure. There are numerous ways this example can be improved. If you want to reduce the number of lines, a compound conditional can help: <?php function authorized($username, $page) { if (!isBlacklisted($username)) { if (isAdmin($username) || isAllowed($username, $page)) { return TRUE; } else { return FALSE; } } else { return FALSE; } } ?> In fact, you can reduce the entire function to a single compound conditional: <?php function authorized($username, $page) { if (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page)) { return TRUE; } else { return FALSE; } } ?> Finally, this can be reduced to a single return: <?php function authorized($username, $page) { return (!isBlacklisted($username) && (isAdmin($username) || isAllowed($username, $page)); } ?> If your goal is to reduce the number of lines, you’re done. However, note that we’re using isBlacklisted(), isAdmin(), and isAllowed() as placeholders. Depending on what’s involved in making these determinations, reducing everything to a compound conditional may not be as attractive. This brings us to our tip. A return immediately exits the function, so if you return as soon as possible, you can express these rules very simply: <?php function authorized($username, $page) { if (isBlacklisted($username)) { return FALSE; } if (isAdmin($username)) { return TRUE; } return isAllowed($username, $page); } ?> This uses more lines of code, but it’s very simple and unimpressive (we’re proudest of our code when it’s the least impressive). More importantly, this approach reduces the amount of context you must keep up with. For example, as soon as you’ve determined whether the user is blacklisted, you can safely forget about it. This is particularly helpful when your logic is more complicated.

Drop Those Brackets

Based on the content of this tip, we believe the author means “braces,” not brackets. “Curly brackets” may mean braces to some, but “brackets” universally means “square brackets.” This tip should be unconditionally ignored. Without braces, readability and maintainability are damaged. Consider a simple example: <?php if (date('d M') == '21 May') $birthdays = array('Al Franken', 'Chris Shiflett', 'Chris Wallace', 'Lawrence Tureaud'); ?> If you’re good enough, smart enough, secure enough, notorious enough, or pitied enough, you might want to party on the 21st of May: <?php if (date('d M') == '21 May') $birthdays = array('Al Franken', 'Chris Shiflett', 'Chris Wallace', 'Lawrence Tureaud'); party(TRUE); ?> Without braces, this simple addition causes you to party every day. Perhaps you have the stamina for it, so the mistake is a welcome one. Hopefully, the silly example doesn’t detract from the point, which is that the excessive partying is an unintended side effect. In order to promote the practice of dropping braces, the previous article uses short examples such as the following: <?php if ($gollum == 'halfling') $height --; else $height ++; ?> Because each condition is constrained to a single line, such mistakes might be less likely, but this leads to another problem: inconsistencies are jarring and require more time to read and comprehend. Consistency is such a valued quality that developers often abide by a coding standard even if they dislike the coding standard itself. We recommend always using braces: <?php if (date('d M') == '21 May') { $birthdays = array('Al Franken', 'Chris Shiflett', 'Chris Wallace', 'Lawrence Tureaud'); party(TRUE); } ?>

Favor str_replace() Over ereg_replace() and preg_replace()

We hate to sound disparaging, but this tip demonstrates the sort of misunderstanding that leads to the same misuse it’s trying to prevent. It’s an obvious truth that string functions are faster at string matching than regular expression functions, but the author’s attempt to draw a corollary from this fails miserably:
If you’re using regular expressions, then ereg_replace() and preg_replace() will be much faster than str_replace().
Because str_replace() does not support pattern matching, this statement makes no sense. The choice between string functions and regular expression functions comes down to which is fit for purpose, not which is faster. If you need to match a pattern, use a regular expression function. If you need to match a string, use a string function.

Use Ternary Operators

The benefit of the ternary operator is debatable (there’s only one, by the way). Here is a line of code from an audit we performed recently: <?php $host = strlen($host) > 0 ? $host : htmlentities($host); ?> Oops! The author actually means to escape $host if the string length is greater than zero, but instead accidentally does the opposite. Easy mistake to make? Maybe. Easy to miss during a code audit? Certainly. Concision doesn’t necessarily make the code any better. The ternary operator may be fine for one-liners, prototypes, and templates, but we strongly believe that an ordinary conditional statement is almost always better. PHP is descriptive and verbose. We think code should be, too.

Memcached

Disk access is slow. Network access is slow. Databases typically use both. Memory is fast. Using a local cache avoids the overhead of network and disk access. Combine these truths and you get memcached, a “distributed memory object caching system” originally developed for the Perl-based blogging platform LiveJournal. If your application isn’t distributed across multiple servers, you probably don’t need memcached. Simpler caching approaches — serializing data and storing it in a temporary file, for example — can eliminate a lot of redundant work on each request. In fact, this is the sort of low-hanging fruit we consider when helping our clients tune their apps. One of the easiest and most universal ways to cache data in memory is to use the shared memory helpers in APC, a caching system originally developed by our colleague George Schlossnagle. Consider the following example: <?php $feed = apc_fetch('news'); if ($feed === FALSE) { $feed = file_get_contents('http://example.org/news.xml'); // Store this data in shared memory for five minutes. apc_store('news', $feed, 300); } // Do something with $feed. ?> With this type of caching, you don’t have to wait on a remote server to send the feed data for every request. Some latency is incurred — up to five minutes in this example — but this can be adjusted to as close to real time as your app requires.

Use a Framework

All decisions have consequences. We appreciate frameworks — in fact, the main developers behind CakePHP and Solar work with us at OmniTI — but using one doesn’t magically make what you’re doing better. In December, our colleague Paul Jones wrote an article for PHP Advent called The Framework as Franchise, in which he compares frameworks to business franchises. He refers to a suggestion by Michael Gerber from his book “The E-Myth Revisited”:
Gerber notes that to run a successful business, the entrepreneur needs to act as if he is going to sell his business as a franchise prototype. It is the only way the business owner can make the business operate without him being personally involved in every decision.
This is good advice. Whether you’re using a framework or defining your own standards and conventions, it’s important to consider the value from the perspective of future developers. Although we would love to give you a universal truth, extending this idea to suggest that a framework is always appropriate isn’t something we’re willing to do. If you ask us whether you should use a framework, the best answer we could give is, “It depends.”

Use the Suppression Operator Correctly

Always try to avoid using the error suppression operator. In the previous article, the author states:
The @ operator is rather slow and can be costly if you need to write code with performance in mind.
Error suppression is slow. This is because PHP dynamically changes error_reporting to 0 before executing the suppressed statement, then immediately changes it back. This is expensive. Worse, using the error suppression operator makes it difficult to track down the root cause of a problem. The previous article uses the following example to support the practice of assigning a variable by reference when it is unknown if $albus is set: <?php $albert =& $albus; ?> Although this works — for now — relying on strange, undocumented behavior without a very good understanding of why it works is a good way to introduce bugs. Because $albert is assigned to $albus by reference, future modifications to $albus will also modify $albert. A much better solution is to use isset(), with braces: <?php if (!isset($albus)) { $albert = NULL; } ?> Assigning $albert to NULL is the same as assigning it to a nonexistent reference, but being explicit greatly improves the clarity of the code and avoids the referential relationship between the two variables. If you inherit code that uses the error suppression operator excessively, we’ve got a bonus tip for you. There is a new PECL extension called Scream that disables error suppression.

Use isset() Instead of strlen()

This is actually a neat trick, although the previous article completely fails to explain it. Here is the missing example: <?php if (isset($username[5])) { // The username is at least six characters long. } ?> When you treat strings as arrays, each character in the string is an element in the array. By determining whether a particular element exists, you can determine whether the string is at least that many characters long. (Note that the first character is element 0, so $username[5] is the sixth character in $username.) The reason this is slightly faster than strlen() is complicated. The simple explanation is that strlen() is a function, and isset() is a language construct. Generally speaking, calling a function is more expensive than using a language construct.

Tips

In order to write future-proof code, it is recommended that you don't place many variables, functions or classes in the global namespace. This will prevent naming conflicts with 3rd party code as well as possible future additions to the language. One common way to prevent naming conflicts of functions and classes is to add them to their own dedicated namespace. I. How Does PHP Work? As mentioned, PHP is a server-side, interpreted scripting language. Like JavaScript, Perl, ASP, Python, and Ruby, it’s mostly used to create back-end software. While these can be achieved using client-side scripting languages (HTML & CSS), PHP lets you design all the layers and nitty-gritty of your website, including the structure, database, design, content, and functionality.

Turn on error reporting feature

Before you start working on a new project, turning the error reporting feature is one of the first things you should do. Even pro developers swear by it. What will happen is that, throughout the production mode, you will see a helpful error message instead of just a blank screen when problems occur. This helps you cope with errors as you run through the code, making the process more efficient. Enable error reporting by modifying your php.ini with this line: diplay_errors = on Include this function immediately after opening the script. This ensures that the display_errors is on and the appropriate error_reporting level is used. This will save you the agony of going over thousands of lines of codes to detect an error. As you move on to writing more complex codes, you’ll need to implement advanced functions to catch syntax and parse errors.

Familiarize yourself with security practices

All websites and applications should be developed and designed using the best security practices. There are two rules to follow:
  1. Don’t trust data received from anywhere else other than your website or application
  2. Escape the data before you decide to send it to another website or application.
These two rules make up the building blocks of web security, aka Filter Input, Escape Output (FIEO), as they protect your website or application against SQL injections. A failure in escaping output could lead to a security breach. The solutions to these attacks are 1) remove the quote mark, 2) escape the quote mark, or 3) use a built-in feature to protect against the quote mark. But that’s just scratching the surface. If you want to develop a deeper understanding of web security, know what this code is for and where to place it in the application: mysql_real_escape_string ()

Familiarize yourself with ternary expression

The ternary operator logic provides a way to shorten if-else code blocks. Use ternary operators instead of IF constructions to simplify and nest your code without any hassles. Adopting this logic helps you enhance your code’s performance. Your codes not only look shorter, they will also be easier and quicker to maintain. Here’s a basic if-else statement: //equivalent if-else if($x==1) { if($y++2) { $variable = true; } else { $variable = false; } } else { $variable = false; } Here’s a simple use of the ternary operator logic: //nested ternary operator $ variable = ($x==1) ? (($==2) ? true : false) : false; By expanding your vocabulary beyond shorthand, you’ll be able to move up from your novice status quickly and get a better grasp of the subtleties of the language. This way, you’ll handle micro-optimizations like a pro.

Sketch your code

As with all programs built with PHP, the end goal is to create a usable interface for your code. Before you dive into development, you may want to sketch out your code and data structure first. You’d also want to have an idea of how your interface will look like before you start. When sketching, think about this:

“How would you like to interact with the module or web service?”

If you think about it, API is basically a visual and intuitive connection between the end user and the web service. You’d want to have a clear and consistent idea of what your code’s end goal will be. And one of the best ways to achieve this is to plot out key variables from the get-go. This will also help you to understand your code in detail before you jump into working on the real platform.
One more thing: keep the latest UX/UI principles in mind and you’ll arrive at a well-designed code.

Keep yourself updated

PHP is a widely used programming language. Every day, PHP receives new updates to match user requirements and deliver technology quickly and more efficiently. If you want to know how to become a good PHP developer, it’s vital to be familiar with all the latest updates to find out the best ways to code a website. Also, make sure your PHP software and code editing program are the latest versions.

Widen your vocabulary

Functions, classes, constants, and interfaces: these four things make up the bulk of PHP vocabulary and are the keys to expanding the functionality and look of websites, web pages, and applications. Mastering these will streamline your coding and make your program awesome. They not only help you accomplish a chore repeatedly, but they also add unique features to your program. PHP.net has an extensive manual to help you expand your vocabulary and understanding of the language. From basic syntax to supporter protocols, it basically covers everything. And as mentioned above, good vocabulary is the key to more advanced skills. Refer to the manual regularly to support your learning.

Create a master file

One of the key aspects of simplifying the coding process is to consolidate all the necessary settings into a single file. You can then associate the file with different PHP scripts and avoid disseminated data connections. Instead of making changes in multiple files, now you just need to make changes in a single file, especially in instances where a new function has to be added to multiple files.

Comment and Document

Many novice developers believe that commentaries should be the least of their worries. But the truth is, it’s a good habit to pick up as early as possible. And you may want to be as attentive and voracious when commenting as when you’re coding. Comments within the code will serve as your reference should you forget the essence of a piece of code. You wouldn’t want to clutter your code with comments, though. Just make a few, brief notes to enhance the code’s readability. Another alternative is to document the code for the most complicated section so that when you revisit that section, you can quickly recall the most complex details. And don’t forget to change comments when you change the code. phpDocumentor and Doxygen are useful tools to read these comments and produce usable documentation pages. Stfalcon.com offers a step-by-step guide on how to document and comment within the program code.

Use a PHP Framework

A PHP Framework is designed to make the web developer’s life easier. Back in the day, or if you’re still a coding purist, creating a web application from scratch would take weeks to months. Much of it will go to producing repetitive code. There’s no harm in that, except that it takes loads of time and effort. As a web developer, you want to create more (high-quality) products efficiently to earn big bucks and win your clients’ good graces. Writing everything from scratch is obviously not a good strategy. PHP frameworks are the solution to that. A framework is simply a platform that provides the basic structure for your program. On top of that, it ensures the connection between your database and whatever application you build from scratch. The best PHP frameworks also provide database support, an easy-to-follow user guide, and a strong, helpful community. So when you’re choosing one, make sure it has all these characteristics.

Use object-oriented programming (OOP)

Object-oriented programming (OOP) is something that every PHP developer needs to know and be familiar with. OOP helps you to skip code that keeps repeating, allowing the code to be executed efficiently. It helps in building complex, reusable web applications that would otherwise take a lot more time and effort in a procedural approach. Here are OO concepts in PHP you should explore: Here’s a more thorough discussion on this topic at Valuebound.com. Overall, OOP reduces the length of procedures associated with coding and execution. But as your skills advance, you’ll learn to code and test both object-oriented and procedural programs and assemble them seamlessly into a complete program.

Takeaways

Many advanced techniques can be accomplished with PHP, especially now that it’s being constantly upgraded with more APIs and capabilities. Many elite developers now swear by PHP because it allows the code to be highly personalized, allowing them to transform a program or website at their will or according to the requirements of the client. The best part about PHP is that it has a global community of supportive and friendly developers who are willing to answer all your questions. You can join a local user group, open source project community, or IRC channel to fine-tune your skills and discover other resources. More importantly, polishing your PHP coding skills gives you a better chance at landing a high-paying job and developing the next groundbreaking web application. Take these beginner PHP tips and tricks, sign up for advanced PHP classes online, put what you learn into practice and you’ll be a pro developer in no time.

Do not use relative paths , instead define a ROOT path

Its quite common to see such lines : require_once('../../lib/some_class.php'); This approach has many drawbacks : It first searches for directories specified in the include paths of php , then looks from the current directory. So many directories are checked. When a script is included by another script in a different directory , its base directory changes to that of the including script. Another issue , is that when a script is being run from cron , it may not have its parent directory as the working directory. So its a good idea to have absolute paths : define('ROOT' , '/var/www/project/'); require_once(ROOT. '../../lib/some_class.php'); //rest of the code Now this is an absolute path and will always stay constant. But we can improve this further. The directory /var/www/project can change , so do we change it everytime ? No instead we make it portable using magic constants like __FILE__. Take a closer look : //suppose your script is /var/www/project/index.php //Then __FILE__ will always have that full path. define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME)); require_once(ROOT. '../../lib/some_class.php'); //rest of the code So now even if you shift your project to a different directory , like moving it to an online server , the same code will run without any changes.

Dont use require , include , require_once or include_once

Your script could be including various files on top , like class libraries , files for utility and helper functions etc like this : require_once('lib/Database.php'); require_once('lib/Mail.php'); require_once('helpers/utitlity_functions.php'); This is rather primitive. The code needs to be more flexible. Write up helper functions to include things more easily. Lets take an example : function load_class($class_name) { //path to the class file $path = ROOT. '/lib/'. $class_name. '.php'); require_once( $path ); } load_class('Database'); load_class('Mail'); See any difference ? You must. It does not need any more explanation. You can improve this further if you wish to like this : function load_class($class_name) { //path to the class file $path = ROOT. '/lib/'. $class_name. '.php'); if(file_exists($path)) { require_once( $path ); } } There are a lot of things that can be done with this : Search multiple directories for the same class file. Change the directory containing class files easily , without breaking the code anywhere. Use similar functions for loading files that contain helper functions , html content etc.

Maintain debugging environment in your application

During development we echo database queries , dump variables which are creating problems , and then once the problem is solved , we comment them or erase them. But its a good idea to let everything stay and help in the long run On your development machine you can do this : define('ENVIRONMENT' , 'development'); if(! $db->query( $query ) { if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } } And on the server you can do this : define('ENVIRONMENT' , 'production'); if(! $db->query( $query ) { if(ENVIRONMENT == 'development') { echo "$query failed"; } else { echo "Database error. Please contact administrator"; } }

Propagate status messages via session

Status messages are those messages that are generated after doing a task. <?php if($wrong_username || $wrong_password) { $msg = 'Invalid username or password'; } ?> <html> <body> <?php echo $msg; ?> <form> ... </form> </body> </html> Code like that is common. Using variables to show status messages has limitations. They cannot be send via redirects (unless you propagate them as GET variables to the next script , which is very silly). In large scripts there might be multiple messages etc. Best way is to use session to propagate them (even if on same page). For this there has to be a session_start on every page. function set_flash($msg) { $_SESSION['message'] = $msg; } function get_flash() { $msg = $_SESSION['message']; unset($_SESSION['message']); return $msg; } and in your script : <?php if($wrong_username || $wrong_password) { set_flash('Invalid username or password'); } ?> <html> <body> Status is : <?php echo get_flash(); ?> <form> ... </form> </body> </html>

Make your functions flexible

function add_to_cart($item_id , $qty) { $_SESSION['cart'][$item_id] = $qty; } add_to_cart( 'IPHONE3' , 2 ); When adding a single item you use the above function. When adding multiple items , will you create another function ? NO. Just make the function flexible enough to take different kinds of parameters. Have a closer look : function add_to_cart($item_id , $qty) { if(!is_array($item_id)) { $_SESSION['cart'][$item_id] = $qty; } else { foreach($item_id as $i_id => $qty) { $_SESSION['cart'][$i_id] = $qty; } } } add_to_cart( 'IPHONE3' , 2 ); add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) ); So now the same function can accept different kinds of output. The above can be applied in lots of places to make your code more agile.

Omit the closing php tag if it is the last thing in a script

I wonder why this tip is omitted from so many blog posts on php tips. <?php echo "Hello"; //Now dont close this tag This will save you lots of problem. Lets take an example : A class file super_class.php <?php class super_class { function super_function() { //super code } } ?> //super extra character after the closing tag Now index.php require_once('super_class.php'); //echo an image or pdf , or set the cookies or session data And you will get Headers already send error. Why ? because the "super extra character" has been echoed , and all headers went along with that. Now you start debugging. You may have to waste many hours to find the super extra space. Hence make it a habit to omit the closing tag : <?php class super_class { function super_function() { //super code } } //No closing tag Thats better.

Collect all output at one place, and output at one shot

This is called output buffering. Lets say you have been echoing content from different functions like this : function print_header() {echo "<div id='header'>Site Log and Login links</div>";} function print_footer() { echo "<div id='footer'>Site was made by me</div>"; } print_header(); for($i = 0 ; $i < 100; $i++) { echo "I is : $i <br />'; } print_footer(); Instead of doing like that , first collect all output in one place. You can either store it inside variables in the functions or use ob_start and ob_end_clean. So now it should look like function print_header() { $o = "<div id='header'>Site Log and Login links</div>"; return $o; } function print_footer() { $o = "<div id='footer'>Site was made by me</div>"; return $o; } echo print_header(); for($i = 0 ; $i < 100; $i++) { echo "I is : $i <br />'; } echo print_footer(); So why should you do output buffering :

Send correct mime types via header when outputting non-html content

Lets echo some xml. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'; $xml = "<response> <code>0</code> </response>"; //Send xml data echo $xml; Works fine. But it needs some improvement. $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>'; $xml = "<response> <code>0</code> </response>"; //Send xml data header("content-type: text/xml"); echo $xml; Note that header line. That line tells the browser that the content is xml content. So the browser can handle it correctly. Many javascript libraries also rely on header information. Similarly for javascript , css , jpg image , png image : Javascript header("content-type: application/x-javascript"); echo "var a = 10"; CSS header("content-type: text/css"); echo "#div id { background:#000; }";

Set the correct character encoding for a mysql connection

Ever faced a problem that unicode/utf-8 characters are stored in mysql table correctly , phpmyadmin also shows them correct , but when you fetch them and echo on your page they do not show up correctly. The secret is mysql connection collation. $host = 'localhost'; $username = 'root'; $password = 'super_secret'; //Attempt to connect to database $c = mysqli_connect($host , $username, $password); //Check connection validity if (!$c) { die ("Could not connect to the database host: <br />". mysqli_connect_error()); } //Set the character set of the connection if(!mysqli_set_charset ( $c , 'UTF8' )) { die('mysqli_set_charset() failed'); } Once you connect to the database , its a good idea to set the connections characterset. This is a must when you are working with multiple languages in your application. Otherwise what will happen ? You will see lots of boxes and ???????? in non english text.

Use htmlentities with the correct characterset option

Prior to php 5.4 the default character encoding used is ISO-8859-1 which cannot display characters like À â etc. $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8'); Php 5.4 onwards the default encoding will be UTF-8 which will solve most problems , but still better be aware about it if your application is multilingual.

Do not gzip output in your application , make apache do that

Thinking of using ob_gzhandler ? No dont do that. It doesnt make sense. Php is supposed to write your application. Dont worry about how to optimise data transfer between server and browser inside Php. Use apache mod_gzip/mod_deflate to compress content via the.htaccess file.

Use json_encode when echoing javascript code from php

There are times when some javascript code is generated dynamically from php. $images = array( 'myself.png' , 'friends.png' , 'colleagues.png'); $js_code = ''; foreach($images as $image) { $js_code.= "'$image' ,";} $js_code = 'var images = ['. $js_code. ']; '; echo $js_code; //Output is var images = ['myself.png' ,'friends.png' ,'colleagues.png' ,]; Be smart. use json_encode : $images = array( 'myself.png' , 'friends.png' , 'colleagues.png' ); $js_code = 'var images = '. json_encode($images); echo $js_code; //Output is : var images = ["myself.png","friends.png","colleagues.png"] Isn't that neat ?

Check if directory is writable before writing any files

Before writing or saving any file , make sure you check that the directory is writable or not , and flash an error message if it is not. This will save you a lot of "debugging" time. When you are working on a linux , permissions have to be dealt with and there would be many many permission issues when directories would not be writable , files would not be readable and so on. Make sure that your application is as intelligent as possible and reports the most important information in the shortest time. $contents = "All the content"; $file_path = "/var/www/project/content.txt"; file_put_contents($file_path , $contents); That is totally correct. But has some indirect problems. The file_put_contents may fail for a number of reasons : So its better to make everything clear before writing out to a file. $contents = "All the content"; $dir = '/var/www/project'; $file_path = $dir. "/content.txt"; if(is_writable($dir)) { file_put_contents($file_path , $contents); } else { die("Directory $dir is not writable, or does not exist. Please check"); } By doing this you get the accurate information that where is a file write failing and why

Change permission of files that your application creates

When working in linux environment , permission handling can waste a lot of your time. Hence whenever your php application creates some files do a chmod over them to ensure they are "accessible" outside. Otherwise for example the files may be created by "php" user and you are working as a different user and the system wont let you access or open the file , and then you have to struggle to get root privileges , change the permissions of the file and so on. // Read and write for owner, read for everybody else chmod("/somedir/somefile", 0644); // Everything for owner, read and execute for others chmod("/somedir/somefile", 0755);

Don't check submit button value to check form submission

if($_POST['submit'] == 'Save') { //Save the things } The above is mostly correct , except when your application is multi-lingual. Then the 'Save' can be many different things. How would you compare then. So do not rely on the value of submit button. Instead use this : if( $_SERVER['REQUEST_METHOD'] == 'POST' and isset($_POST['submit']) ) { //Save the things } Now you are free from the value the submit button

Use static variables in function where they always have same value

//Delay for some time function delay() { $sync_delay = get_option('sync_delay'); echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />"; } Instead use static variables as : //Delay for some time function delay() { static $sync_delay = null; if($sync_delay == null) { $sync_delay = get_option('sync_delay'); } echo "<br />Delaying for $sync_delay seconds..."; sleep($sync_delay); echo "Done <br />"; }

Don't use the $_SESSION variable directly

Some simple examples are : $_SESSION['username'] = $username; $username = $_SESSION['username']; But this has a problem. If you are running multiple applications on the same domain , the session variables my conflict. 2 different applications may set the same key name in the session variable. Take for example , a frontend portal , and the backend management application , on the same domain. Hence use application specific keys with wrapper functions : define('APP_ID' , 'abc_corp_ecommerce'); //Function to get a session variable function session_get($key) { $k = APP_ID. '.'. $key; if(isset($_SESSION[$k])) { return $_SESSION[$k]; } return false; } //Function set the session variable function session_set($key , $value) { $k = APP_ID. '.'. $key; $_SESSION[$k] = $value; return true; }

Wrap utility helper functions into a class

So you have a lot of utility functions in a file like : function utility_a() { //This function does a utility thing like string processing } function utility_b() { //This function does nother utility thing like database processing } function utility_c() { //This function is... } And you use the function throughout your application freely. You may want to wrap them into a class as static functions : class Utility { public static function utility_a() { } public static function utility_b() { } public static function utility_c() { } } //and call them as $a = Utility::utility_a(); $b = Utility::utility_b(); One clear benefit you get here is if php has inbuilt functions with similar names , then names will not conflict. Another perspective , though little advanced is that you can maintain multiple versions of the same class in the same application without any conflict. Its basically encapsulation , nothing else.

Bunch of silly tips

Process arrays quickly with array_map

Lets say you want to trim all elements of an array. Newbies do it like this : foreach($arr as $c => $v) { $arr[$c] = trim($v); } But it can more cleaner with array_map : $arr = array_map('trim' , $arr); This will apply trim on all elements of the array $arr. Another similar function is array_walk. Check out the documentation on these to know more.

Validate data with php filters

Have you been using to regex to validate values like email , ip address etc. Yes everybody had been doing that. Now lets try something different, called filters. The php filter extension provides simple way to validate or check values as being a valid 'something'.

Force type checking

$amount = intval( $_GET['amount'] ); $rate = (int) $_GET['rate']; Its a good habit.

Write Php errors to file using set_error_handler()

set_error_handler() can be used to set a custom error handler. A good idea would be write some important errors in a file for logging purpose

Handle large arrays carefully

Large arrays or strings , if a variable is holding something very large in size then handle with care. Common mistake is to create a copy and then run out of memory and get a Fatal Error of Memory size exceeded : $db_records_in_array_format; //This is a big array holding 1000 rows from a table each having 20 columns , every row is atleast 100 bytes , so total 1000 * 20 * 100 = 2MB $cc = $db_records_in_array_format; //2MB more some_function($cc); //Another 2MB ? The above thing is common when importing a csv file or exporting table to a csv file Doing things like above can crashs scripts quite often due to memory limits. For small sized variables its not a problem , but must be avoided when handling large arrays. Consider passing them by reference , or storing them in a class variable : $a = get_large_array(); pass_to_function(&$a); by doing this the same variable (and not its copy) will be available to the function. Check documentation class A { function first() { $this->a = get_large_array(); $this->pass_to_function(); } function pass_to_function() { //process $this->a } } unset them as soon as possible , so that memory is freed and rest of the script can relax. Here is a simple demonstration of how assign by reference can save memory in some cases <?php ini_set('display_errors' , true); error_reporting(E_ALL); $a = array(); for($i = 0; $i < 100000 ; $i++) { $a[$i] = 'A'.$i; } echo 'Memory usage in MB : '. memory_get_usage() / 1000000. '<br />'; $b = $a; $b[0] = 'B'; echo 'Memory usage in MB after 1st copy : '. memory_get_usage() / 1000000. '<br />'; $c = $a; $c[0] = 'B'; echo 'Memory usage in MB after 2st copy : '. memory_get_usage() / 1000000. '<br />'; $d =& $a; $d[0] = 'B'; echo 'Memory usage in MB after 3st copy (reference) : '. memory_get_usage() / 1000000. '<br />'; The output on a typical php 5.4 machine is : Memory usage in MB : 18.08208 Memory usage in MB after 1st copy : 27.930944 Memory usage in MB after 2st copy : 37.779808 Memory usage in MB after 3st copy (reference) : 37.779864 So it can be seen that in the 3rd copy which was by reference memory was saved. Otherwise in all plain copies memory is used up more and more.

Use a single database connection, throughout the script

Make sure that you use a single connection to your database throughout your script. Open a connection right in the beginning and use it till the end , and close it at the end. Do not open connections inside functions like this : function add_to_cart() { $db = new Database(); $db->query("INSERT INTO cart....."); } function empty_cart() { $db = new Database(); $db->query("DELETE FROM cart....."); } Having multiple connections is a bad idea and moreover they slow down the execution since every connection takes time to create and uses more memory. Use the singleton pattern for special cases like database connection.

Avoid direct SQL query , abstract it

$query = "INSERT INTO users(name , email , address , phone) VALUES('$name' , '$email' , '$address' , '$phone')"; $db->query($query); //call to mysqli_query() The above is the simplest way way of writing sql queries and interacting with databases for operations like INSERT, UPDATE, DELETE etc. But it has few drawbacks like: Solution: ActiveRecord It involves writing simple functions that abstract the generation of sql queries, hence avoid writing of direct sql queries. A very simple example of an activerecord insert function can be like this : function insert_record($table_name , $data) { foreach($data as $key => $value) { //mysqli_real_escape_string $data[$key] = $db->mres($value); } $fields = implode(',' , array_keys($data)); $values = "'". implode("','" , array_values($data)). "'"; //Final query $query = "INSERT INTO {$table}($fields) VALUES($values)"; return $db->query($query); } //data to be inserted in database $data = array('name' => $name , 'email' => $email , 'address' => $address , 'phone' => $phone); //perform the INSERT query insert_record('users' , $data); The above example shows how to insert data in a database, without actually having to write INSERT statements. The function insert_record takes care of escaping data as well. A big advantage here is that since the data is being prepared as a php array, any syntax mistake is caught instantly (by the php interpreter ofcourse). This function can be part of a database class, and callable like this $db->insert_record(). Similar functions can be written for update, select, delete as well. Should be a good practise.

Cache database generated content to static files

Pages that are generated by fetching content from the database like cms etc, can be cached. It means that once generated, a copy of it can be writted to file. Next time the same page is requested, then fetch it from the cache directory, dont query the database again. Benefits :

Store sessions in database

File based sessions have many limitation. Applications using file based sessions cannot scale to multiple servers, since files are stored on a single server. But database can be access from multiple servers hence the the problem is solved there. Also on shared hosting, the session files reside in the tmp directory, which is readable by other accounts. This can be a security issue. Storing session in database makes many other things easier like:

Avoid using globals

Use base url in head tag

Quick example : [html] <head> <base href="http://www.domain.com/store/"> </head> <body> <img src="happy.jpg" /> </body> </html> [/html] The base tag is like a 'ROOT' url for all relative urls in the html body. Its useful when static content files are organised into directories and subdirectories. Lets take an example www.domain.com/store/home.php www.domain.com/store/products/ipad.php In home.php the following can be written : [html] <a href="home.php">Home</a> <a href="products/ipad.php">Ipad</a> [/html] But in ipad.php the links have to be like this : [html] <a href="../home.php">Home</a> <a href="ipad.php">Ipad</a> [/html] This is because of different directories. For this multiple versions of the navigation html code has to be maintained. So the quick solution is base tag. [html] <head> <base href="http://www.domain.com/store/"> </head> <body> <a href="home.php">Home</a> <a href="products/ipad.php">Ipad</a> </body> </html> [/html] Now this particular code will work the same way in the home directory as well as the product directory. The base href value is used to form the full url for home.php and products/ipad.php

Manage error reporting

error_reporting is the function to use to set the necessary level of error reporting required. On a development machine notices and strict messages may be disabled by doing. ini_set('display_errors', 1); error_reporting(~E_NOTICE & ~E_STRICT); On production , the display should be disabled. ini_set('display_errors', 0); error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); It is important to note that error_reporting should never be set to 0 on production machines. Atleast E_FATALs have to be known. Just switch off the display using the display_errors directive. If error_reporting is set to 0, errors wont be raised at all keeping all problems in the dark. After the display is switched off, the errors should be logged to a file for later analysis. This can be done inside the script using init_set. ini_set('log_errors' , '1'); ini_set('error_log' , '/path/to/errors.txt'); ini_set('display_errors' , 0); error_reporting(~E_WARNING & ~E_NOTICE & ~E_STRICT); Note : 1. The path '/path/to/errors.txt' should be writable by the web server for errors to be logged there. 2. A separate error file is specified , otherwise all logs would go inside the apache/web server error log and get mixed up with other apache errors. 3. Also since it is being setup in the current application , the error log will contain the errors of only the current application (there may be other applications running on the webserver). 4. The path can be somewhere inside the directory of the current application as well , so that the system directories like /var/log dont have to searched. 5. Dont set error_reporting to 0. It will not log anything then. Alternatively set_error_handler should be used to set a custom user written function as the error handler. That particular function, for example can log all errors to a file. Set 'display_errors=On' in php.ini on development machine On development machine its important to enable display_errors right in the php.ini (and not rely on ini_set) This is because any compile time fatal errors will now allow ini_set to execute , hence no error display and a blank WHITE page. Similarly when they are On in php.ini , switching it off in a script that has fatal errors will not work. Set 'display_errors=Off' in php.ini on production machine Do not rely on init_set('display_errors' , 0); simply because it will not get executed if any compile time fatal errors come in the script , and errors will be displayed right away.

Be aware of platform architecture

The length of integers is different on 32 and 64 bit architectures. So functions like strtotime give different results. On a 64 bit machine you can see such output. $ php -a Interactive shell php > echo strtotime("0000-00-00 00:00:00"); -62170005200 php > echo strtotime('1000-01-30'); -30607739600 php > echo strtotime('2100-01-30'); 4104930600 But on a 32 bit machine all of them would give bool(false). Check here for more. What would happen if an integer is left shifted more than 32 bits ? the result would be different on different machines.

Dont rely on set_time_limit too much

If you are limiting the maximum run-time of a script , by doing this : set_time_limit(30); //Rest of the code It may not always work. Any execution that happens outside the script via system calls/os functions like socket operations, database operations etc. will not be under control of set_time_limit. So if a database operation takes lot of time or "hangs" then the script will not stop. Dont be surprised then. Make better strategies to handle the run-time.

Make a portable function for executing shell commands

system , exec , passthru , shell_exec are the 4 functions that are available to execute system commands. Each has a slightly different behaviour. But the problem is that when you are working on shared hosting environments some of the functions are selectively disabled. Most newbie programmers tend to first find out which function is enabled and then use it. A better solution : function terminal($command) { //system if(function_exists('system')) { ob_start(); system($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //passthru else if(function_exists('passthru')) { ob_start(); passthru($command , $return_var); $output = ob_get_contents(); ob_end_clean(); } //exec else if(function_exists('exec')) { exec($command , $output , $return_var); $output = implode("n" , $output); } //shell_exec else if(function_exists('shell_exec')) { $output = shell_exec($command) ; } else { $output = 'Command execution not possible on this system'; $return_var = 1; } return array('output' => $output , 'status' => $return_var); } terminal('ls'); The above function will execute the shell command using whichever function is available , keeping your code consistent.

Localize your application

Localise your php application. Format dates and numbers with commas and decimals. Show the time according to timezone of the user.

Use a profiler like xdebug if you need to

Profilers are used to generate reports that show the time is taken by different parts of the code to execute. When writing large application where lots of libraries and other resources are working to do a cetain task, speed might be an important aspect to optimise. Use profilers to check how your code is performing in terms of speed. Check out xdebug and webgrind.

Use plenty of external libraries

An application often needs more than what can be coded with basic php. Like generating pdf files, processing images, sending emails, generating graphs and documents etc. And there are lots of libraries out there for doing these things quickly and easily. Few popular libraries are :
  • mPDF - Generate pdf documents, by converting html to pdf beautifully.
  • PHPExcel - Read and write Excel files
  • PhpMailer - Send html emails with attachments easily
  • pChart - Generate graphs in php
  • phpbench for micro-optimisation stats

    Optimisation at the level of microtime: phpbench... it has some benchmarks for various syntax variations that can create significant difference.

    Use an MVC framework

    Its time to start using an MVC (Model view controller) framework like codeigniter. MVC does not make your code object oriented rightaway. The first thing they do is separate the php code from html code.

    Read the comments on the php documentation website

    The php documentation website has entries for each function, class and their methods. All those individual pages have got lots of user comments below them that contain a whole lot of valuable information from the community. They contain user feedback, expert advice and useful code snippets. So check them out.

    Go to the IRC channel to ask

    The irc channel #php is the best place online to ask about php related things. Although there are lots of blogs, forums out there and even more coming up everyday, still when a specific problem arises the solution might not be available there. Then irc is the place to ask. And its totally free!!

    Read open source code

    Reading other open source applications is always a good idea to improve own skills if you have not already. Things to learn are techniques, coding style, comment style, organisation and naming of files etc. The first open source thing that I read was the codeigniter framework. Its easy to developers to use, as well as easy to look inside. Here are a few more Codeigniter WordPress Joomla CMS

    Develop on Linux

    If you are already developing on windows, then you might give Linux a try. My favorite is ubuntu. Although this is just an opinion but still I strongly feel that for development linux is a much better environment. Php applications are mostly deployed on linux (LAMP) environments. Therefore, developing in a similar environment helps to produce a robust application faster. Most of the development tools can be very easily installed from synaptic package manager in Ubuntu. Plus they need very little configuration to setup and run. And the best thing is, that they all are free.

    Ternary Operators

    In previous articles we've touched on some major sections such as MySQLi, Classes and cURL. There are a lot of other tips and tricks that you should look at, and a few of them are covered below, a couple of which are transferrable between languages. A 三个一组 ternary operator is a different way to layout a simple if statement. (Condition) ? (Statement1) : (Statement2); Let's take a look at one and then break it down. We'll just use a simple check to see if a GET parameter is set and not empty, if it is we will default to the word John, otherwise use the value that was set as the GET parameter. $name = (!empty($_GET['name'])? $_GET['name'] : 'John'); This might look complex to begin with but there are three sections to a ternary operator:
    1. The conditional !empty($_GET['name'])
    2. The true result $_GET['name']
    3. The false result 'John'
    The ternary operator will return either the true or false conditional, and therefore it will be assigned to $name. If we write this as a normal if statement we'd have one of the following: if(!empty($_GET['name'])){ $name = $_GET['name']; }else{ $name = 'John'; } // Or $name = 'John'; if(!empty($_GET['name'])){ $name = $_GET['name']; } The two above and the ternary operator will all end up with $name having something assigned to it.

    Nesting

    While not advisable, it is possible to nest ternary operators within each other much like you would with standard if statements, or to form a long string of if...else if...else if...else statements. Ternary operators can be very helpful and clean up code, but don't over complicate them otherwise your code might become inundated with large amounts of complex rediculousness that will get you hunted down by a violent psychopath.

    Class Autoloading

    To make use of a class file, you have to ensure that the class you're using is available within the page that you're using it. In most cases this will be as easy as you just including the PHP file that contains the class. But what if we have a very large number of classes that we could potentially use within one or many sections of our code? Well, we could include all of them within a common header file, or only include the ones that we know that we're going to use on that page. However, we then need to remember to include new classes whenever we want to use a different one etc. So instead of including classes that might not get used, or we might remove later, we can employ class autoloading. When we autoload classes we can write what will happen - this might be to just throw an error to let us know that we've not included the class file, or, as in most cases, we make the function include the file that we need.

    The Code

    Here we'll be using the PHP function spl_autoload_register(), we'll only be interested in the first parameter, but there are two others that you can define if you wanted the function to behave differently. I'll jump straight into how to use it: function loadMyClass($class){ echo 'We are loading class: '.$class; include_once('classes/'.$class.'.inc.php'); echo 'Class loaded.'; } spl_autoload_register('loadMyClass'); This will pass the name of the class that we're trying to load as the first parameter of the function that we specified. As of PHP 5.3.0 we are able to use anonymous functions, basically a function thas has no name: spl_autoload_register(function ($class){ echo 'We are loading class: '.$class; include_once('classes/'.$class.'.inc.php'); echo 'Class loaded.'; }); Which will work exactly the same as the method of implementation above. So now in future, we don't need to include the class files that we'll be using as this function will run if the class is undefined, include the class and then the instantiation will be called.

    Dynamic Variables

    Sometimes we want to be able to dynmically define a variable, or refer to a variable based on a user's input. Let's start with this code: $myname = 'Michael'; $yourname = 'Ben'; if($_GET['whatname'] == 'your'){ echo $yourname; }else if($_GET['whatname'] == 'my'){ echo $myname; }else{ echo 'No Name'; } To use the value of a variable to then form another variable we use double dollar signs $$ so for example we could do $who = 'myname'; then echo $$who. This will echo out the value of $myname. Break it down like this (exemplary code, not actual working code): $who = 'myname'; $$who = $'myname'; $$who = $myname; echo $$who; // would return 'Michael' In reference to the code above we could look to use something along the lines of the following for very dynamically defined variables: $who = $_GET['whatname'].'name'; if(isset($$who)){ echo $$who; }else{ echo 'No Name'; } As with ternary operators, you should use these loosely, as in most situations there's not much need for them, but you will most probably find some crazy-ninja somewhere who uses this notation.

    Referencing

    Passing variables by reference, is a way to pass variables into functions so that the function can alter the original variable without having to return anything or define it as global etc. A function parameter that is going to be passed in as a reference is preceeded by an ampersand (&). Let's go with an example: function lowercase(&$string){ $string = strtolower($string); } $name = 'STEPHEN'; lowercase($name); echo $name; // returns stephen What you can see is that where we've called the lowercase() method and passed in $name, the function has altered the actual string that we passed in, as within the function $string becomes $name. There are advantages of using references, for example you don't have to return anything from the function, nor do you have to look to define them as globally accessible.

    References - indirect pointer

    References are super awesome when you use them with arrays. Let's say we have a function that sets the first item in any array to potato - because you know, it'll be the most helpful function ever: function potatoArray(&$array){ $array[0] = 'potato'; } $nonpotato = array( 'john', 'andrew', 'cheese' ); potatoArray($nonpotato); print_r($nonpotato); // This will now have changed 'john' to 'potato' References are very powerful things, and could be used extensively. You'll find them used with the array_walk() method other some other array methods that PHP have.

    Relative Time Calculation

    Everywhere you look people love their relative times, they're on Facebook, they're in most Twitter apps and they're here on Codular. Codular isn't too fussed about the specific time of when an action was made and so we have come up with a special class with handle the relative date for us. We define a list of the days that exist, and then do some logic to find out what to display. We firstly check if it's today or yesterday, obviously returning the respective term. We then look to see if the date falls in the last 7 days (less than 8 days), this is so that we can display last Monday, last Sunday etc. But obviously the 'Last' prefix can only apply to one week. Our method takes a second parameter with is a fallback format, this is the format that we use when the date falls out of the 'Last' date range. The first parameter is a simple UNIX timestamp. <?php class TimeClass { private static $days = array( 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ); /** * relativeTime() * @param int $time * @param string $format */ public static function relative($time, $format = 'jS F Y'){ if(date('d/m/Y', $time) === date('d/m/Y')){ return 'Today'; }else if(date('d/m/Y', $time) === date('d/m/Y', time() - 3600 * 24)){ return 'Yesterday'; }else if((time() - $time) < 3600 * 24 * 8){ return 'Last '.self::$days[date('w', $time)]; }else{ return date($format, $time); } } } Usage would be as simple as doing: echo TimeClass:relative(time()); That will always output Today as we are using the current timestamp. Relative date calculations can be pretty smple, another that is commonly used is to round to the nearest multiple of a time frame - ie days, weeks, months years etc. Below is a quick function to finish off with that will do exactly that up to 10 years in time then fall back to a date: <?php function relativeTime($timestamp, $format = 'Y-m-d H:i'){ $dif = time() - $timestamp; $dateArray = array( "second" => 60, // 60 seconds in 1 minute "minute" => 60, // 60 minutes in 1 hour "hour" => 24, // 24 hours in 1 day "day" => 7, // 7 days in 1 week "week" => 4, // 4 weeks in 1 month "month" => 12, // 12 months in 1 year "year" => 10 // Up to 10 years ); foreach($dateArray as $key => $item){ if($dif < $item) return $dif.' '.$key.($dif == 1? '' : 's').' ago'; $dif = round($dif/$item); } return date($format, $timestamp); }

    useful libraries

    With the help of Composer and Github, lots of useful libraries released every day, and easy to discover and use.

    - Dispatch - Micro Framework

    Dispatch is a minimal PHP framework. It doesn't give you the full MVC setup, but 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(); You can match specific types of HTTP requests and paths, render views and more. If you combine Dispatch with some of the other frameworks here, you can have a really powerful and lightweight setup!

    - Klein – Lightning fast router for PHP

    Klein is another light weight routing library for PHP 5.3+. It has a bit more verbose syntax than Dispatch, but is quite fast. 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 } }); This is great for small projects, but you have to be disciplined when using a library like this for larger apps, as your code can become unmaintainable very fast. For this purpose, you would be better off with a full blown MVC framework like Laravel or CodeIgniter.

    - Ham - Routing Library with Caching

    Ham is also a lightweight routing framework but it utilizes caching for even more speed gains. It achieves this by caching anything I/O related in XCache/APC. Here is an example: require '../ham/ham.php'; $app = new Ham('example'); $app->config_from_file('settings.php'); $app->route('/pork', function($app) { return "Delicious pork."; }); $hello = function($app, $name='world') { return $app->render('hello.html', array( 'name' => $name )); }; $app->route('/hello/<string>', $hello); $app->route('/', $hello); $app->run(); The library requires that you have either XCache or APC installed, which would mean that it won't work on most hosting providers. But if you do have one of these installed or if you control your webserver, you should try this very fast framework.

    - Assetic - Asset Management

    Assetic is am 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(); Combining assets in this manner is a good idea, as it can speed up your site. Not only is the total download size reduced, but also a lot of unnecessary HTTP requests are eliminated (two of the things that affect page load time the most).

    - ImageWorkshop - Image Manipulation with Layers

    ImageWorkshop is an Open Source library that lets you manipulate images with layers. With it you can resize, crop, make thumbnails, add watermarks and more. Here is an 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'); $image = $norwayLayer->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; ImageWorkshop is developed to make easy the most common cases for manipulating images in PHP. If you need something more powerful though, you should look at the Imagine library.

    - Snappy - Snapshot/PDF Library

    Snappy is a PHP5 library that allows you to take snapshots or PDFs of URLs or HTML documents. It depends on the wkhtmltopdf binary, which is available on Linux, Windows and OSX. You use it 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.

    - Idiorm - Lightweight ORM Library

    Idiorm is a personal favorite that I have used in tutorials in this site before. It is a lightweight ORM library and a fluent query builder for PHP5 that is built on top of PDO. With it, you can forget writing tedious SQL: $user = ORM::for_table('user') ->where_equal('username', 'j4mie') ->find_one(); $user->first_name = 'Jamie'; $user->save(); $tweets = ORM::for_table('tweet') ->select('tweet.*') ->join('user', array( 'user.id', '=', 'tweet.user_id' )) ->where_equal('user.username', 'j4mie') ->find_many(); foreach ($tweets as $tweet) { echo $tweet->text; } Idiorm has a sister library called Paris, which is an Active Record implementation built on top of it.

    - Underscore - PHP's Utility Belt

    Underscore is a port of the original Underscore.js – the utility belt for JavaScript applications. The PHP version doesn't disappoint and has support for nearly all of the original's functionality. Some 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.

    interger examples

    $a = 1234; // decimal number $a = 0123; // octal number (equivalent to 83 decimal) $a = 0x1A; // hexadecimal number (equivalent to 26 decimal) $a = 0b11111111; // binary number (equivalent to 255 decimal) $a = 1_234_567; // decimal number (as of PHP 7.4.0) decimal : [1-9][0-9]*(_[0-9]+)* | 0 hexadecimal : 0[xX][0-9a-fA-F]+(_[0-9a-fA-F]+)* octal : 0[0-7]+(_[0-7]+)* binary : 0[bB][01]+(_[01]+)*

    intval examples

    intval — Get the integer value of a variable echo intval(42); // 42 echo intval(4.2); // 4 echo intval('42'); // 42 echo intval('+42'); // 42 echo intval('-42'); // -42 echo intval(042); // 34 echo intval('042'); // 42 echo intval(1e10); // 1410065408 echo intval('1e10'); // 1 echo intval(0x1A); // 26 echo intval(42000000); // 42000000 echo intval(420000000000000000000); // 0 echo intval('420000000000000000000'); // 2147483647 echo intval(42, 8); // 42 echo intval('42', 8); // 34 echo intval(array()); // 0 echo intval(array('foo', 'bar')); // 1 echo intval(false); // 0 echo intval(true); // 1

    array_walk example

    array_walk — Apply a user supplied function to every member of an array Example #1 array_walk() example $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); function test_alter(&$item1, $key, $prefix) {$item1 = "$prefix: $item1";} function test_print($item2, $key) {echo "$key. $item2\n";} echo "Before ...:\n"; array_walk($fruits, 'test_print'); array_walk($fruits, 'test_alter', 'fruit'); echo "... and after:\n"; array_walk($fruits, 'test_print'); The above example will output: Before ...: d. lemon a. orange b. banana c. apple ... and after: d. fruit: lemon a. fruit: orange b. fruit: banana c. fruit: apple array_map — Applies the callback to the elements of the given arrays Example #1 array_map() example function cube($n) {return ($n * $n * $n);} $a = [1, 2, 3, 4, 5]; $b = array_map('cube', $a); print_r($b); This makes $b have: Array ( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125 ) Example #2 array_map() using a lambda function (as of PHP 5.3.0) $func = function($value) {return $value * 2;}; print_r(array_map($func, range(1, 5))); Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 ) Example #3 array_map() - using more arrays function show_Spanish($n, $m) {return "The number {$n} is called {$m} in Spanish";} function map_Spanish($n, $m) {return [$n => $m];} $a = [1, 2, 3, 4, 5]; $b = ['uno', 'dos', 'tres', 'cuatro', 'cinco']; $c = array_map('show_Spanish', $a, $b); print_r($c); $d = array_map('map_Spanish', $a , $b); print_r($d); The above example will output: // printout of $c Array ( [0] => The number 1 is called uno in Spanish [1] => The number 2 is called dos in Spanish [2] => The number 3 is called tres in Spanish [3] => The number 4 is called cuatro in Spanish [4] => The number 5 is called cinco in Spanish ) // printout of $d Array ( [0] => Array ( [1] => uno ) [1] => Array ( [2] => dos ) [2] => Array ( [3] => tres ) [3] => Array ( [4] => cuatro ) [4] => Array ( [5] => cinco ) )

    - Requests - Easy HTTP Requests

    Requests is a library that makes it easy to issue HTTP requests. If you are like me, and can never seem to remember the various options passed to Curl, this is for you: $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.

    - Buzz - Simple HTTP Request Library

    Buzz is another PHP 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; It is lacking in documentation, so you will have to read through the source code to get a feel of all the options that it supports. Or you can go with the Requests library that I presented above.

    - Goutte - Web Scraping Library

    Goutte is a library for scraping websites and extracting data. It provides a nice API that makes it easy to select specific elements from the remote pages. require_once '/path/to/goutte.phar'; use Goutte\Client; $client = new Client(); $crawler = $client->request('GET', 'http://www.symfony-project.org/'); // Click on links: $link = $crawler->selectLink('Plugins')->link(); $crawler = $client->click($link); // Extract data with a CSS-like syntax: $t = $crawler->filter('#data')->text(); echo "Here is the text: $t";

    - Carbon - DateTime Library

    Carbon is a simple API extension for the DateTime. It enhances the class with some useful methods for working with dates and time. For example: printf("Right now is %s", Carbon::now()->toDateTimeString()); printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); $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'); $endOfWorld = Carbon::createFromDate(2012, 12, 21, 'GMT'); // comparisons are always done in UTC if (Carbon::now()->gte($endOfWorld)) { die(); } if (Carbon::now()->isWeekend()) { echo 'Party!'; } echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago' Carbon hasn't seen new commits in the last few months, so you might want to check out Datum, a fork that continues to be worked on.

    - Ubench - Micro Benchmarking Library

    Ubench is a micro library for benchmarking your PHP code. It monitors execution time and memory usage. Here's an example: use Ubench\Ubench; $bench = new Ubench; $bench->start(); // Execute some code $bench->end(); // Get elapsed time and memory echo $bench->getTime(); // 156ms or 1.123s echo $bench->getTime(true); // elapsed microtime in float echo $bench->getTime(false, '%d%s'); // 156ms or 1s echo $bench->getMemoryPeak(); // 152B or 90.00Kb or 15.23Mb echo $bench->getMemoryPeak(true); // memory peak in bytes echo $bench->getMemoryPeak(false, '%.3f%s'); // 152B or 90.152Kb or 15.234Mb // Returns the memory usage at the end mark echo $bench->getMemoryUsage(); // 152B or 90.00Kb or 15.23Mb It would be a good idea to run these checks only while developing.

    - Validation - Input Validation Engine

    Validation claims to be the most awesome validation engine ever created for PHP. But can it deliver? See for yourself: use Respect\Validation\Validator as v; // 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 = new stdClass; $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 With this library you can validate your forms or other user-submitted data. In addition, it supports a wide number of existing checks, throwing exceptions and customizable error messages.

    - Filterus - Filtering Library

    Filterus is another filtering library, but it can not only validate, but also filter input to match a preset pattern. Here is an example: $f = Filter::factory('string,max:5'); $str = 'This is a test string'; $f->validate($str); // false $f->filter($str); // 'This ' Filterus has a lot of built-in patterns, supports chaining and can even validate array elements with individual validation rules.

    - Faker - Fake Data Generator

    Faker is a PHP library that generates fake data for you. It can come handy when you need to populate a test database or generate sample data for your web application. It is also very easy to use: // 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 ... As long as you keep accessing properties of the object, it will continue returning randomly generated data.

    - 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!" To see more advanced examples, I suggest taking a look at the official Mustache docs.

    - Gaufrette - File System Abstraction Layer

    Gaufrette is a PHP5 library that provides a filesystem abstraction layer. It makes it possible to work with local files, FTP servers, Amazon S3 and more in the same way. This permits you to develop your application without having to know how you are going to access your files in the future. use Gaufrette\Filesystem; use Gaufrette\Adapter\Ftp as FtpAdapter; use Gaufrette\Adapter\Local as LocalAdapter; // Local files: $adapter = new LocalAdapter('/var/media'); // Optionally use an FTP adapter: // $ftp = new FtpAdapter($path, $host, $username, $password, $port); // Initialize the filesystem: $filesystem = new Filesystem($adapter); // Use it: $content = $filesystem->read('myFile'); $content = 'Hello I am the new content'; $filesystem->write('myFile', $content); There are also caching and in-memory adapters, and more will be added over time.

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

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

    - HTMLPurifier - HTML XSS Protection

    HTMLPurifier (on github) is an HTML filtering library that protects your code from XSS attacks by using a combination of robust whitelists and agressive parsing. It also makes sure that the resulting markup is standards compliant. require_once '/path/to/HTMLPurifier.auto.php'; $config = HTMLPurifier_Config::createDefault(); $purifier = new HTMLPurifier($config); $clean_html = $purifier->purify($dirty_html); The best place to use this library would be when you are allowing users to submit HTML which is to be displayed unmodified on the site.

    - ColorJizz-PHP - Color Manipulation Library

    ColorJizz is a tiny library that can convert between different color formats and do simple color arithmetic. For example: use MischiefCollective\ColorJizz\Formats\Hex; $red_hex = new Hex(0xFF0000); $red_cmyk = $hex->toCMYK(); echo $red_cmyk; // 0,1,1,0 echo Hex::fromString('red')->hue(-20)->greyscale(); // 555555 It has support for and can manipulate all major color formats.

    - PHP Geo - Geo Location Library

    phpgeo is a simple library for calculating distances between geographic coordinates with high precision. For example: use Location\Coordinate; use Location\Distance\Vincenty; $coordinate1 = new Coordinate(19.820664, -155.468066); // Mauna Kea Summit $coordinate2 = new Coordinate(20.709722, -156.253333); // Haleakala Summit $calculator = new Vincenty(); $distance = $calculator->getDistance($coordinate1, $coordinate2); // returns 128130.850 (meters; ≈128 kilometers) This will work great in apps that make use of location data. To obtain the coordinates, you can use the HTML5 Location API, Yahoo's API (or both, like we did in the weather web app tutorial).

    - ShellWrap - Beautiful Shell Wrapper

    ShellWrap is library that allows you to work with the powerful Linux/Unix command line tools in PHP through a beautiful syntax: require 'ShellWrap.php'; use \MrRio\ShellWrap as sh; // List all files in current dir echo sh::ls(); // Checkout a branch in git sh::git('checkout', 'master'); // You can also pipe the output of one command, into another // This downloads example.com through cURL, follows location, then pipes through grep to // filter for 'html' echo sh::grep('html', sh::curl('http://example.com', array( 'location' => true ))); // Touch a file to create it sh::touch('file.html'); // Remove file sh::rm('file.html'); // Remove file again (this fails, and throws an exception because the file doesn't exist) try { sh::rm('file.html'); } catch (Exception $e) { echo 'Caught failing sh::rm() call'; } The library throws exceptions when an error occurs in the command, so you can act accordingly. It also can pipe the output of one command as the input of another for even greater flexibility.

    - Symfony Console Component

    Symfony Console Component Command line interface (CLI) is one of the core elements of major PHP frameworks including Laravel, Symfony, CodeIgniter and others. This library provides easy to understand command line interface in Symfony. Its integration in the application is also quite simple and is precisely made to build testable command line interfaces. Composer Command: composer require symfony/console Implementation First you need to create a PHP script and define console like this: <?php // application.php require __DIR__.'/vendor/autoload.php'; use Symfony\Component\Console\Application; $application = new Application(); $application->run(); Now you need to register the commands using add() functions. $application->add(new GenerateAdminCommand());

    - Symfony Finder Component

    Symfony Finder Component Developers often find difficulties while locating desired files and folders within the project. Using this Finder component, developers can easily find files and directories within the project. It provides different attributes (name, file size, modification time, extension etc.) to find the related files or directories. Moreover, it has an intuitive interface which helps users to find the desired resources. Composer Command: composer require symfony/finder Implementation Let’s suppose you need to find all files and folders in the root directory. You can do it as: You can also find files in FTP and user defined streams

    - Psr/log

    Psr/log If you want to find all the interfaces, classes, traits etc. related to PS-3, this PHP logging library helps you finding all those resources with just a few clicks. The library isn’t a logger itself, but is an interface that forms a logging system. This PHP logging library comes up with full documentation, so that developers can easily work with it. Composer Command: composer require psr/log Implementation You can use the logger for logging like below code snippet: <?php use Psr\Log\LoggerInterface; class Foo { private $logger; public function __construct(LoggerInterface $logger = null) { $this->logger = $logger; } public function doSomething() { if ($this->logger) { $this->logger->info('Doing work'); } // do something useful } }

    - Monolog

    Monolog It is necessary to save the logs to particular files or folders. Saving them at a certain place often seems to be a difficult job, but using this PHP logging library you can easily save your logs to the defined locations. Monolog helps you to send you logs to defined files, sockets, inboxes, databases and other web services. It uses a PSR-3 interface which allows you to type-hint logs against your own libraries in order to keep maximum interoperability. Composer Command: composer require monolog/monolog Implementation The basic usage to log error and warning with PSR log can be defined as: <?php use Monolog\Logger; use Monolog\Handler\StreamHandler; // create a log channel $log = new Logger('name'); $log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING)); // add records to the log $log->warning('Foo'); $log->error('Bar');

    - Guzzle

    Guzzle Guzzle works as a particular PHP client for sending HTTP requests to the web servers. Using this library, developers can easily send HTTP requests to integrate with the web services. The library provides a simple interface for building query strings, POST requests, HTTP cookies and other attributes. It also allows developers to send both synchronous and asynchronous requests from the same interface. Composer Command: composer require guzzlehttp/guzzle Implementation Previously we have written some articles consuming Cloudways API in Guzzle. Let me show the example usage of Guzzle api to get authentication and then run different methods to get servers and applications. You can read the complete article here. Let’s look at the example: <?php Class CloudwaysAPIClient { private $client = null; const API_URL = "https://api.cloudways.com/api/v1"; var $auth_key; var $auth_email; var $accessToken; public function __construct($email,$key) { $this->auth_email = $email; $this->auth_key = $key; $this->client = new GuzzleHttpClient(); $this->prepare_access_token(); } public function prepare_access_token() { try { $url = self::API_URL . "/oauth/access_token"; $data = ['email' => $this->auth_email,'api_key' => $this->auth_key]; $response = $this->client->post($url, ['query' => $data]); $result = json_decode($response->getBody()->getContents()); $this->accessToken = $result->access_token; } catch (RequestException $e) { $response = $this->StatusCodeHandling($e); return $response; } }

    - Assert

    Assert Using the Assert library, developers can easily test the input and output of the methods within minutes. It’s a simple PHP library that reduces the need of extensive coding in web applications. The integration of the library within the project is also quite easy, as it provides complete documentation for the integration. It features some built-in error messages by default, which you can later change according to custom error requirements. Composer Command: composer require webmozart/assert

    - Symfony/translation

    Symfony/translation This translation package is really handy for the developers who want to build multilingual apps supported by various languages. It is the growing demand of the modern world to build a multilingual product, and using this library developers can easily create desired projects with different languages. The library comes up with complete documentation and is easy to work with. Composer Command: composer require symfony/translation Implementation You need to define the locale in constructor class to translate pages automatically. use Symfony\Component\Translation\Translator; $translator = new Translator('fr_FR');

    - PHPUnit

    PHPUnit PHPUnit is perhaps the best PHP library for performing unit testing in PHP web applications. It is used to test application’s code for possible errors and bugs. While performing the unit testing with PHPUnit, developers can resolve various application bugs that may arise during the run-time execution. Hence, the library is vital to assess the cores of application and fixing it timely with the required solutions. Composer Command: composer require phpunit/phpunit

    - PHP-code-coverage

    PHP-code-coverage If you want to measure how much source code of a program is executed during a particular test, this library helps you out in measuring that degree of code. The library provides you collection and rendering functionality of the executed PHP code, so that you can get a better idea about the tested chunk of code and how to resolve the errors in it. Composer Command: composer require phpunit/php-code-coverage

    - Swiftmailer

    Swiftmailer Swiftmailer is a feature-rich PHP email library primarily built to ease out mailing operation in any web application. The library provides advanced object-oriented-approach combined with multitude of mailing features to send emails over the web. The most significant feature of Swiftmailer is that it protects the mails from header injection attacks without removing the request data content, which is what makes it a very efficient mailing system. Composer Command: composer require swiftmailer/swiftmailer Implementation The basic usage of swiftmailer for sending emails is: require_once '/path/to/vendor/autoload.php'; // Create the Transport $transport = (new Swift_SmtpTransport('smtp.example.org', 25)) ->setUsername('your username') ->setPassword('your password'); // Create the Mailer using your created Transport $mailer = new Swift_Mailer($transport); // Create a message $message = (new Swift_Message('Wonderful Subject')) ->setFrom(['john@doe.com' => 'John Doe']) ->setTo(['receiver@domain.org', 'other@domain.org' => 'A name']) ->setBody('Here is the message itself'); // Send the message $result = $mailer->send($message);

    - Email-validator

    Email-validator Email-validator is a specialized PHP validation library used to validate emails via number of chosen validation features. The library provides multiple types of validation for emails including RFC Validation, NoRFCWarningsValidation, SpoofCheckValidation and others. The library also provides DNS validation feature through which you can validate and spam out emails with the DNS verification. Composer Command: composer require egulias/email-validator Implementation You need to define the validation strategy or method to follow in the code. Right now you have 6 type of available validations which you can see in official documentation: The basic usage is as follows: use Egulias\EmailValidator\EmailValidator; use Egulias\EmailValidator\Validation\RFCValidation; $validator = new EmailValidator(); $validator->isValid("example@example.com", new RFCValidation()); //true

    - PHP dotenv

    PHP dotenv This library helps developers to export environment variables from .env to getenv(), $_ENV and $_SERVER. The library is recently upgraded to the latest version V3, which now supports multiline variables as well. The library also allows developers to choose which part of the environment they want to read and modify according to the needs of application. Composer commands: composer require vlucas/phpdotenv Implementation First you need to create a .env file on the root level of your directory. Next add variable and values in it like this: S3_BUCKET="devbucket" SECRET_KEY="abc123" Now load the .env file in application like this: $dotenv = Dotenv\Dotenv::create(__DIR__); $dotenv->load(); Now you can access the variables created in env file with these three methods. You can use any one of them. $s3_bucket = getenv('S3_BUCKET'); $s3_bucket = $_ENV['S3_BUCKET']; $s3_bucket = $_SERVER['S3_BUCKET'];

    - Symfony Filesystem Component

    Symfony Filesystem Component This Filesystem library provides basic utilities for the filesystem. Using this library, developers can easily create directories, files and much more in just a few steps. It also allows you to change the edit rights of the file and create a symlink with it. To install the library, you just have to use composer for the installation which is a quite straight forward process. Composer Command: composer require symfony/filesystem

    - Twig

    Twig Twig is a fast, efficient and secure templating engine for PHP. It compiles templates to simple PHP code which is easily understandable to the developers. This reduces the overhead of complex backend code, and gives application a boost in performance. Moreover, it is also super-customizable, as it allows you to define your own tags, filters and custom DSL according to the needs of application. Composer Command: composer require twig/twig

    - Faker

    Faker Faker is a handy PHP library that allows developers to generate dummy content for the web applications. Whether you want to fill up application database with mock data, or want to create sample XML documents, Faker does the job for you with good looking testing data. It supports all PHP 5+ versions and requires easy composer installation just once. Composer command: composer require fzaninotto/faker Implementation You need to use Faker\Factory::create() to create and initialize fake generator which can generate data by accessing properties. <?php // require the Faker autoloader require_once '/path/to/Faker/src/autoload.php'; // alternatively, use another PSR-4 compliant autoloader // 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; // Dolores sit sint laboriosam dolorem culpa et autem. Beatae nam sunt fugit // et sit et mollitia sed. // Fuga deserunt tempora facere magni omnis. Omnis quia temporibus laudantium // sit minima sint.

    - AWS SDK for PHP

    AWS SDK for PHP This particular AWS library allows developers to use Amazon Web Services in PHP applications. Using this AWS SDK, you can build desired web applications associated with Amazon S3, Glacier, DynamoDB and other Amazon services. Simply install this SDK using composer or download a zip file, all the Amazon services come pre-configured in it and are ready to be deployed with your PHP application. But, since you are on Cloudways, you won't gonna need this library for your PHP applications. As Cloudways provides PHP website hosting on completely managed AWS services for its deployed applications combined with the integrated stack of optimized web tools. Composer Command: composer require aws/aws-sdk-php Implementation First you need to initialize the sdk by including vendor files and then you can create different use cases like may be you want to upload files. Let’s see how you can do this. <?php // Require the Composer autoloader. require 'vendor/autoload.php'; use Aws\S3\S3Client; // Instantiate an Amazon S3 client. $s3 = new S3Client([ 'version' => 'latest', 'region' => 'us-west-2' ]); Now upload the file on the AWS servers like this: <?php // Upload a publicly accessible file. The file size and type are determined by the SDK. try { $s3->putObject([ 'Bucket' => 'my-bucket', 'Key' => 'my-object', 'Body' => fopen('/path/to/file', 'r'), 'ACL' => 'public-read', ]); } catch (Aws\S3\Exception\S3Exception $e) { echo "There was an error uploading the file.\n"; }

    - PHPseclib

    PHPseclib Transferring files from one server to another always remains a risky process, because hackers can intervene in between the route and can steal confidential information. To fortify this process, PHPSeclib provides a fully secure data transmission between the servers using SFTP protocol. This PHP SFTP library is compatible with all the latest versions of PHP and is easy to integrate in web applications. Composer Command: composer require phpseclib/phpseclib

    - Laravel Tinker

    Laravel Tinker Laravel Tinker is a powerful Laravel package built to give users the ease to interact with Laravel applications directly from command line. It is perfect to use with Eloquent ORM to manage jobs, events and more. It is a built in artisan tool and can be easily accessed using the Tinker artisan command in composer. Composer Command: composer require laravel/tinker

    - Predis

    Predis Predis is a Redis client for PHP applications. It is a very effective caching tool precisely made to reduce the overhead of caching in web applications. You can use it for clustering, master slave replication setups, transparent key prefixing and many more optimization operations. It also supports different custom connection classes for providing different network and protocol backends. Composer Command: composer require predis/predis Implementation For implementing predis in your PHP project you first need to load the library in the project. // Prepend a base path if Predis is not available in your "include_path". require 'Predis/Autoloader.php'; Predis\Autoloader::register(); Now create a client connection like this: $client = new Predis\Client(); $client->set('foo', 'bar'); $value = $client->get('foo');

    - PHP AMQP Library

    php-amqplib is a library purely designed for PHP. It is compatible with every framework of PHP and is fully featured for RabbitMQ client. A number of OS are being supported by RabbitMQ, and has several official client libraries available, one of them is php-amqplib. It is a message-oriented middleware whose main features are: Queuing and Orientation. Composer Command: composer require php-amqplib/php-amqplib Implementation <?php Include (__DIR__ . '/config.php'); use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Connection\AMQPSocketConnection; use PhpAmqpLib\Connection\AMQPSSLConnection; define ('CERTS_PATH', '/git/rabbitmqinaction/av_scratchwork/openssl'); $sslOptions = array ( $ssl_options = array ( 'cafile' => CERTS_PATH . '/rmqca/cacert.pem', 'local_cert' => CERTS_PATH . '/phpcert.pem', 'verify_peer' => true );

    - Laravel-Permission Library

    This library is for Laravel 5.8 and for later versions. This package allows you to manage user’s role and permissions in a database. Composer command: composer require spatie/laravel-permission Implementation You can manually add the service provider in your config/app.php file: 'providers' => [ // ... Spatie\Permission\PermissionServiceProvider::class, ]; You must publish the migration with: php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations"

    - Twill Library

    Twill is an open source CMS toolkit for Laravel. It provides author to create, curate and personalize command in the digital workflows. It also allows publishers to design and take control without restricting anything. It also gives the freedom to produce a powerful admin without undermining developer's controls with the configuration. Composer command: composer global require yanhaoli/create-twill-app:"1.0.*" create-twill-app new blog

    - OAuth 2.0

    OAuth is an open standard for access delegation. It gives access to user information on other websites but without revealing the password. A lightweight and powerful OAuth 2.0 library is built for the users to authenticate and authorize the client of application and protect its API. Composer command: composer require league/oauth2-server Implementation The examples here demonstrate its usage with the Slim Framework. Slim is not a requirement to use this library, you just need something that generates PSR7-compatible HTTP requests and responses. The client will redirect the user to an authorization endpoint. $app->get('/authorize', function (ServerRequestInterface $request, ResponseInterface $response) use ($server) { try { $authRequest = $server->validateAuthorizationRequest($request); $authRequest->setUser(new UserEntity()); // an instance of UserEntityInterface $authRequest->setAuthorizationApproved(true); return $server->completeAuthorizationRequest($authRequest, $response); } catch (OAuthServerException $exception) { return $exception->generateHttpResponse($response); } catch (\Exception $exception) { $body = new Stream(fopen('php://temp', 'r+')); $body->write($exception->getMessage()); return $response->withStatus(500)->withBody($body); } });

    - Laravel Backup

    This package creates a backup of your application. A zip file of backup is created containing all the files in the specified directories. Any file system is supported by the backup package, and it can also create multiple backup in different file systems at once. It also notifies you via mail, slack or other notification provider if something goes wrong. Composer command: composer require spatie/laravel-backup Implementation To publish the config file to config/backup.php run: php artisan vendor:publish --provider="Spatie\Backup\BackupServiceProvider"

    - PHP Rector

    This package instantly upgrade and refactor the PHP code. It renames classes, namespaces & constants, and upgrades PHP 5.3 to PHP 7.4 easily. It also migrates projects from Nette to Symfony, and turns static Laravel to Dependency Injection. It is used with almost every PHP framework i.e. Laravel, Symfony, CakePHP, PHPUnit and much more. Composer command: composer require rector/rector Implementation When the library is first implemented, you can execute a dry run and then permanently change your code through the following commands. #see the diff first vendor/bin/rector process src --dry-run # if it's ok, apply vendor/bin/rector process src

    - Lighthouse

    GraphQL is a query language for the APIs. It fulfills the queries on your existing data and gives an extensive understanding of the data in APIs. It also gives the client the power to specify the needs, and evolves the API overtime. Composer command: composer require nuwave/lighthouse Implementation By the following artisan command, you can get the default Lighthouse Schema: php artisan vendor:publish --provider="Nuwave\Lighthouse\LighthouseServiceProvider" --tag=schema

    - Laravel Admin LTE

    This library provides an easy integration of AdminLTE with Laravel 5 or later versions. Composer command: composer require jeroennoten/laravel-adminlte Implementation <?php namespace JeroenNoten\LaravelAdminLte; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Contracts\Container\Container; use JeroenNoten\LaravelAdminLte\Menu\Builder; use JeroenNoten\LaravelAdminLte\Events\BuildingMenu; class AdminLte { protected $menu; protected $filters; protected $events; protected $container; public function __construct( array $filters, Dispatcher $events, Container $container ) { $this->filters = $filters; $this->events = $events; $this->container = $container; } public function menu() { if (! $this->menu) { $this->menu = $this->buildMenu(); } return $this->menu; } protected function buildMenu() { $builder = new Builder($this->buildFilters()); if (method_exists($this->events, 'dispatch')) { $this->events->dispatch(new BuildingMenu($builder)); } else { $this->events->fire(new BuildingMenu($builder)); } return $builder->menu; } protected function buildFilters() { return array_map([$this->container, 'make'], $this->filters); } }

    - Swagger PHP library

    Swagger is a library that helps to generate an interactive documentation for restful API using phpdoc annotations. It is compatible with OpenAPI 3.0, as it extracts code & existing annotations using a CLI interface. Composer command: composer require zircote/swagger-php Implementation /** * @OA\Info(title="My First API", version="0.1") */ /** * @OA\Get( * path="/api/resource.json", * @OA\Response(response="200", description="An example resource") * ) */

    - Laravel/Passport MongoDB

    It is a service provider that helps to add support for Laravel Passport and MongoDB. Composer command: composer require jenssegers/mongodb

    - Best PHP Ecommerce Libraries to Integrate in Web Apps

    - Stripe-PHP

    Stripe-PHP Stripe is a popular e-payment platform used to conduct online transactions over the web. This package is specially made for PHP ecommerce applications to interact with the Stripe API. This library provides a fast, efficient access to the Stripe API and makes end-to-end connection secure between the platforms. The library includes predefined set of API classes which are compatible with most of Stripe versions. Composer Command: composer require stripe/stripe-php You Might Also Like: Laravel Stripe Payment Gateway Integration

    - Omnipay

    Omnipay This payment processing PHP library allows fast connection to Omnipay web services. It deploys a very smooth web API that is fully unit-tested, advanced and comes with full documentation to ease out the configuration process. The package itself uses the powerful PHP-HTTP library to make HTTP requests, so that all the transactions becomes secure and reliable. Composer Command: composer require league/omnipay

    - Laravel Cashier

    Laravel Cashier Laravel Cashier provides a simple and easy-to-use interface for Stripe’s subscription billing services. All the boilerplate billing services come pre-coded in the library, so that you don’t have to worry for the complex configuration of payment billing. Using Laravel Cashier, you can easily handle coupons, discount codes, swapping subscription, invoices and other operations. Composer Command: composer require laravel/cashier

    - Sylius

    Sylius If you want to integrate Sylius with your PHP application, this library will help you in building the secure web connection. It is built with strong API structure to connect web applications safely with the Sylius ecommerce platform. Just navigate to composer and install the Sylius library, all the payment settings come pre configured in it, so that developers aren’t required to do extra work. Composer Command: composer create-project sylius/sylius

    - Laravel Aimeos

    Laravel Aimeos Aimeos is one of the most used ecommerce packages for Laravel. It provides advanced ecommerce functionalities to the existing Laravel application. It is a composer based extension having compatibility with all the Laravel 5+ versions. It integrates the core online store components into the Laravel application and provides optimized ecommerce features for the applications. Composer Command: composer require aimeos/aimeos-laravel

    - Spatie Image Optimizer

    Spatie Image Optimizer Image optimization improves application’s performance and holds a great value in the sights of Google Bot. Spatie is a specialized PHP image optimization library for Laravel applications. It can easily optimize PNGs, JPGs, SVGs and GIFs according to the required needs. This PHP image library comes pre-configured with multiple image optimization tools including JpegOptim, Optipng, Pngquant2, SVGO and Gifsicle. The interface is quite simple and is easy to work with even for beginners. Composer Command: composer require spatie/image-optimizer

    - Elastica

    Elastica Elasticsearch is a popular full-text search system widely used by most of the PHP developers all around the world. It allows fast data searching from the records stored in its database. This package is a PHP client for Elasticsearch, it provides pre-configured settings for Elasticsearch and gives fast data indexing for applications. It is compatible with all PHP 5+ versions and comes up with detailed installation documentation. Composer Command: composer require ruflin/elastica

    - Intervention/image

    Intervention/image This is another great tool to handle image optimization in PHP applications. Using this PHP image library, you can easily customize images as you wish. It provides you an easy-to-use interface for creating, editing and composing images. To integrate with Laravel applications easily, the PHP image library includes ServiceProviders and Facades as they facilitate hassle-free package installation process. Composer Command: composer require predis/predis

    - Minify

    Minify Minification is one of the most important aspects of optimizing CSS and JavaScript files. It helps reducing the overhead programming patterns of the file and optimizes it according to the standards of web performance. This library helps developers to minify their CSS and JavaScripting files. It removes the white spaces, strip comments and other unnoticed attributes from the code, making it light and simple to execute. It combines statements, small assets in CSS files and minifies few coding structures according to best standards. Composer Command: composer require matthiasmullie/minify

    - Swap

    Swap Swap is a handy PHP library for working with currency exchange rates. It allows you to retrieve those exchange rates from the popular currency platforms like Fixer, currencylayer and others. It is one of the most used libraries for working with exchange rates, as it is also integrated with other libraries and has simple configuration pattern to work with. Composer Command: composer require florianv/swap

    - Tcpdf

    Tcpdf This PHP PDF library helps you generate high quality PDF documents. It supports all standard and custom page formats, making it simple for the users to work with PDF documents. The package provides several advanced formatting features including automatic page header and footer management, annotations, links, multiple columns (if needed), text rendering and various other features. In short, it’s a fine tool to work and manage PDF documents on the go. Composer Command: composer require tecnickcom/tcpdf

    - Shellwrap

    Shellwrap When it comes to PHP libraries this one creates magic. Powerful syntax and Linux / UNIX tools and easy collaboration of commands along with detecting PHP errors, Shellwrap does it all.

    - Imagine

    Imagine With image manipulation and in built PHP 5.3, Imagine is an OOP library that uses the best designs for best decoupling and unit testable code.3

    - PHP_Markdown

    PHP Markdown Although originally a port to the John Grubber PHP of Markdown, this library now contains PHP Markup Extra and other additional tools.

    - PHP_Error

    PHP Error Just as the name suggests, this PHP library helps in detecting errors along with Ajax works, code snipers and syntax highlights.

    - Unirest

    Unirest When it comes to light weight http libraries which offer help to the web developers, Unirest remains unparalleled.

    - PHPgeo

    PHPgeo PHPgeo is specially designed for measuring geographical co-ordinates and the distance between them.

    - Faker

    Faker This PHP library creates fake data for stress tests, bootstrapping the database, creating XML documents and more.

    - Parody

    Parody Parody is one of the simplest PHP libraries available which defines class structure and makes operation quick as well as helps in getting properties and installing objects.

    - Klein

    Klein If you want a PHP 5.3 router which is speedy and easy, Klein is your thing. It is very useful in building website applications.

    - Hoa

    Hoa A perfect bridge joining the business and research areas, Hoa is extensible, structured and modular. It’s one of the best PHP libraries available.

    - Gaufrette

    Gaufrette This PHP5 library provides abstraction layer which allows you to develop an app without the headache of knowing where and how data is being stored.

    - Buzz

    Buzz Buzz is specifically created PHP library for HTTP issues.

    - Alice

    Alice Alice provides users with essential data generating tools and produces loads of fake data and fixtures for development and testing of the project.

    - Ham

    Ham Ham basically provides a PHP Microframework for various uses. It will add more tools for easy PHP development.

    - Carbon

    Carbon When working with date and time, Carbon is one of the easiest and simplest PHP libraries.

    - uBench

    uBench uBench is one of the most useful PHP libraries for benchmark developing.

    - PHP_PasswordLib

    PHP PasswordLib Easily installed and used, PHP PasswordLib is meant for satisfying the cryptographic needs that may arise for developers.

    - ColorJizz_PHP

    ColorJizz PHP ColorJizz PHP was made to simplify the use of frameworks like Symfony 2. This PHP library uses PSR for creating namespaces.

    - Whoops

    Whoops Whoops helps in easy management of errors and exceptions resulting in better management of the project.

    - Ratchet

    Ratchet Using WebSockets, Ratchet helps in the creation of bidirectional apps between client and servers.

    - Requests for PHP

    Requests for PHP A no-dependencies library that lets you send HTTP requests. It provides the needed methods for adding headers, accessing response data, handling forms, and everything else you may need, neatly packaged in a clean and easy to use API. $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) "[...]"

    - Rinvex Country

    Rinvex Country Rinvex Country is a PHP package that lets developers retrieve detailed information about the countries of the world. Using the over 50 methods you can get the area of Angola, the currency of Cyprus, the native name of Namibia or even the FIFA name of Finland. There is a ton of info available and the data sources are pretty reliable. $egypt = country('eg'); $egypt->getCapital(); // Cairo $egypt->getDemonym(); // Egyptian $egypt->getTld(); // .eg $egypt->getContinent(); // Africa $egypt->getSubregion(); // Northern Africa $egypt->getBorders(); // ["ISR","LBY","SDN"]

    - Botman

    Botman A PHP library for developing messenger bots. Works with most of the popular messaging platforms including Facebook Messenger, Slack, Telegram, WeChat, and others. There is also a helpful boilerplate Laravel project available here. // create an instance $botman = BotManFactory::create($config); // give the bot something to listen for. $botman->hears('hello', function (BotMan $bot) { $bot->reply('Hello yourself.'); }); // start listening $botman->listen(); If you are not familiar with the concept of messenger bots we suggest you check out our article Developer's Introduction To Chatbots.

    - Charts

    Charts Laravel package for generating highly customizable charts out of datasets. The package works as a PHP wrapper for multiple built-in JavaScript chart libraries, allowing devs to create a wide variety of graphs, gauges and progressbars using only one tool. $chart = Charts::create('line', 'highcharts') ->title('My nice chart') ->labels(['First', 'Second', 'Third']) ->values([5,10,20]) ->dimensions(0,500);

    - Swap

    Swap Swap allows you to retrieve currency exchange rates from a number of services such as Fixer, Google, and Yahoo. Request responses can be easily cached and accessed later. The library is available in the form of a Laravel Package as well. // Build Swap with Fixer.io $swap = (new Builder()) ->add('fixer') ->build(); // Get the latest EUR/USD rate $rate = $swap->latest('EUR/USD'); // 1.129 $rate->getValue(); // Get the EUR/USD rate 15 days ago $rate = $swap->historical('EUR/USD', (new \DateTime())->modify('-15 days'));

    - Math PHP

    Math PHP A collection of mathematical functions and algorithms ranging from simple algebra to finances, statistics, numerical analysis and others fields. The library is modular, has a straightforward API, and doesn't require any external dependencies. // Factors of an integer $factors = Algebra::factors($n); // Fibonacci sequence $fib = Advanced::fibonacci($n); // Combinations $nCk = Combinatorics::combinations($n, $k); // Likelihood ratios $LL = Experiment::likelihoodRatio($a, $b, $c, $d);

    - PHPUnit

    PHPUnit PHPUnit is an advanced testing framework that enables teams to thoroughly test their code. Unit tests are written in standalone object-oriented classes with the help of many methods for handling assertions, dependencies, etc. A simple CLI is provided for running test and generating reports. class StackTest extends TestCase { public function testPushAndPop() { $stack = []; $this->assertEquals(0, count($stack)); array_push($stack, 'foo'); $this->assertEquals('foo', $stack[count($stack)-1]); $this->assertEquals(1, count($stack)); $this->assertEquals('foo', array_pop($stack)); $this->assertEquals(0, count($stack)); } }

    - Atoum

    Atoum A less popular testing framework we also wanted to share. Atoum offers a one-step installation precess and a relatively simple workflow, while still maintaining a ton of great features. It has a mock engine, expressive assertions, and a CLI that can execute multiple tests in parallel. $this->given($testedInstance = new testedClass()) ->and($testedClass[] = $firstValue = uniqid()) ->then ->sizeof($testedInstance)->isEqualTo(1) ->string($testedClass[0])->isEqualTo($firstValue);

    - Simple Regex Language

    Simple Regex Language A PHP implementation of the Simple Regex Language - a verbose way of writing regular expressions. The library provides multiple methods that can be chained together, forming readable and easy to understand RegEx rules. The library has ports for JavaScript and Python as well. $query = SRL::startsWith() ->anyOf(function (Builder $query) { $query->digit() ->letter() ->oneOf('._%+-'); })->onceOrMore() ->literally('@') ->anyOf(function (Builder $query) { $query->digit() ->letter() ->oneOf('.-'); })->onceOrMore() ->literally('.') ->letter()->atLeast(2) ->mustEnd()->caseInsensitive();

    - Stash

    Stash Stash makes it easy to speed up your code by caching the results of expensive functions or code. Certain actions, like database queries or calls to external APIs, take a lot of time to run but tend to have the same results over short periods of time. This makes it much more efficient to store the results and call them back up later. $pool = $this->cachePool; // Get a Stash object from the cache pool. $item = $pool->getItem("/user/{$userId}/info"); // Get the data from it, if any happens to be there. $userInfo = $item->get(); // Check to see if the cache missed, which could mean that it either // didn't exist or was stale. if($item->isMiss()) { // Run the relatively expensive code. $userInfo = loadUserInfoFromDatabase($userId); // Set the new value in $item. $item->set($userInfo); // Store the expensive code so the next time it doesn't miss. $pool->save($item) }

    - PHP VCR

    PHP VCR A port of the popular Ruby library for testing HTTP interactions. PHP VCR records HTTP requests and stores them in "cassettes" which can be replayed later on. A set of testing utilities are also provided, making it possible to inspect and compare recordings in detail. // After turning on, the VCR will intercept all requests \VCR\VCR::turnOn(); // Record requests and responses in cassette file 'example' \VCR\VCR::insertCassette('example'); // Following request will be recorded once and replayed in future test runs $result = file_get_contents('http://example.com'); $this->assertNotEmpty($result); // To stop recording requests, eject the cassette \VCR\VCR::eject(); // Turn off VCR to stop intercepting requests \VCR\VCR::turnOff();

    - OAuth 2.0 Server

    OAuth 2.0 Server This library allows you to easily configure an OAuth 2.0 server and set up all the authentication levels needed to protect your API. It is fully standards compliant and supports all the grants defined by OAuth protocol. The Laravel Passport module is built on top of the OAuth 2.0 Server. // Setup the authorization server $server = new \League\OAuth2\Server\AuthorizationServer( $clientRepository, $accessTokenRepository, $scopeRepository, $privateKey, $publicKey ); // Enable a grant on the server $server->enableGrantType( new \League\OAuth2\Server\Grant\ClientCredentialsGrant(), new \DateInterval('PT1H') // access tokens will expire after 1 hour );

    - Imagine

    Imagine An image manipulation library that tries to bring together all low level PHP image processing libraries under the same object-oriented API. This allows Imagine to be used for a wide variety of tasks such as drawing, resizing, cropping, filters, effects, metadata editing, and others. $palette = new Imagine\Image\Palette\RGB(); $image = $imagine->create(new Box(400, 300), $palette->color('#000')); $image->draw() ->ellipse(new Point(200, 150), new Box(300, 225), $image->palette()->color('fff')); $image->save('/path/to/ellipse.png');

    - MINI

    MINI Extremely simple and easy to understand skeleton PHP application, providing only the most essential features every project needs. It does not strive to be a do-it-all framework like Laravel, but due to it's simplicity MINI can be used for getting smaller apps up and running in no time. // Working with the model $songs = $this->model->getAllSongs(); $amount_of_songs = $this->model->getAmountOfSongs(); // Loading views require APP . 'views/_templates/header.php'; require APP . 'views/songs/index.php'; require APP . 'views/_templates/footer.php';

    - AWS SDK

    AWS SDK The official PHP library for working with Amazon Web Services. The SDK makes it easy to connect AWS with any PHP project and access all the various available services. There is also a useful Laravel wrapper which can be found here. // Instantiate an Amazon S3 client. $s3 = new S3Client([ 'version' => 'latest', 'region' => 'us-west-2' ]); $s3->putObject([ 'Bucket' => 'my-bucket', 'Key' => 'my-object', 'Body' => fopen('/path/to/file', 'r'), 'ACL' => 'public-read', ]);

    - Purl

    Purl Lightweight PHP library for working with URLs. With Purl you can compose complex paths attribute by attribute, extract data from URLs, manipulate queries, recognize URLs in strings, and much more. $url = \Purl\Url::parse('http://jwage.com') ->set('scheme', 'https') ->set('port', '443') ->set('user', 'jwage') ->set('pass', 'password') ->set('path', 'about/me') ->set('query', 'param1=value1&param2=value2'); echo $url->getUrl(); // https://jwage:[email protected]:443/about/me?param1=value1&param2=value2 echo $url->publicSuffix; // com echo $url->registerableDomain; // jwage.com

    - Daux.io

    Daux.io Documentation generator that uses a simple folder structure and Markdown files to create responsive documentation websites. Daux.io has automatic syntax highlighting, 4 theming options, Bootstrap HTML for easy customization, navigation with readable URLs, and many other goodies. // Example configuration { "title": "DAUX.IO", "tagline": "The Easiest Way To Document Your Project", "author": "Justin Walsh", "image": "app.png", "html": { "theme": "daux-blue", "breadcrumbs": true, "repo": "justinwalsh/daux.io", "edit_on_github": "justinwalsh/daux.io/blob/master/docs", "twitter": ["justin_walsh", "todaymade"], "google_analytics": "UA-12653604-10", "links": { "Download": "https://github.com/justinwalsh/daux.io/archive/master.zip", "GitHub Repo": "https://github.com/justinwalsh/daux.io", "Made by Todaymade": "http://todaymade.com" } } }

    - Dompdf

    Dompdf Dompdf is a PDF generator that takes regular HTML markup and converts it to .pdf files. It understands most CSS rules, which can be fed in-line or via an external stylesheet. // reference the Dompdf namespace use Dompdf\Dompdf; // instantiate and use the dompdf class $dompdf = new Dompdf(); $dompdf->loadHtml('hello world'); // (Optional) Setup the paper size and orientation $dompdf->setPaper('A4', 'landscape'); // Render the HTML as PDF $dompdf->render(); // Output the generated PDF to Browser $dompdf->stream();

    - Instaphp

    Instaphp Non-official library for accessing the Instagram API. It provides developers with an easy way to authenticate their app and get access to various Instagram data endpoints including images, users, likes, comments, and tags. $api = new Instaphp\Instaphp([ 'client_id' => 'your client id', 'client_secret' => 'your client secret', 'redirect_uri' => 'http://somehost.foo/callback.php', 'scope' => 'comments+likes' ]); $popular = $api->Media->Popular(['count' => 10]); if (empty($popular->error)) { foreach ($popular->data as $item) { printf('<img src="%s">', $item['images']['low_resolution']['url']); } }

    - Latitude

    Latitude Zero-dependencies library for building SQL queries using chainable methods. It supports most query types and works well with MySQL, Postgres, SQL Server, and other databases. There are also built-in escaping helpers for protecting against SQL injection. $select = SelectQuery::make( 'id', 'username' ) ->from('users'); echo $select->sql(); // SELECT id, username FROM users