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:

error_reporting ( E_ALL ) ;
ini_set ( 'display_errors' , 1 ) ;

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:

$query_result = mysql_query ( "SELECT * FROM WHERE Ex_table ex_field = \" " . mysql_real_escape_string( $ ex_field ) . " \ " " ) ;

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:

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

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:

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

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:

$name = ( !empty ( $ _ GET [ 'name' ] ) ? $ _ GET [ 'name' ] : 'John' ) ;

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:

switch ($color ) {
  case 'blue' :
   echo "The color is blue" ;
    break ;
  case 'red' :
   echo "The color is red" ;
   break ;
  case 'turquoise' :
   echo "The color is turquoise" ;
   break ;
 case 'black' :
   echo "Color is black" ;
   break ;
}

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 .

RewriteEngine On
RewriteRule ^ ( [ a - zA - Z0 - 9 ] + ) $ index . Php? Page = $ 1

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:

$enc_pass = password_hash ( $submitted_pass , PASSWORD_DEFAULT ) ;

And check if the password is correct? Equally simple:

if ( password_verify ( $submitted_pass , $stored_pass ) )
{ 
// User successfully authenticated
}

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:

$foo = null ;
if ( isset( $ foo ) ) // returns false

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

$foo = NULL ;
$vars = get_defined_vars( );
if ( array_key_exists ( 'foo' , $ vars ) ) // returns True

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 (&):

function square ( & $number ) {
$number = $number * $number ;
}
$number = 2 ;
square ( $number ) ;
echo $number ; // returns 4

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.

3 thoughts on “13 PHP tips and tricks that can make Developers life easier”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top