13 PHP tips and tricks that can make Developers life easier

PHP has a pretty bad reputation being a poor cousin of scripting languages . At conferences, no presenter wants to be speak about it and the truth is that the many atrocities that make PHP developers emboldened by its flexibility and simplicity have a good share of the blame. However, it is one of the most widely used language for web development, and the people who love and embrace PHP are truly making great contribution by developing excellent frameworks and content management systems which gets things done easily and smartly and brings it at par with another modern languages.

In the blog post we will give you some tips, tricks and best practices (13 in particular) of PHP for you to code better, your professional life can be more enjoyable and can go to developer conferences with high head and without hiding the elephant :P.

Develop with error reporting enabled

One of the great nemesis of web developers in general and PHP errors in particular is the “white screen of death” . Error 500 gives no information and that can be extremely frustrating. To avoid this , without having to modify the php.ini file during the development phase you need only include the following two lines at the beginning of the code:

This lets you see both fatal errors that produce the dreaded white screen as warnings and notices that may be bugs to fix. Then, of course, do not forget to remove the board production.

Prevents SQL injection

Possibly one of the causes of bad reputation of PHP are security holes (Cross-Site Scripting, Cross-Site Request Forgeries) that can be cast as you’re not a little finicky. Of these the best known (and the easiest to prevent) is the SQL Injection : “inserting SQL code invader in order to disrupt the normal operation of the program and ensure that the portion of invasive code to run in the database” with direct consequences.

How do we avoid it ?

There are several ways but the simplest is always escaping any variable (and not only the user inputs) that we will use the database. Like this:

How Does using an outdated driver instead of MySQL MySQLi or PDO? And you are doing consultations here? Tranquility, we do not anticipate events of other tricks and tips that will come afterward.

Retire the MySQL driver

We are not in 2005 nor we still use PHP4 (or at least I hope) so we can now undo the MySQL driver to connect to, where you look, MySQL. We can bet on the driver MySQL (especially in its object – oriented way ) or better yet, fall into the burly arms of PDO.

PDO, which stands for PHP Data Object is a PHP extension that provides an abstraction layer for connecting with different managers databases (because PHP can also work with databases other than MySQL although sometimes not seems). Come on , saving the distances can be compared to Java Hibernate and its use is as simple as we show below:

Just remember to have installed and activated the extent and dust off your PDO notes.
sanitize your database

Embraces cURL

Okay, when you need to retrieve a file from another server, file_get_contents() is powerful, easy to use and gets you out of trouble but you have no control over what happens and flexibility is also poor. Come on, it’s like having death on your computer. So better pull the popular extension cURL (be sure to have it installed and activated before use), more powerful, flexible and with dozens of options. An example of use of cURL can be as simple as the following:

You open a connection to a URL for a certain time and recover the contents therefore in addition to the status of the operation and not forgetting close it . Then the options you have to complicate everything are huge, clear (headers, POST parameters, authentication, different outputs, FTP connections, SSH connections, encryption).

cURL If you fall short you can always pull bookstores like GuzzleHTTP.

Use the _once() function with caution

When calling other files, libraries or classes we can choose the function include() or function require(). The first given a warning not found the file and continues execution. The second gives a fatal error and stops execution. Well, so far unclear, 101 PHP manual.

But we also have the option to use features include_eleven() and require_eleven(), which have the same functionality but prevent the files, classes or loaded libraries can be loaded again causing duplication and undesired states in the code. This is great to get priority but at the cost of decreased performance quite noticeable. Therefore almost better take care yourself, whenever possible, to avoid these duplication by reviewing the code and all calls in it.

Learn to handle ternary operators

Ternary operators are a good alternative to simple IF constructions: on the same line have the conditional and results of TRUE and FALSE . Here ‘s an example:

The variable will have the value of the GET parameter and have not, will the literal John. If you are dyslexic or just something distracted same costs you a bit of this ternary operators but to change your code will be lighter. They can be nested without any problems.

Use a switch instead of stringing Ifs like crazy

We continue our struggle against use If constructions for everything. The switch is slightly faster than If but leaving aside the performance issue, it is horrible to see that obscene amount of if-else if-else chains that make some codes unreadable.Use Switch, that’s what PHP5 as modern language and brings this construction,

a trick for Switch: put before the cases that you think are going to be used, performance will be even better. Example:

Use single quotes rather than double

This may seem a truism but use single quotes (”) instead of double quotes (“”) is twice as fast . So use it whenever you can strip single quotes. The performance of your server will thank you.

Clean URLs quickly with .htaccess

URLs that generates PHP can be a disaster. Solutions for cleaner and more friendly URLs for both the human eye and for SEO there are many but few as fast and simple as “hack” the file .htaccess.

.htaccess Is a hidden file with Apache directives that serves a lot of things (here a fairly extensive and exhaustive tutorial), including performing redirection and clean URLs do not cease to be redirected to after all .

With these two simple lines of code you can prevent horrible URLs as Geeksprogramming.com/index.php?page=contact is accessible through the much friendlier Geeksprogramming.com/contact . If you are adept with regular expressions, you can get real fancy stuff.

Read our detailed blog post on removing url extensions

PHP encrypts your passwords for you

From PHP 5.5 (and 5.3.7 an alternative library) provides native encryption for passwords you want to store in a database as easily as:

And check if the password is correct? Equally simple:

Be Aware of the problems of isset()

Another problem that gives a bad name to PHP is that there are functions that do exactly what its name suggests. This is the case, for example, isset(). Besides when the variable does not exist, isset() returns False if the value of the variable is NULL. Yes, as you read.

Therefore, if NULL can be a valid value of the variable, we have a problem:

Solution? Almost best we pull get defined vars() and array_key_exists ():

Passing variables by reference

Passing variables by reference is not just for Java and other compiled languages, PHP also can pass parameters by reference to a function and so this will update its value without returning anything or declare global variables cumbersome and forgetful. As easy as putting an ampersand (&):

Make use of the resources available

PHP is one of the most popular languages in the world of programming and but still it takes a long time to learn and develop good applications this is good, very good because there are infinite resources and many of them are free and or open-source. For example, Awesome PHP collect hundreds of libraries and resources of proven quality for almost everything: APIs, HTTP connections, database connections SQL and No-SQL data, generate documentation, testing, authentication, routing, continuous integration tools for e-commerce and, of course, whenever you can, use frameworks over core PHP, use it :).

So make the best use of all the available resources and frameworks, CMSs on the web.
You can also hire PHP developers and tutors here at GeeksProgramming to help you with your Programming assignments and projects.


Nice information 🙂

Glad! that you like it.
Thanks for commenting

Great and useful article.. this tips helpful to develop my php knowledge more..

Leave a reply