PHP Coding Guidelines & Best Practices

PHP is the most widely-used language for programming on the web. Here are thirty best practices for beginners wanting to gain a firmer grasp of the fundamentals.Coding Standards are an important factor for achieving a high code quality. A common visual style, naming conventions and other technical settings allow us to produce a homogenous code which is easy to read and maintain. However, not all important factors can be covered by rules and coding standards.

 

Read PHP Manual : The PHP manual is incredibly thorough and has truly helpful comments following each article. Before asking questions or trying to figure out an issue on your own, save some time and just head straight to the manual.

Always use Meaningful, Consistent Name Standard : camelCase and underscores are two popular naming standard. In camelCase, the first letter of each word is capitalized, expect for the first word while underscores, adds underscore between words, like mysql_real_escape_string().

Turn on Error Reporting : Error reporting in PHP is very helpful. You’ll find bugs in your code that you might not have spotted earlier, as not all bugs keep the application from working. There are different levels of strictness in the reporting that you can use, but E_ALL will show you the most errors, critical and warnings alike.

Once you’ve gotten your application ready for production, you’ll want to turn off error reporting, or your visitors will see strange errors that they don’t understand.

Try an IDE : IDE’s (Integrated Development Environments) are helpful tools for any developer. While they’re not for everyone, an IDE definitely has its place. IDE’s provide tools like

syntax highlighting
code completion
error warnings
refactoring (reworking).

Use the DRY approach : ‘Do not Repeat Yourself’ abbreviated for DRY, which is one of the best and useful programming concept and should be used in any programming language like PHP, Java, and C#. Using the DRY approach ensure that no redundant code is there.
A piece of code, violating DRY refers as the WET solution. WET stands for ‘We Enjoy Typing’ or ‘Write Everything Twic’. Check out below given code:
DRY and WET approaches

$mysql = mysql_connect ( ‘localhost’, ‘mysqladmin_uid’, ‘mysqladmin_pwd’ );
mysql_select_db( ‘DB_NAME’ ) or die( “Sorry !! No database selected!”);

The above given code is based on the WET approach as the relevant parameters are hardcoded. Below given is the DRY approach and code can be updated to.

$db_host = ‘ localhost ‘; $db_user = ‘ mysqladmin_uid ‘; $db_password = ‘ mysqladmin_pwd ‘; $db_database = ‘ DB_NAME ‘; $mysql = mysql_connect($db_host, $db_user, $db_password); mysql_select_db($db_database);

 

Avoid putting phpinfo() in your web root : Phpinfo is a useful function. Users just have to create a simple PHP file with <?php phpinfo(); ?> and have to paste it to the server as you know everything about your server environment.But, there are many programmers would place the file contain phpinfo() in the webroot, which is consider very insecure practice. It results into it could potentially speel doom from the server.Ensure to place phpinfo() in the secure sport and it should be delete once you are done.

Try ORM : Using the nifty object relational mapping (ORM) is an excellent ideas to write object-oriented PHP. With object relational mapping, one can easily convert their data between relational databases and object-oriented programming languages. ORM allows working with databases like you are working with classes and objects in PHP. Developers can find loads of ORM libraries for PHP such as Propel and ORm is created into PHP frameworks like CakePHP.

Ensure to Comment: It is advisable to leave comment inside your source code as it is essential when you are involving 5-10 programmers in your project. Comments help to the people, who are maintaining a project from a long time ago.
It is recommended to get educated with some PHP Documentation packages like phpDocumentor to maintain a high quality of comment standard and also take extra time to do it.

Try a PHP Framework : Those developers, who have learned the fundamentals of PHP, can try some PHP frameworks. Different types of PHP frameworks are available that mostly designed on the basis of Model-View Controller (MVC) software architecture.Moreover, one can learn many interesting and latest things by using a PHP framework. Those who want to create some awesome PHP applications with ease can use framework like Symfony, CakePHP, CodeIgniter, and Zend.

“Tier” your Code : Tiering applications means separating the different components of the code into various parts. It allows changing code easily in future. If you want to know how to how to tier your PHP applications for easier maintenance then read this article.

Always Use

<?php ?> 

<?

echo “Hello world”;
?>
<?=”Hello world”; ?>

<% echo “Hello world”; %>

While these do save a few characters, all of these methods are depreciated and unofficial. Stick with the standard <?php ?> as it will be guaranteed to be supported in all future versions.

