Followings are some helpful codes in php:
1] Develop with error reporting enabled
- error_reporting ( E_ALL ) ;
- 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
- 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 ( ) ;
- }
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
- RewriteEngine On
- RewriteRule ^ ( [ a – zA – Z0 – 9 ] + ) $ index . Php? Page = $ 1
8] Know all the Problems of isset()
- $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
9] Use a switch instead of stringing If Statements
- 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 ;
- }
10] Take up 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 ) ;
11] Password Encryption
$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
- }
