PHP Coding Convention / Style

PHP being an open source product, lacks a formal and official coding convention. Different frameworks, CMS etc have come up with their own standards which in many cases are similar but at the same time do differ.

The convention mentioned below is mainly inspired from CodeIgniter documentation but does a very good job:

Class names
Class names should always start with a capital letter and multiple words should be separated by an underscore(_) letter. Example:

class Student_records { }

Method and Variable names
All method and variable names should be lowercase and separated by an underscore.

Private Methods and Variable names
Private members should additionally be prefixed with an underscore.

Constants
Constants should always be fully upper case and word should be separated by an underscore.

TRUE, FALSE and NULL
They should always be fully upper case.

Logical Operators
OR should be used instead of || and && should be preferred instead of AND. For negation there should be a space between ! and the word.

Comparison Operators
Always prefer the === and !== over == and != when comparing for boolean.

Whitespaces
For pure PHP files, there should be no whitespace before or after the php opening tags.

Strings
Always prefer single quotes over double quotes.

SQL Queries
SQL keywords should be capitalized like SELECT etc.

For a complete detailed description: http://codeigniter.com/user_guide/general/styleguide.html

Advertisements

Use a Single PHP Session across Multiple Subdomains

By default PHP Sessions are created per domain / sub-domain and are limited within this scope. However there are ways by which a single PHP session will be available in multiple sub-domains.

Our Scenario

Suppose we have a domain named website.com with the following sub-domains:
http://www.website.com
image.website.com
video.website.com etc.

All the sub-domains share the same user accounts. It would be annoying to ask the user to re-enter the login details every time he/she visits a different sub-domains. For example, Google just takes the login credentials once and then we are automatically logged in the accounts.

The Solution

Any two of the following approaches can be used:

  1. Changing the php.ini file
  2. Just by updating the php.ini file, the changes will take effect without doing anything else in the coding. This file can be found in /etc in Redhat/CentOS or Fedora and in /etc/php5/apache2 in Ubuntu and Debian. After opening php.ini file, locate the line with the text session.cookie_domain = and modify it as below:

    session.cookie_domain=.website.com

    The dot (.) is very important to sub-domain access. Save the file reload it using the command:

    For Redhat/CentOS/Fedora (as root)

    service httpd reload

    For Ubuntu/Debian

    sudo service apache2 reload

    This will effect the whole system and that’s not what you would like to see if you are running multiple sites with difference domains on the same server.

  3. Providing the Session Cookie parameters at run-time
  4. Just by calling the session_set_cookie_params method at the top before the session_start. But this approach requires that this should be written on top of every page on every sub-domain. Either of the following will serve the purpose:

    session_set_cookie_params(0, '/', '.website.com');

    or

    ini_set('session.cookie_domain', '.website.com'); 

Try it and it should work!

Enabling Clean URLs for CodeIgniter