Install MAMP/WAMP : MySQL is one of the most popular types of database that can be used along with PHP. Installing MAMP (Mac) or WAMP (Windows) is possible, if you want to set up a local environment to develop and test PHP applications on your computer.Developers can find the installation process of MySQL on their computer is tedious one and both of such software packages are drop-in installs of MySQL.

Use Objects (or OOP) : Objects are used by Object-oriented programming that represents parts of the application. Along with breaking the code into separate and logical sections, OOP helps to minimizes code repetition and make it much easier to change for future correction. To know more about write-up on object-oriented programming with PHP.

Know the Difference Between Single and Double Quotes : It is more efficient to use single quotes in strings as the parser doesn’t have to sift through the code to look for escaped characters and other things that double quotes allow. Always try to use single quotes whenever possible.

Never, Ever Trust Your Users : If your application has places for user input, you should always assume that they’re going to try to input naughty code. (We’re not implying that your users are bad people. It’s just a good mindset.) A great way to keep your site hacker-free is to always initialize your variables to safeguard your site from XSS attacks. PHP.net has an example of a properly secured form with initialized variables:

<?php
if (correct_user($_POST[‘user’], $_POST[‘password’]) {
$login = true;
}

if ($login) {
forward_to_secure_environment();
}
?>

Always Store Passwords with Encryption : Many PHP beginners often plunk sensitive data like passwords into the database without applying any encryption. Consider using MD5 to encrypt passwords before you put them into the database.

echo md5(‘yourpassword’); 

use Output Buffering : Output buffering is a simple way to greatly improve the performance and speed of your PHP script. Without output buffering, your script will show the HTML on the page as it’s processed – in pieces. Adding output buffering allows the PHP to store the HTML as a variable and send it to the browser in one chunk.

To enable output buffering, simply add ob_start() like so at the top of the file.

<!DOCTYPE html>
<?php ob_start(‘ob_gzhandler’); ?>
<html lang=”en”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″>
<title>untitled</title>
</head>
<body>

</body>
</html>
<?php ob_end_flush(); ?>

Protect your Script From SQL Injection : If you don’t escape your characters used in SQL strings, your code is vulnerable to SQL injections. You can avoid this by either using the mysql_real_escape_string, or by using prepared statements.

Here’s an example of mysql_real_escape_string in action:

$username = mysql_real_escape_string( $GET[‘username’] );

Prepared Statement: 

$id = $_GET['id'];
$statement = $connection->prepare( "SELECT * FROM tbl_members WHERE id = ?" );
$statement->bind_param( "i", $id );
$statement->execute();
Upgrade to the Latest Version of PHP : While it seems like a common sense thing, many people don’t upgrade PHP as often as they should. There are lots of performance increases between PHP 4 and PHP 5. Check your server to make sure you’re up to date.

 

 

 

How to use Zend Framework 2 Tool

ZFTool is an utility module for maintaining modular Zend Framework 2 applications. It runs from the command line and can be installed as ZF2 module or as PHAR. This tool gives you the ability to:
– create a ZF2 project, installing a skeleton application
– create a new module inside an existing ZF2 application
– get the list of all the modules installed inside an application
– get the configuration file of a ZF2 application
– install the ZF2 library choosing a specific version

Features

Class-map generator
Listing of loaded modules
Create a new project (install the ZF2 skeleton application)
Create a new module
Create a new controller
Create a new action in a controller
Application diagnostics

What is PHAR ?

The phar extension provides a way to put entire PHP applications into a single file called a “phar” (PHP Archive) for easy distribution and installation. In addition to providing this service, the phar extension also provides a file-format abstraction method for creating and manipulating tar and zip files through the PharData class, much as PDO provides a unified interface for accessing different databases. Unlike PDO, which cannot convert between different databases, Phar also can convert between tar, zip and phar file formats with a single line of code. see Phar::convertToExecutable() for one example.

 

You can simply follow this link and follow all the steps according to this (ZFTOOL).

Or

You can install it through from the root of your project. issue the following command

php composer.phar require zendframework/zftool:dev-master

After sucessfully installation you can go to your root project.

your zftool is installed in your vendor->zendframework->zftool . Then go to zftool folder and execute php zf.php or you can copy zf.php in your root directory the run cmd

php zftool.phar modules   or  php zf.php modules

create a new module using cmd : php zftool.phar create module Blog ./      or    php  zf.php create module Blog ./

Find some refrences:

Zend Framework Tool (ZFTool)

Stack Overflow How to install Zend Framework 2 Tool with composer

 

 

 

Use regular expressions in MySQL SELECT statements !!

A very cool and powerful capability in MySQL and other databases is the ability to incorporate regular expression syntax when selecting data. The regular expresion support in MySQL is extensive. This recipe reviews regular expression use in MySQL and lists the supported regular expression metacharacters.

The basic syntax to use regular expressions in a MySQL query is:

SELECT something FROM table WHERE column REGEXP 'regexp';

For example, to select all columns from the table events where the values in the column id end with 5587, use:

SELECT * FROM events WHERE id REGEXP '5587$';

A more elaborate example selects all columns of the table reviews where the values in the column description contain the word excellent:

SELECT * FROM reviews WHERE description REGEXP '[[:<:]]excellent[[:>:]]';

MySQL allows the following regular expression metacharacters:

. match any character ? match zero or one
* match zero or more
+ match one or more
{n} match n times
{m,n} match m through n times
{n,} match n or more times
^ beginning of line
$ end of line
[[:<:]] match beginning of words
[[:>:]] match ending of words
[:class:] match a character class
i.e., [:alpha:] for letters
[:space:] for whitespace
[:punct:] for punctuation
[:upper:] for upper case letters
[abc] match one of enclosed chars
[^xyz] match any char not enclosed
| separates alternatives

 

MySQL interprets a backslash (\) character as an escape character. To use a backslash in a regular expression, you must escape it with another backslash (\\).

 

 

 

Mysql Query IF Case in Query

attendanceHow to fetch the attendance of a student for particular time slot in a single row. Like this is the table in my database where slot

1 = > Slot1

2 =>Slot2

3=>Slot3

4=>Slot4

I want a student data in one row like:

student id | slot1 | Slot2 |Slot3 | Slot 4 (How to acheive that)

SELECT `subject_id`, MAX(IF(`time_slot` = 1, `attendance`, NULL)) slot1, MAX(IF(`time_slot` = 2, `attendance`, NULL)) slot2, MAX(IF(`time_slot` = 3, `attendance`, NULL)) slot3, MAX(IF(`time_slot` = 4, `attendance`, NULL)) slot4 FROM pro_attendance GROUP BY `subject_id`

Result like :

student-attendance-slot

Question : How to join two records and find whose value is null on next table

SELECT employee.title,department.DEPT_NAME FROM employee LEFT OUTER JOIN departmentON employee.id = department.DEPT_ID WHERE department.id IS null

 

 

Adding a Local Git Repository to GitHub

So what do you do if you have a local Git repository and you want to push it up to GitHub to share it with the greater public, or use it as a collaboration point with a number of other developers without spending any money? Well that’s where GitHub comes in, it’s a “web-based hosting service for software development projects that use the Git revision control system.” – Wikipedia. GitHub sports a number of features but we’re only going to be focusing on it’s ability to house a public repository in this post.

GitHub-Logo

Assumptions
Several quick assumptions to tick off.

You’re using a Windows machine – sorry this is targeted at Windows users only.
You have Git installed locally as well as Git GUI and Git Bash (available for download from Git for Windows).
You have a local Git repository.

  • First Thing you have to do : Create an account over github
  • Adding the Project to GitHub :

url

 

Once you’ve done this you’ll have a fixed repository address, i.e. https://github.com/username/MvcApplication. This is where you’ll be able to view and manage your local repository once you’ve pushed it up to GitHub. The following page will appear after you’ve created the repository and good old GitHub will even tell you which Git commands you’ll need to execute in Git Bash – see below under the “Push an existing repository from the command line” heading:

pushanexisting

If we were using a GUI application we could get through the next few steps with a series of button clicks but we’re going to take those two Git commands from the screenshot above and run them through Git Bash instead.

   git remote add origin https://github.com/username/MvcApplication.git
    git push -u origin master

So open up Git Bash and navigate to the root folder of your Visual Studio solution. TIP: An easy way to do this is to use Windows Explorer to find the solution’s root folder then right-click it and select the “Git Bash Here” option. This will open up Git Bash right on top of your folder.

If we were using a GUI application we could get through the next few steps with a series of button clicks but we’re going to take those two Git commands from the screenshot above and run them through Git Bash instead.

 

windowsexplorer1

You can read full post here : http://berniecook.wordpress.com/2013/01/13/adding-a-local-git-repository-to-github-step-by-step-guide/

 

How to convert rows into coloumn of array in PHP.

$arr = array
 (array(1,2,3,4),array(5,6,7,8),array(9,10,11,12),array(13,14,15,16));


// Before Conversion

echo $arr[0][0].”: “.$arr[0][1].”, “.$arr[0][2].”, “.$arr[0][3].”.
“;
echo $arr[1][0].”: “.$arr[1][1].”, “.$arr[1][2].”, “.$arr[1][3].”.
“;
echo $arr[2][0].”: “.$arr[2][1].”, “.$arr[2][2].”, “.$arr[2][3].”.
“;
echo $arr[3][0].”: “.$arr[3][1].”, “.$arr[3][2].”, “.$arr[3][3].”.
“;




$rows = count($arr);
$cols = count($arr[0]);
$ridx = 0;
$cidx = 0;

$out = array();
foreach($arr as $rowidx => $row){
    //print_r($row);die;
    foreach($row as $colidx => $val){
        $out[$ridx][$cidx] = $val;
        $ridx++;
        if($ridx >= $rows){
            $cidx++;
            $ridx = 0;
        }
    }
}


// After Conversion

echo $out[0][0].”: “.$out[0][1].”, “.$out[0][2].”, “.$out[0][3].”.
“;
echo $out[1][0].”: “.$out[1][1].”, “.$out[1][2].”, “.$out[1][3].”.
“;
echo $out[2][0].”: “.$out[2][1].”, “.$out[2][2].”, “.$out[2][3].”.
“;
echo $out[3][0].”: “.$out[3][1].”, “.$out[3][2].”, “.$out[3][3].”.
“;

How to sort an array in PHP

$array=array(‘2′,’4′,’8′,’5′,’1′,’7′,’6′,’9′,’10’,’3′);

function arraySortMuti($array)
{    //print_r($array);die;
    for($j = 0; $j < count($array); $j ++) {
    for($i = 0; $i < count($array)-1; $i ++){

        if($array[$i] > $array[$i+1]) {
            $temp = $array[$i+1];
            $array[$i+1]=$array[$i];
            $array[$i]=$temp;
        }      
    }
    }
    echo “
“;echo “Sorted Array is: “;echo “
“;print_r($array);   
}

echo arraySortMuti($array);

How to install PEAR and PHPUnit on windows.

Problem for me start from beginning when I looked for go-pear.bat file on my c:\\php directory to install pear.

I was unable to locate go-pear.bat file in my php installation directory.

On http://pear.php.net/manual/en/installation.getting.php it is clearly written to use this file to install pear itself. I googled a lot and found some of the useful instruction for pear installation, but unfortunately they either failed or too old to handle the new environment. After a day of long search I finally manage to install pear and PHPunit on my system.  If you also unable to find go-pear.php on your local php installation directory then you can take the following approach.

Here are the steps i have taken to solve this problem, this might also help you.

– See more at: http://truelogic.org/wordpress/2012/07/25/installing-latest-pear-and-phpunit-on-windows-7/#sthash.cwKKoIFn.dpuf

 On http://pear.php.net/manual/en/installation.getting.php it is clearly written to use this file to install pear itself.

I googled a lot and found some of the useful instruction for pear installation, but unfortunately they either failed or too old to handle the new environment.

After a day of long search I finally manage to install pear and PHPunit on my system. 

If you also unable to find go-pear.php on your local php installation directory then you can take the following approach.

Here are the steps i have taken to solve this problem, this might also help you.

1.    In your php.ini file find the following line.
;phar.require_hash = On

2.    Remove the semi-colon from beginning of this line and change “On” to “Off” (without double quotes).

3.    Restart your apache server.

4.    Input this url in your browser http://pear.php.net/go-pear.phar, you will be prompted to download go-pear.phar file.

5.    Download go-pear.phar file and move it to the php installation directory (c:\\php in my case).

6.    Open cmd navigate to c:\\php and run the following command
php go-pear.phar

7.    Enter ‘local’ to the question asked. Follow the instruction.

8.    Restart apache.

PEAR has been installed successfully (no need to configure your environment variable). To check it, type pear on your cmd you will be able to see the help menu for the pear.

Now let’s install PHPUnit (I have installed PHPUnit 3.6.11). While installing PHPUnit when I run the below command (in point 9) I got the error “PEAR_Config::writeConfigFile fopen(‘C:\Windows\pear.ini’,’w’)indows\pear.ini): failed to open stream: Permission denied)”.

