PHP Tips and Tricks

Followings are some helpful codes in php:

1] Develop with error reporting enabled

  1. error_reporting ( E_ALL ) ;
  2. ini_set ( ‘display_errors’ , 1 ) ;

2] Prevents SQL injection

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

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

4] Learn to handle ternary operators

$age = ( !empty ( $ _ GET [ ‘age ] ) ? $ _ GET [ ‘age’ ] : 58 ) ;

5] Retire the MySQL driver

  1. try {
  2. $conn = new PDO ( “mysql: host = localhost; dbname = database ‘ , $ user , $ pass);
  3. $conn -> setAttribute ( PDO :: ATTR_ERRMODE , PDO :: ERRMODE_EXCEPTION) ;
  4. } Catch ( PDOException $e ) {
  5. Echo “ERROR:” . $e -> getMessage ( ) ;
  6. }

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

7] Clean URLs quickly with .htaccess

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

8] Know all the Problems of isset()

  1. $foo = null ;
  2. if ( isset( $ foo ) ) // returns false
  3. And the solution is: Use get_defined_vars( );
  4. $foo = NULL ;
  5. $vars = get_defined_vars( );
  6. if ( array_key_exists ( ‘foo’ , $ vars ) ) // returns True

9] Use a switch instead of stringing If Statements

  1. switch ($color ) {
  2. case ‘white’ :
  3. echo “The color is White” ;
  4. break ;
  5. case ‘blue’ :
  6. echo “The color is Blue” ;
  7. break ;
  8. case ‘green’ :
  9. echo “The color is Green” ;
  10. break ;
  11. case ‘black’ :
  12. echo “Color is black” ;
  13. break ;
  14. }

10] Take up cURL

  1. $c = curl_init ( ) ;
  2. curl_setopt ( $c , CURLOPT_URL , $URL ) ;
  3. curl_setopt ( $c , CURLOPT_TIMEOUT , 15 ) ;
  4. curl_setopt ( $c , CURLOPT_RETURNTRANSFER , true ) ;
  5. $content = curl_exec ( $c ) ;
  6. $status = curl_getinfo ( $c , CURLINFO_HTTP_CODE ) ;
  7. curl_close ( $c ) ;

11] Password Encryption

$enc_pass = password_hash ( $submitted_pass , PASSWORD_DEFAULT ) ;

To check if password is correct or not:

  1. if ( password_verify ( $submitted_pass , $stored_pass ) )
  2. {
  3. // User successfully authenticated
  4. }

 

Leave a comment