CodeIgniter by default will have to first load the index.php page which would then further load the rest of the pages. This can be removed from the URL simply by following these steps:

  1. Create a new file in the CodeIgniter root folder named .htaccess with the following contents.
    <IfModule mod_rewrite.c="">
        RewriteEngine On
        RewriteBase /
        #Removes access to the system folder by users.
        #Additionally this will allow you to create a System.php controller,
        #previously this would not have been possible.
        #'system' can be replaced if you have renamed your system folder.
        RewriteCond %{REQUEST_URI} ^system.*
        RewriteRule ^(.*)$ /index.php?/$1 [L]
    
        #When your application folder isn't in the system folder
        #This snippet prevents user access to the application folder
        #Submitted by: Fabdrol
        #Rename 'application' to your applications folder name.
        RewriteCond %{REQUEST_URI} ^application.*
        RewriteRule ^(.*)$ /index.php?/$1 [L]
    
        #Checks to see if the user is attempting to access a valid file,
        #such as an image or css document, if this isn't true it sends the
        #request to index.php
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php?/$1 [L]
    </IfModule>
    
    <IfModule !mod_rewrite.c="">
        # If we don't have mod_rewrite installed, all 404's
        # can be sent to index.php, and everything works as normal.
        # Submitted by: ElliotHaughin
    
        ErrorDocument 404 /index.php
    </IfModule>
    

    If CodeIgniter is not the webroot and is a subfolder then alter the line RewriteBase / to RewriteBase /[Sub Folder Name]/ where [Sub Folder Name] should be replaced by the actual name of the folder.

    Note: In case the above file doesn’t work, remove the <IfModule> opening and closing tags to test if for some reason Apache wasn’t able to load the module.

    Save the file.

  2. Open the file inside the CodeIgniter folder in the path application/config/config.php and alter the following line
    $config['index_page'] = 'index.php';

    Remove the ‘index.php’ to (empty string) and save.

  3. Enable the mod_rewrite module of Apache using the following command on Ubuntu:
    sudo a2enmod rewrite

    The Apache needs to be restarted before changes can take affect.

  4. Make sure the required settings are made in the sites file. In Ubuntu this file can be found at /etc/apache/sites-available/default and make the following changes:
    <Directory>
           ...
           Options FollowSymLinks
           AllowOverride FileInfo
           ...
    </Directory>
  5. Restart Apache using the following command:
    sudo service apache2 restart

Now test the website by using the URL without the index.php word and it should work fine.

Configure PHP to Send Mails using External SMTP Server

Sending e-mails from website is a very task and almost all proper web applications have a need to send e-mails. This feature is available in PHP but by default PHP is configured to use the local SMTP server. However, this is not the only option you have. PHP can be configured to use an external SMTP server like Gmail for this purpose.

For that these additional packages will be required:

sudo apt-get install php-pear php-mail php-net-socket php-net-smtp php-mail-mime

Once the required packages have been installed, you can start sending the mails. Here is a sample PHP script I have created for the demo purpose:

<?php
   include("Mail.php"); // Actual path /usr/share/php/Mail.php
   include("Mail/mime.php"); // Actual path /usr/share/Mail/mime.php

   /* mail setup recipients, subject etc */
   $recipients = "destination@gmail.com";
   $headers["From"] = "youremail@gmail.com";
   $headers["To"] = "destination@gmail.com";
   $headers["Subject"] = "Mail Test (PEAR) 3";
   // Use this for Unicode messages
   $headers["Content-type"] = 'text/html; charset="UTF-8"';
  
   $mailmsg = "<div style='color:blue;'>Sample New Message<br />احمد</div>";
      
   $mime= new Mail_mime("\n");
   $mime->setHTMLBody($mailmsg);
      
   $mailmsg = $mime->get();
      
   $headers = $mime->headers($headers);
     
   /* SMTP server name, port, user/passwd */
   $smtpinfo["host"] = "smtp.gmail.com";
   $smtpinfo["port"] = "25";
   $smtpinfo["auth"] = true;
   $smtpinfo["username"] = "youremail@gmail.com";
   $smtpinfo["password"] = "";
   
   /* Create the mail object using the Mail::factory method */
   $mail_object =& Mail::factory("smtp", $smtpinfo);
   /* Ok send mail */
   $mail_object->send($recipients, $headers, $mailmsg);
?>

Load the page in the browser and you will be happy to see that it works! 🙂

Install Apache, PHP and MySQL on Ubuntu

Installing these packages on Ubuntu is very simple. Just execute the following commands and you will be done with everything.

Install Apache

sudo apt-get install apache2

Install PHP

sudo apt-get install php5 libapache2-mod-php5

Install MySQL (with Apache & PHP support)

sudo apt-get install mysql-server libapache2-mod-auth-mysql php5-mysql

Restart Apache

sudo /etc/init.d/apache2 restart

Install MySQL Query Browser

sudo apt-get install mysql-query-browser

Update for MySQL

MySQL has officially declared EOL (End of Life) for Query Browser. You can check it onhttp://dev.mysql.com/doc/query-browser/en/

MySQL Workbench is its replacement and its now available in Ubuntu 12.04 repositories:

sudo apt-get install mysql-workbench

All features are supported by Workbench.