I have to re-open the cmd as administrator, so let’s continue to finish our installation by installing PHPUnit

9.    Open cmd (remember to open it as Administrator ) navigate to the php installation folder and run the following commands.
pear config-set auto_discover 1
pear install pear.phpunit.de/PHPUnit

10.    Wait while it install and follow the instruction.

11.    Restart your apache server.

That’s all you need to run a successful installation on windows 7.

 Though I have not tested but this process may also work in windows XP.

Problem for me start from beginning when I looked for go-pear.bat file on my c:\\php directory to install pear. I was unable to locate go-pear.bat file in my php installation directory.

Problem for me start from beginning when I looked for go-pear.bat file on my c:\\php directory to install pear. I was unable to locate go-pear.bat file in my php installation directory.

How to make OOPS based functions file in php.

functions.php 

define(‘DB_SERVER’, ‘localhost’);
define(‘DB_USERNAME’, ‘root’);
define(‘DB_PASSWORD’, ”);
define(‘DB_DATABASE’, ‘project’);

class Common
    {
        public $mysqli;
        public function __construct()
        {
            $mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
            $this->mysqli = $mysqli;
        }
      
        public function checkLogin($username , $password)
        {  
          
            $query = “select id from login where username=’$username’ and password=’$password'”;
            $result = $this->mysqli->query($query);
            $records = $result->fetch_array();//print_r($query);die;
            if($result->num_rows != ”)
            {
                $_SESSION[‘login’] = true;
                //echo $records[‘username’];die;
                $_SESSION[‘id’] = $records[‘username’];

                return true;
            }else
            {
                return false;
            }
              
        }
      
      
        public function getSession()
        {
            return $_SESSION[‘login’];
              
        }
      
        public function logout()
        {
            $_SESSION[‘login’] = false;
          
            session_destroy();  
            header(‘Location:index.php’);
        }
          
      
        public function fetching($table)
        {
        $query = “SELECT * FROM “.$table.” where id>0″;
        $result = $this->mysqli->query($query);
       
       
        $total = array();
        while($row = $result->fetch_assoc()){
              
             $total[] = $row;
        }
        return $total;
      
        }
      
        public function completeQuery($cmplet_query)
        {
        $query = $cmplet_query;
        $result = $this->mysqli->query($query);
        $records = $result->fetch_assoc();
        $total = array();
        while($row = $result->fetch_assoc()){  
             $total[] = $row;
        }
        return $total;
      
        }
      
        public function InsertQuery($set_table_name,$data)
        {   
            if(count($data)>0){
                $string =’insert into ‘.$set_table_name.’ set ‘;
                foreach($data as $key=>$value){
                    $value = ‘”‘.$value.'”‘;
                    $value = str_replace(“‘”, “””, $value);
                    $string .= $key.’=’.$value.’,’;
                }
            }
          
            $trimm =  rtrim($string,’,’);
            //print_r($trimm);die;
            $result = $this->mysqli->query($trimm);
        }
      
        public function updateQuery($set_table_name,$data,$whr)
        {
                if(count($data)>0){
                $string =’update ‘.$set_table_name.’ set ‘;
                foreach($data as $key=>$value){
                    $value = ‘”‘.$value.'”‘;
                    $value = str_replace(“‘”, “””, $value);
                    $string .= $key.’=’.$value.’,’;
                }
            }
          
            $trimm =  rtrim($string,’,’).’ where ‘.$whr;
            $result = $this->mysqli->query($trimm);
        }
      
      
        public function deleteQuery($set_table_name,$whr)
        {
          
            $query = “delete from “.$set_table_name.” where id =”.$whr;
          
            $result = $this->mysqli->query($query);
          
        }

      
    }

Now make a page where input fields are username and password and form action is like logincheck.php

In logincheck.php

session_start();
include_once ‘functions.php’;
$user = new Common();

 
if ($_SERVER[“REQUEST_METHOD”] == “POST”)
{

$login = $user->checkLogin($_POST[‘username’], $_POST[‘password’]);

if ($login)
{
 header(“location:home.php”); // if session is not created redirect to index page
}else
{
header(“location:index.php”); // if session is not created redirect to index page
}
}

How to submit a form using functions.php 
simply pass a array in insert query .. 

include_once ‘functions.php’;
$user = new Common();

if(isset($_REQUEST[‘submit’]))
    {
    $data[‘category’] = $_POST[‘category’];
    $data[‘description’] = $_POST[‘description’];
    $data[‘status’] = $_POST[‘status’];
    $data[‘posted’] = date(‘Y-m-d H:i:s’);
   
    $user->InsertQuery(‘category’,$data);
    header(“location: category.php”);
       
    }