Pages

Monday, December 16, 2013

PHP-Arrays-Get the occurance of each value in numeric array

Like as always we have a problem we have some prerequisites we will have a function and we will draw some results


Problem and Prerequisites :

We have an array let us suppose array(1,2,1,3,4,5,4,6,3,2,1,2,8,9,3,4,5,3,2,4,6,2) and we want to create a function that checks for number of times value repeats in the array.

So we need and output like

1 repeats 3 times
2 repeats 5 times etc.

Function and Solution :

 <?php
 function get_modes($numarray)  
 {  
   if(!(is_array($numarray)))  
     throw new Exception ('Parameter Not an array');  
   $revarray=array();  
   foreach($numarray as $key=>$value)  
   {  
     if(array_key_exists($value,$revarray))  
     {  
       $revarray[$value]++;  
     }  
     else   
     {  
       $revarray[$value]=1;  
     }  
   }  
   return $revarray;  
 }  
 $myarray=array(1,2,1,3,4,5,4,6,3,2,1,2,8,9,3,4,5,3,2,4,6,2);  
 $navarray=get_modes($myarray);  
 foreach($navarray as $key=>$value)  
 {  
   echo $key." repeats ".$value." times<br/>";  
 }  
 ?>  

Output:

1 repeats 3 times
2 repeats 5 times
3 repeats 4 times
4 repeats 4 times
5 repeats 2 times
6 repeats 2 times
8 repeats 1 times
9 repeats 1 times

Sunday, December 15, 2013

PHP-Image functions

//size of image
getimagesize()
http://www.php.net/getimagesize

//image width
imagesx()
http://www.php.net/manual/en/function.imagesx.php


//image height
imagesy()
http://www.php.net/manual/en/function.imagesy.php

//determine type of an image
exif_imagetype()
http://www.php.net/manual/en/function.exif-imagetype.php

Encrypt data using PHP

Encryption Decryption
AES_ENCRYPT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() N/A
ENCRYPT() N/A
MD5() N/A
OLD_PASSWORD() N/A
PASSWORD() N/A
SHA() N/A
SHA1() N/A
N/A UNCOMPRESSED_LENGTH()

Saturday, December 14, 2013

HTML->Difference between GET and POST methods

POST Method
In Post method we can send unlimited data(This limit is defined by server for example "post_max_size=20M" in Apache)

Data is not shown in URL so it is good for sensitive data

GET Method

In GET method this depends on browser for example IE8 can take about 2048 bytes of data i.e about 2KB

Data is shown in URL so not appropriate for sensitive data

PHP-Database connectivity function's

One of the main aspects of PHP is database connectivity.Though it supports variety of databases we will talk about mysql in particular here.

All the functions which are of concern are present in file mysqli.php which contains class "mysqli_sql_exception" which in turn extends "RuntimeException"

The very first functions that we encounter while working with databases with PHP are the "connect functions".

Let's see what we get when we execute these functions in order

As a software development flows we will have some prerequisites,a function which will process them and then we will have some results.

Prerequiaites :

A dbhost : "localhost"
A username : "uroot"
A password : "proot"
Also

That's it and all we need is a php setup LAMP/WAMP/MAMP/XAMPP package

Our first function :
 $con= mysqli_connect('localhost1','puroot','pproot','test1');  
Reference :
/**
 * (PHP 5)<br/>
 * Alias of <b>mysqli::__construct</b>
 * @link http://php.net/manual/en/function.mysqli-connect.php
 * @param $host [optional]
 * @param $user [optional]
 * @param $password [optional]
 * @param $database [optional]
 * @param $port [optional]
 * @param $socket [optional]
 */
function mysqli_connect ($host, $user, $password, $database, $port, $socket) {}

This function tries to connect to the database with given credentials. We have created a negative mutant to test the same as you can see from what credentials we have passed above.


Our Second function and third function :
 if (mysqli_connect_errno())  
 {  
   echo "Failed to connect to MySQL: " . mysqli_connect_error();  
 }
Reference:
/**
 * (PHP 5)<br/>
 * Returns the error code from last connect call
 * @link http://php.net/manual/en/mysqli.connect-errno.php
 * @return int An error code value for the last call to <b>mysqli_connect</b>, if it failed.
 * zero means no error occurred.
 */
function mysqli_connect_errno () {}

/**
 * (PHP 5)<br/>
 * Returns a string description of the last connect error
 * @link http://php.net/manual/en/mysqli.connect-error.php
 * @return string A string that describes the error. <b>NULL</b> is returned if no error occurred.
 */
function mysqli_connect_error () {}

Now when we execute the above pieces of code we get an error

Failed to connect to MySQL: Unknown MySQL server host 'localhost1' (2)Error creating database:

When we set host right we get following error
Failed to connect to MySQL: Access denied for user 'puroot'@'localhost' (using password: YES)Error creating database: 

Similarly when we set username and password right we get
Failed to connect to MySQL: Unknown database 'test1'

Now that we are done with the set of connection functions we will try to create a database on success.Now since we have already created a database "test" we will test with a negative mutant.

Our fourth and fifth function
 $sql="CREATE DATABASE test";  
 if (mysqli_query($con,$sql))  
 {  
   echo "Database test created successfully";  
 }  
 else  
 {  
   echo "Error creating database: " . mysqli_error($con);  
 }  
Reference:

 /**  
  * (PHP 5)<br/>  
  * Performs a query on the database  
  * @link http://php.net/manual/en/mysqli.query.php  
  * @param mysqli $link  
  * @param string $query <p>  
  * The query string.  
  * </p>  
  * <p>  
  * Data inside the query should be properly escaped.  
  * </p>  
  * @param int $resultmode [optional] <p>  
  * Either the constant <b>MYSQLI_USE_RESULT</b> or  
  * <b>MYSQLI_STORE_RESULT</b> depending on the desired  
  * behavior. By default, <b>MYSQLI_STORE_RESULT</b> is used.  
  * </p>  
  * <p>  
  * If you use <b>MYSQLI_USE_RESULT</b> all subsequent calls  
  * will return error Commands out of sync unless you  
  * call <b>mysqli_free_result</b>  
  * </p>  
  * <p>  
  * With <b>MYSQLI_ASYNC</b> (available with mysqlnd), it is  
  * possible to perform query asynchronously.  
  * <b>mysqli_poll</b> is then used to get results from such  
  * queries.  
  * </p>  
  * @return mixed <b>FALSE</b> on failure. For successful SELECT, SHOW, DESCRIBE or  
  * EXPLAIN queries <b>mysqli_query</b> will return  
  * a <b>mysqli_result</b> object. For other successful queries <b>mysqli_query</b> will  
  * return <b>TRUE</b>.  
  */  
 function mysqli_query (mysqli $link, $query, $resultmode = 'MYSQLI_STORE_RESULT') {}  
 /**  
  * (PHP 5)<br/>  
  * Returns a string description of the last error  
  * @link http://php.net/manual/en/mysqli.error.php  
  * @param mysqli $link  
  * @return string A string that describes the error. An empty string if no error occurred.  
  */  
 function mysqli_error (mysqli $link) {}  


Error creating database: Can't create database 'test'; database exists

because we have already created one

similarly mysql_query() is used for create table,insert

Our sixth function

 $result= mysqli_query($con,"SELECT * FROM Persons");  
 while($row= mysqli_fetch_array($result))  
 {  
   echo "<pre>";  
   print_r($row);  
   echo "</pre>";  
 }  
 $result= mysqli_query($con,"SELECT * FROM Persons");  
 while($row= mysqli_fetch_row($result))  
 {  
   echo "<pre>";  
   print_r($row);  
   echo "</pre>";  
 }  
 $result= mysqli_query($con,"SELECT * FROM Persons");  
 while($row= mysqli_fetch_object($result))  
 {  
   echo "<pre>";  
   print_r($row);  
   echo "</pre>";  
 }  
 $result= mysqli_query($con,"SELECT * FROM Persons");  
 while($row= mysqli_fetch_assoc($result))  
 {  
   echo "<pre>";  
   print_r($row);  
   echo "</pre>";  
 }  
References for ways we can fetch row:
 /**  
  * (PHP 5)<br/>  
  * Fetch a result row as an associative, a numeric array, or both  
  * @link http://php.net/manual/en/mysqli-result.fetch-array.php  
  * @param mysqli_result $result  
  * @param int $resulttype [optional] <p>  
  * This optional parameter is a constant indicating what type of array  
  * should be produced from the current row data. The possible values for  
  * this parameter are the constants <b>MYSQLI_ASSOC</b>,  
  * <b>MYSQLI_NUM</b>, or <b>MYSQLI_BOTH</b>.  
  * </p>  
  * <p>  
  * By using the <b>MYSQLI_ASSOC</b> constant this function  
  * will behave identically to the <b>mysqli_fetch_assoc</b>,  
  * while <b>MYSQLI_NUM</b> will behave identically to the  
  * <b>mysqli_fetch_row</b> function. The final option  
  * <b>MYSQLI_BOTH</b> will create a single array with the  
  * attributes of both.  
  * </p>  
  * @return mixed an array of strings that corresponds to the fetched row or <b>NULL</b> if there  
  * are no more rows in resultset.  
  */  
 function mysqli_fetch_array (mysqli_result $result, $resulttype = 'MYSQLI_BOTH') {}
/**
 * (PHP 5)<br/>
 * Get a result row as an enumerated array
 * @link http://php.net/manual/en/mysqli-result.fetch-row.php
 * @param mysqli_result $result
 * @return mixed <b>mysqli_fetch_row</b> returns an array of strings that corresponds to the fetched row
 * or <b>NULL</b> if there are no more rows in result set.
 */
function mysqli_fetch_row (mysqli_result $result) {}
/**
 * (PHP 5)<br/>
 * Fetch a result row as an associative array
 * @link http://php.net/manual/en/mysqli-result.fetch-assoc.php
 * @param mysqli_result $result
 * @return array an associative array of strings representing the fetched row in the result
 * set, where each key in the array represents the name of one of the result
 * set's columns or <b>NULL</b> if there are no more rows in resultset.
 * </p>
 * <p>
 * If two or more columns of the result have the same field names, the last
 * column will take precedence. To access the other column(s) of the same
 * name, you either need to access the result with numeric indices by using
 * <b>mysqli_fetch_row</b> or add alias names.
 */
function mysqli_fetch_assoc (mysqli_result $result) {}
/**
 * (PHP 5)<br/>
 * Returns the current row of a result set as an object
 * @link http://php.net/manual/en/mysqli-result.fetch-object.php
 * @param mysqli_result $result
 * @param string $class_name [optional] <p>
 * The name of the class to instantiate, set the properties of and return.
 * If not specified, a <b>stdClass</b> object is returned.
 * </p>
 * @param array $params [optional] <p>
 * An optional array of parameters to pass to the constructor
 * for <i>class_name</i> objects.
 * </p>
 * @return object an object with string properties that corresponds to the fetched
 * row or <b>NULL</b> if there are no more rows in resultset.
 */
function mysqli_fetch_object (mysqli_result $result, $class_name = null, array $params = null) {}

PHP-Reference Variable

Reference variable are those that have a reference to the value stored in them for example

 $name = 'fruit'; //Generic Varible  
 $$name='banana'; //Reference Variable  
 echo $fruit;   
 //Outputs Banana  


Here $name is a variable which stores name 'fruit' and in turn there is a memory location in your system when you run this program which is labelled as 'fruit' in which value is stored as $$name or $fruit.

Saturday, December 7, 2013

Static function,Variable accesibility

Recently one of my co-friends regarding  a programme which made my concepts clear for a static function, variable accessibility outside a class

 <?php  
 final class Hello  
 {  
      private static $greeting='Hello';  
      private static $initialized=false;  
      private static function initialize()  
      {  
           if(self::$initialized)  
           return;  
         self::$greeting='There';  
         self::$initialized=true;  
      }  
     public static function greet()  
     {  
       self::initialize();  
       echo self::$greeting;  
     }  
     public function hello1()  
     {  
       return 'hi';  
     }  
 }  
 echo Hello::hello1();  
 $obj=new Hello();  
 echo "==>";  
 echo $obj->greet();  
 ?>  


this outputs "hi==>There"

A static function though can be called with scope resolution operator via class name directly or from object.

A static variable can only be called from a static function or from a class name via scope resolution operator

And since we can call a static function directly we cannot use $this in the same

for example in static function greet we are calling the
echo self::$greeting;
and not
echo $this->$greeting;

Sunday, September 15, 2013

PHP-Loop Queston's

1. for($i=1;$i++;$i<100)
echo $i;

2. for($i=0;$i++;$i<100)
echo $i;

How many times will the loop execute in both the cases.

Answers:

1. Infinite why?
We know that for loop has 3 blocks 1st is assignment 2nd is condition and 3rd is increment.

Now in first block we have assignment $i=1 We are fine with it
In second block we are having $i++ which means that it will check for value of $i as condition before incrementing so $i=1 and increment $i to 2 and again in next pass we have $i=2 which is again true value>0 results in true.
and it will go on until falls short of memory.

2. 0 Why?

$i=0 initially checked that condition before increment $i=0 which returns false and as such loop halts.


OOPS-PHP-Magic Methods

1. __get($property)

Get value for a property set in a class foe example

 function __get($property)  
 {  
 return $this->properties[$property];  
 }  


Usage: echo $st->name;

2. __set($property,$value) Set value for a property
 function __set($property, $value)  
 {  
 $this->properties[$property]="AutoSet {$property} as: ".$value;  
 }  


Usage: $st->roll=16;

3. __call()
overloads any undefined function in a class.Thus we can also call an undefined function and show custom error message.

 function __call($method, $arguments)  
 {  
 echo "You called a method named {$method} with the following  
 arguments <br/>";  
 print_r($arguments);  
 echo "<br/>";  
 }  

Usage: $ol->notAnyMethod("boo");

OOPS-Static keyword,Singleton Design Pattern and its implementation

Static keyword is useful in creating Singleton design pattern because in such a scenario changes made by 1 object to a variable is reflected in all the objects of that class in that request.

Here is my example code with Singleton Design Pattern.

What I was trying to do is I was trying a singleton object over different request's and was trying to see whether it maintains its state or not. And it doesn't I tried running this page from different browser's and I failed to retrieve data of previous request's or session's.

Singleton Pattern is just needed so that only one object access at a time a resource to avoid conflict's

Singleton's are used to write log's and database access,maintain configuration variable's.

And that is when I realized the importance of an Application Server over a Web Server where we can create application object's.

 <?php  
 session_start();  
 //Singleton class example  
 error_reporting(E_ALL);  
 final class UserInfo  
 {  
   static $user=null;  
   static $instance=NULL;  
   public static function Instance()  
   {  
     if (self::$instance === null) {  
       self::$instance = new UserInfo();  
     }  
     return self::$instance;  
   }  
   /*  
    * Shows the array  
    */  
   public static function showUser()  
   {  
     if(self::$user!=null)  
     {  
       foreach(self::$user as $key=>$value)  
       {  
         echo "<br/>Sessionid ".$key." is assigned to ".$value."<br/>";  
       }  
     }  
   }  
   /*  
    * Adds session Id and user to the array  
    */  
   public static function AddUser()  
   {  
     echo "<br/>";  
     echo "Object count is ==>";  
     echo $ucount=count(self::$user);  
     echo "<br/>";  
     if(self::$user===null)  
     {  
       self::$user=array();  
       self::$user[session_id()]="User ".($ucount+1);  
       //print_r(self::$user);  
     }  
     else   
     {  
       if(!(array_key_exists(session_id(),self::$user)))  
       {  
         self::$user[session_id()]="User ".$ucount+1;  
       }  
     }  
   }  
   private function __construct()  
   {  
   }  
 }  
 echo "My Session Id is :". session_id();  
 UserInfo::Instance()->AddUser();  
 $fact1= UserInfo::Instance();  
 $fact= UserInfo::Instance();  
 $fact1->AddUser();  
 $fact->showUser();  
 UserInfo::Instance()->showUser();  
 if($fact1===$fact)  
   echo "Matches";  
 /*  
  * ERROR LINE  
  */  
 //$fact3= new UserInfo();  
 ?>  

Output is:
 My Session Id is :p15snn5ebgn52ftsj0eb43e4n0  
 Object count is ==>0  
 Object count is ==>1  
 Sessionid p15snn5ebgn52ftsj0eb43e4n0 is assigned to User 1  
 Sessionid p15snn5ebgn52ftsj0eb43e4n0 is assigned to User 1  
 Matches  

As you can see above is mine singleton class with a private constructor.I have 2 static methods one to store data and other to show data

In first case I have added user name as value and corresponding session id as key to the array.
I have called my method in 2 way's directly via class and by an object.

In the second call count goes 1

Finally I call show user in 2 way's and the 2 object's matches as per the condition

OOPS-What is the difference between Static and Final Keyword

Static
A static method remains common for all objects and can be called directly without the need of creation of any object.

For Example : classname::functionname();

A static property on the other end remains common for all the objects.It preserves its last changed state by any object.

Final
Final keyword on other end does not allows a class to be extended a method to be overridden in subclass or to change a property respective to its use in a class.

Saturday, September 14, 2013

OOPS-PHP4,PHP5-difference

1. In PHP4 there are no access modifiers everything is open we can't use public,private or protected for our methods.

2. In PHP4 there are interfaces but no abstract or final keyword.

An interface can be implemented by any object and which means that all the functions of interface must be implemented by the object.We can only declare the name and access type of any method in an interface.

An abstract class is where some methods may have some body too.

A final class cannot be extended.

3. In PHP4 there is no multiple inheritances for interfaces but Php5 supports multiple inheritance via implementing multiple interfaces together.

4. In PHP4 everything is static i.e if we declare any method in class which uses $this keyword we can call the same via classname::method() i.e. without instantiating the class which is not allowed in PHP5.

5. There is no class based constant,static property,destructor in PHP 4.

6. PHP 4 allows shallow copy of object.But in PHP 5 shallow copy is possible only via clone keyword.

7. PHP 4 does not have an exception object where as PHP 5 has an exception object.

8. Method over loading via magic functions like __get() and __set() is possible in PHP 5

OOPS-PHP-usefull functions

1. get_declared_classes();
Returns an array with the name of the defined classes.Useful when you have integrated a component or helper or vender class and what to know whether it's been included or not.

Thursday, September 12, 2013

Differences between abstract class and interface in PHP

Following are some main difference between abstract classes and interface in php
  1. In abstract classes this is not necessary that every method should be abstract. But in interface every method is abstract.
  2. Multiple and multilevel both type of inheritance is possible in interface. But single and multilevel inheritance is possible in abstract classes.
  3. Method of php interface must be public only. Method in abstract class in php could be public or protected both.
  4. In abstract class you can define as well as declare methods. But in interface you can only defined your methods.

Javascript-Typecasting-Question

What will this print

<script type="text/javascript">
alert('1'+2+4);
</script>


Ans : 124(since js typcasts everthing to string if a string is encountered)


When dealing with two numbers, the + operator adds these. When dealing with two strings, it concatenates.

3 + 5;              // 8
"hello " + "world"; // "hello world"
"3" + "5";          // "35"
 
 
When one operand is a string and the other is not, the other is converted to a string and the result is concatenated. 

"the answer is " + 42; // "the answer is 42"
"this is " + true;     // "this is true"
var a;
"a is " + a;           // "a is undefined"
 
In any other case (except for Dates) the operands are converted to numbers and the results are added.
 
1 + true;     // -> 1 + 1 -> 2
null + false; // -> 0 + 0 -> 0
 
 

How can I send headers then start a session?

  <?php 

  // make it or break it 

  error_reporting(E_ALL); 

  // begin output buffering 

  ob_start(); 

  // send a header 

  header ("Pragma: no-cache"); 

  // send some text to the browser 

  echo 'This is a line of text'; 

  // then we start our session  

  session_start(); 

  // set the value of the session variable 'foo' 

  $_SESSION['foo']='bar'; 

  // flush the buffer 

  ob_end_flush(); 

 ?>  


How are sessions stored?

The default behaviour for session storage is to save the session data in a file. This behaviour can be altered by changing the session.save_handler in your php.ini file. Options can be:

1. files
2. mm
3. database
4. SQLite

If we choose we can have this stored in one of the options above.

In files  session's are stored in /var/lib/php5 in Debian based linux
file is named like "sess_v93e2jhpjho4s4ea7r93vkbvu7" and data is stored like
foo|s:3:"bar";animals|a:8:{i:0;s:3:"cat";i:1;s:3:"dog";i:2;s:5:"mouse";i:3;s:4:"bird";i:4;s:9:"crocodile";i:5;s:6:"wombat";i:6;s:5:"koala";i:7;s:8:"kangaroo";}

The mm option saves the session data into memory, this also gives significant speed increase and is often recommended by tutorials for fine tuning PHP and apache web server.

Sessions may also be stored in a database. This option provides for greater manageability of sessions and allows the programmer to perform tasks such as counting of active sessions etc.In this session storage is permanent.

With the advent of PHP5, we now have SQLite bundled with PHP. If PHP is configured --with-sqlite, you will have access to saving sessions with a PHP native database, although SQLite is not truly a database, but a file abstraction layer with and SQL interface.

php-How do sessions work?

Sessions can be used in two ways:

1. cookie based
2. url based

Most sessions are cookie based. What this means is that when a session is started, a cookie is set on the clients machine with a unique session ID or SID. The session variables are stored typically on a file on the server that matches the unique session ID. When a variable is required, the client or browser looks for the file matching the session ID and retrieves the corresponding variables from it. A typical session file stored in the default session file directory would look like this
sess_fd51ab4d1820aa6ea27a01d439fe9959

PHP-Path to Session Storage

We can get and set session storage path using the following keyword in core php

session_save_path ([ string $path ] );

Wednesday, September 11, 2013

cakephp-requestAction

The method requestAction are used in cake php for calls a controller’s action from any location and returns data from the action.

Example :

 // Controller/CommentsController.php  
 class CommentsController extends AppController {  
   public function latest() {  
     if (empty($this->request->params['requested'])) {  
       throw new ForbiddenException();  
     }  
     return $this->Comment->find('all', array('order' => 'Comment.created DESC', 'limit' => 10));  
   }  
 }  

 // View/Elements/latest_comments.ctp  
 $comments = $this->requestAction('/comments/latest');  
 foreach ($comments as $comment) {  
   echo $comment['Comment']['title'];  
 }  

Php-require,require_once,include,include_once

Difference between require() and require_once(): require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page).

So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.

Difference between require() and include() is that require() produces a FATAL ERROR if the file you want to include is not found, while include() only produces a WARNING. There is also include_once() which is the same as include(), but the difference between them is the same as the difference between require() and require_once().

Cakephp-Difference in App:Uses(),App::import(),App::path()

App::uses() loads libraries using same standrds as cakephp folder structure i.e for files which follow the same standards regarding folder and file naming.

This is why it is not advisable to load vendor's using App::uses().

App::import() loads file if it has not been included before i.e. it is just a wrapper of include_once();

App::path() return the path of concerned cakephp folder

example: App::path('Vendor') return's path of vendor

Drawbacks of cakephp

1. Can't be used for small scale apps as it loads the complete application in beginning.
2. Learning Curve

Cakephp-Why cakephp have two vendor folder?

The “vendors” folder in the “app” folder is for application-specifc third-party libraries whereas the other “vendors” folder is for libraries you want to use in multiple applications.

Cakephp-HABTM implementation

HABTM

"Has and Belongs To Many"

A "Post" may have many "Tags" and may belong to many tags

In Post's Model


 public $hasAndBelongsToMany = array(  
  'Tag' => array(  
   'className' => 'Tag',  
   'joinTable' => 'posts_tags',  
   'foreignKey' => 'post_id',  
   'associationForeignKey' => 'tag_id',  
   'unique' => 'keepExisting',  
  )  
  );  

Cakephp-What are cakephp's configuration files?

  1. /app/config/core.php=>where we manage core configuration's such as debug,use of .htaccess
  2. /app/config/database.php=>Manage database configurations
  3. /app/config/email.php=>Manage email smtp configurations
  4. /app/config/routes.php=>manage routing

Cakephp-What are commonly used components of cakephp?

1. Security
2. Sessions
3. Access control lists
4. Emails
5. Cookies
6. Authentication
7. Request handling

Cakephp-What is the naming convention in cakephp

  1. Table names are plural and lowercased
  2. Model names are singular and CamelCased: ModelName, model filenames are singular: model.php
  3. Controller names are plural and CamelCased with *Controller* appended: ControllerNamesController, controller filenames are named similerly : usersController
  4. Associations should use the ModelName, and the order should match the order of the foreignKeys: var $belongsTo = ‘User’; 
  5. Foreign keys should always be: table_name_in_singular_form_id: user_id (foreign key) → users (table),
  6. many-to-many join tables should be named: alphabetically_first_table_plural_alphabetically_second_table_plural: tags_users ,
  7. columns in many-to-many join tables should be named like other foreign keys: tag_id and user_id ,
  8. columns named “created” and “modified” will automatically be populated correctly

Monday, May 6, 2013

Scaling a graph/chart perfectly

Selecting values for a scale for line and bar graphs is cumbersome many a times what should be the minimum value and what should be the maximum value is a question by many...

Here is the formula which might help you to scale a graph perfectly


$minval=floor($minval($minval<0?1.1:(1/1.1)/10)*10)

$maxval=ceil($maxval*($maxval>0?1.1:(1/1.1)/10)*10)


and expand/increment/step by 1.1 in above formula leads to a chart with nice space

//label spacing

$xlabelsteps=1;
if(count($data)>10)
{
    $xlabelsteps=ceil(count($data)/10); 
}

 //grid spacing


$xsteps=1;

if(count($data)>100)
{
      $xsteps=ceil(count($data)/100);
}

Tested on "Fusion charts"

Saturday, April 13, 2013

[Errno 14]Centos-Could not open/read file:///media/CentOS/repodata/repomd.xml,file:///media/cdrecorder/repodata/repomd.xml,file:///media/cdrom/repodata/repomd.xml

CentOS-Repository Error

 file:///media/CentOS/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/CentOS/repodata/repomd.xml
Trying other mirror.
file:///media/cdrecorder/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/cdrecorder/repodata/repomd.xml
Trying other mirror.
file:///media/cdrom/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/cdrom/repodata/repomd.xml
Trying other mirror.
Error: Cannot retrieve repository metadata (repomd.xml) for repository: c6-media. Please verify its path and try again
[root@dhcppc4 Desktop]# yum install yumex yum-fastestmirror yum-skip-broken yum-kmod yum-kernel-module yum-priorities
Loaded plugins: fastestmirror, refresh-packagekit
Loading mirror speeds from cached hostfile
 * base: centos.aol.in
 * c6-media:
 * epel: mirror.unej.ac.id
 * extras: centos.aol.in
 * updates: centos.aol.in
base                                                     | 3.7 kB     00:00    
file:///media/CentOS/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/CentOS/repodata/repomd.xml
Trying other mirror.
file:///media/cdrecorder/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/cdrecorder/repodata/repomd.xml
Trying other mirror.
file:///media/cdrom/repodata/repomd.xml: [Errno 14] Could not open/read file:///media/cdrom/repodata/repomd.xml
Trying other mirror.
Error: Cannot retrieve repository metadata (repomd.xml) for repository: c6-media. Please verify its path and try again

Walkthrough :

To counter this error we need to make some changes as a root in Centos.
I read somewhere that centos keeps up with same set of repos that it came with for a span of 10 years.So it looks for softwares only in specified repositories.

To counter this situation We need to change some repo files of Centos.Make sure you are logged in as root and take backup of each file alongside.

Open the following file
/etc/yum.repos.d/CentOS-Base.repo

 In this you will find sections from where centos reads repositories such as

#additional packages that extend functionality of existing packages

and

#contrib - packages by Centos Users

under these sections you will find that are

enabled=1

change this to

enabled=0

similerly Open the following file
/etc/yum.repos.d/CentOS-Media.repo

for [c6 media] section set
enabled=0

You might also need to modify

/etc/yum.repos.d/epel.repo similer fashion if you are getting erros from same file.

That's it you will be able to download from any repository now

linux user not in sudoers error,giving root permissions to a user

To give root permissions to a user the way out is

We need to edit a file called  

/etc/sudoers 

Note: (I am using CentOS) while writing this one down so customize acordingly

This file orignally has readonly permission for root which must be changed from its properties=>permissions which must be changed to read and write permissions

Now open this file using your favorite editor I am using G Edit

And look for a command like

# User privilege specification
root    ALL=(ALL) ALL
 
This specifies
 
The root user can execute from ALL terminals, acting as ALL (any) users, and run ALL (any) command. 
 
Add your 
username ALL=(ALL) ALL

for example for me it was 

gaurav ALL=(ALL) ALL

that's it

Wednesday, April 3, 2013

Ubuntu Unity Indicators Missing-Power,Time,Shutdown

If you are in a mess with unity and some of your indicators have vanished here is a some commands to bring them back

For Shutdown and user profile use following command

sudo apt-get install indicator-session

for  Time use

sudo apt-get install indicator-datetime

For Battery and Power use 

sudo apt-get install indicator-power

Ubuntu-Unity Issues-Font Issues-Dash Home not Finding Applications

Recently I went through this error during Ubuntu update to version 12

A text of white on white was appearin also Dash Home was not finding applications.The result was due to corrupted Unity User Interface.

To correct the same I ran following 2 commands from Terminal

rm ~/.cache/software-center -R
 
which sorted out my issue of ubuntu sodtware center not running
 
and then
 
unity --reset &
 
which told me to do a complete reinstall of unity via following command
 
sudo apt-get install unity 
 
  

Thursday, March 28, 2013

Efficient Ecommerce

What is e-commerce?
E-commerce is much more than simply making money out of online stores – although it is that too.

As Wikipedia clearly indicates

The term may refer to more than just buying and selling products online. It also includes the entire online process of developing, marketing, selling, delivering, servicing and paying for products and services.
 
E-commerce is, therefore, practically everything traditional business has done since is origination in past – but even more so in almost every respect.

On the one hand, we have:
- more customer-focus;
- more tailor-made solutions;
- and more satisfied niches;

And yet on the other hand, we have:
- more globalisation;
- more automation;
- and more opportunities;

How is it possible to get so big and still act so small?
This is the miracle of e-commerce – and Amazon.com is a perfect example of how this goal can be achieved. On the web since 1995, in 2011 its revenues reached $48 billion. Although it has since diversified into many other fields, it is still best known and loved for its online stores.
For many years, the site was known for just selling books – and for anyone who loves books, this was a mighty achievement. A bookshop owner acquires a very good knowledge of their clients. Over a long and fruitful business relationship, he or she will intuitively learn what their customers are going to like. And customers value that intuition – very much. In a competitive marketplace, it can often be the difference between making that sale or not.
Anyone who knew the publishing trade – at least in 1995 – could hardly have predicted a website might one day substitute the flesh-and-blood appeal of real professionals such as the above.
And yet from personalised recommendations and instant digital downloads to private and public wish-lists of those items we would most like our family and friends to buy, there is nothing a traditional bookshop-owner can do any longer which Amazon, with its virtual intelligence, cannot.
What is even more incredible, however, is that this concentration of ingenuity and wealth has led not to a fall in book-lovers’ choices but, instead, to a more effective connection with that diversity of interests which characterises modern society.
E-commerce doesn’t just mean higher levels of customer satisfaction in matters such as prices, delivery times, almost instantaneous customer-service emails and mobile apps and purchases – it also leads, if properly implemented by businesspeople looking to get that extra edge, to a greater variety of products, services and opportunities.
We may be looking to sell books or language courses; we may want to provide deals on online credit card transfers or travel insurance; but, whatever the product or service in question, bytes and websites are not only better for the Internet-connected customer than bricks and mortar – they’re cheaper to set up, expand and grow.


How to get it right
Starting off in e-commerce can seem a little daunting.Truth be told, a lot of what it needs is already part and parcel of good business practice. All you need to remember is the following maxim from Jerry Gregoire, an ex-CIO at Dell, the computer manufacturer:
“Don’t automate broken business processes.”
If your processes fail to work efficiently in a bricks-and-mortar store, where you only have to sell to those people who live close by – people who, in any case, probably value you as a friend above all – just imagine what’s likely to happen to such processes when they’re exposed to the competitive gaze of millions of potential customers.

The secret is there is no secret…
The only secret is knowing who to ask.
Solutions exist – all you need to do is understand the options first. Once you’ve understood the options and made your bricks-and-mortar processes as resilient as possible, it’s time to contact reputable organisations which show that they are able to understand your processes – as well as engineer effective e-commerce implementations.

7 factors that lead to e-commerce success
As part of its comprehensive analysis, the study examined seven overall factors in online retail success. These range from site design and the user-friendliness to the product range, the pricing level and the payment methods offered to shipping options and delivery of goods to the customer.

Meanwhile, a report on e-commerce in India concluded:
One of the main challenges that online shops have been confronted with for a long time is the desire of Indian consumers to see and touch products before buying them. As a result, many retailers offer cash-on-delivery payment and convenient return and refund options. Nonetheless, B2C E-Commerce experienced a more than 30 % growth from 2010 to 2011 in India.

The results of the largest survey of customer satisfaction in German e-commerce, conducted by ECC Handel and Hermes, were published on the occasion of the Online Trading Congress in Bonn. More than 10,000 consumers and customers of 108 German online shops came to the conclusion: Musikhaus Thomann is better than Amazon.

Wednesday, March 27, 2013

PHP Web Programming and Business Benefits of PHP Development

Inception of PHP is almost two decade old, when Danish programmer Rasmus Lerdorf created PHP in 1995. Inspired by that, in year 1997, two Israeli programmers Andi Gutmans and Zeev Suraski rewrote the parser, creating the base for PHP 3 and also built the Zend engine which is still followed as the interpreter for PHP.

Influence Of PHP Across Web

Today, almost two decades after countless colossal modifications to codebase, more than 35% of web traffic is handled by PHP. Facts on Wikipedia say 75% of websites use PHP, which includes some giant domains such as Facebook, Wikipedia, Yahoo, Photobucket and many others. Amazingly, list doesn’t end here; world’s best blogging platform “WordPress” and other popular CMSs like Drupal and Joomla are built in php.
Above mentioned facts are enough to claim the dominancy of PHP even in the presence of killer web development technologies. But, what are the reasons, why php hits the mainstream enterprise and why it is forecasted to maintain its momentum even in the coming years.
Success of php web programming totally bets on advantages which it offers to its users. Not only PHP developers find it convenient, but even end-users claim it to be friendly. Several studies have concluded some common advantages offered by php development, and they are as follow.

Free For All “Its Open Source”

Under GPL (General Public License) PHP is freely available for use, along with its associated software’s like MySQL, Text Editors and Apache Server to reduce your overall development cost. With the aim to serve you better, php community offers technical support and is constantly sweating hard to improve the core functionalities of PHP.

Cross-Platform Compatibility

It exhibits high compatibility with all the major OS and servers for easy deployment across vivid platforms. PHP scripts can run across OS like Linux, Windows, Solaris, OpenBSD, Mac OSX and others. It also provides support for all leading servers such as Apache, IIS, iPlanet and so on.

Powers Equally – Either Small or Big Websites

Either small or giant, whatever are your business needs a php based business website can be easily developed in not time and in limited budget. Business and organizational websites, informative forums, CRM solutions, e-commerce websites, community websites, e-business and gigantic database driven sites can be easily developed using php.

Extensions to Expand Functionalities

Plethora of extensions and libraries are available across the web using which you can extend core functionalities of your website. Even custom created extensions can be included into source code of PHP.

Top Security – For Hacker Proof Website

It offers top level security that helps prevent malicious attacks. These security stages can be easily attuned in the .ini file.

Veteran Developers to Execute Your Plans

You can hire PHP programmers/developers from reputed web development company more easily than any other language programmers. Just follow simple tips to hire veteran developers and stay away from worries.
In the end, if you are in the mood to add dynamic content to your project, then use of PHP is highly recommended. It free, easy to understand and integrates almost all the functionalities as per your needs. There are tons of php developers available on the net. Please don’t hesitate to add anything if I have missed some other great PHP benefits. Feel free to share your thoughts with other readers.

Tips to Create Secure PHP Applications

PHP is one of the most popular programming languages for the web. Such languages are very helpful for the programmer but the security holes in it can create a problem. They can create problems in the development path.Below are few tips to help you avoid some common PHP security pitfalls and development bug.
1. Use of Proper Error Reporting
Error reporting can be your best friend during the development process. Error reports helps you to find spelling mistakes in your variables and also detect incorrect function usage. Always make sure that you hide all the error reporting once you decide to make the site live.
This can be done by invoking the simple function “error_reporting(0)” at the top of your application file(s).
You should always make sure to log your errors to a protected file. Which help to detect the problem when something go wrong. Therefore, This can be done with the PHP function “set_error_handler”.
2. Disable PHP’s harmful Features
PHP’s creators have always included some features to make PHP development easier. Some of these helpful features can have unintended consequences.
We can call these as “bad features” because they have allowed data validation and created a path for bugs to finding their way into scripts. One of
the first things you should do when the development process begins is
disable certain of these features. Depending on the host which you are using, these may or may not be turned off for you. If you are developing on your own computer or any local environment, they probably won’t be turned off. Some of these features have also been removed in the upcoming PHP6, but are ubiquitous in PHP4 applications and are only deprecated in PHP5 applications.
3. Validate Input
With addition to escaping characters, another good way to protect
input is to validate it. Normally you actually know what kind of data you are expecting on input.  So the simplest way to protect yourself against attacks is to make sure your users can only enter the appropriate data.
4. Watch for Cross Site Scripting (XSS) Attacks in User Input
A web application usually accepts input from users and displays it
in some way. They can be in a wide variety of forms. When accepting input, allowing HTML can be a dangerous thing,because that allows for JavaScript to be executed in unintended ways. If even one hole is left open, JavasScript can be executed and cookies could be hijacked. This cookie data could then be used to fake a real account and give an illegal user access to the website’s data. There are a some ways you can protect your site from such attacks. One way is to disallow HTML altogether, because then there is no possible way to allow any JavaScript to execute.
5. Protecting against SQL Injection
SQL injection attacks occur when data is not checked, and the application doesn’t escape characters used in SQL strings such as single quotes (‘) or double quotes (“). If these characters are not filtered out users can disturb the system by making queries always true and which allow them to trick  login systems.
MySQLi help protect your database input. We can do it in 2 ways.
Either with the mysqli_real_escape_string function when connected to a server or with prepared statements.
Prepared statements are a method of separating SQL logic from the data being passed to it. The functions used within the MySQLi library filter the input for us when we bind variables to the prepared statement.

Thursday, February 7, 2013

UNION Example MySQL

There are 2 tables

Table A

id
1
2
3

Table B

id
1
2
3
4
5

Our job is to merge 2 tables to get following output

We fire our sql query as follows

SELECT  `a`.`id` AS `id` FROM `a` UNION SELECT `b`.`id` AS `id` FROM `b`
and get desired output

There are some rules that you need to follow in order to use the UNION operator:
  • The number of columns appears in the corresponding SELECT statements must be equal.
  • The columns appear in  the corresponding positions of each SELECT statement must have the same data type or at least convertible data type.
By default, the UNION operator eliminates duplicate rows from the result even if you don’t use DISTINCT keyword explicitly. Therefore it is said that UNION is the shortcut of UNION DISTINCT.
If you use UNION ALL explicitly, the duplicate rows, if available, remain in the result. The UNION ALL performs faster than the UNION DISTINCT.

Mysql Joins

Joins are used to get data from Non Clustered indexes in a table

Following are the Types of Joins

Inner Join

id name       id  name
-- ----       --  ----
1  Pirate     1   Rutabaga
2  Monkey     2   Pirate
3  Ninja      3   Darth Vader
4  Spaghetti  4   Ninja
 
SELECT * FROM TableA
INNER JOIN TableB
ON TableA.name = TableB.name

id  name       id   name
--  ----       --   ----
1   Pirate     2    Pirate
3   Ninja      4    Ninja 


FULL OUTER JOIN
 
SELECT * FROM TableA
FULL OUTER JOIN TableB
ON TableA.name = TableB.name

id    name       id    name
--    ----       --    ----
1     Pirate     2     Pirate
2     Monkey     null  null
3     Ninja      4     Ninja
4     Spaghetti  null  null
null  null       1     Rutabaga       
null  null       3     Darth Vader

 
LEFT OUTER JOIN

SELECT * FROM TableA
LEFT OUTER JOIN TableB
ON TableA.name = TableB.name

id  name       id    name
--  ----       --    ----
1   Pirate     2     Pirate
2   Monkey     null  null
3   Ninja      4     Ninja
4   Spaghetti  null  null
 
RIGHT OUTER JOIN

SELECT * FROM TableA
RIGHT OUTER JOIN TableB
ON TableA.name = TableB.name

id  name       id    name
--  ----       --    ----
null  null     1     Rutabaga  
1   Pirate     2     Pirate
null  null     3     Darth Vader 
3   Ninja      4     Ninja

Clustered and Non Clustered Indexes

Non-clustered

The data is present in arbitrary order, but the logical ordering is specified by the index.

The data rows may be spread throughout the table regardless of the value of the indexed column or expression.

The non-clustered index tree contains the index keys in sorted order, with the leaf level of the index containing the pointer to the record (page and the row number in the data page in page-organized engines; row offset in file-organized engines).
In a non-clustered index:
  • The physical order of the rows is not the same as the index order.
  • Typically created on non-primary key columns used in JOIN, WHERE, and ORDER BY clauses.
  • Index is stored separately and data is stored separately
  • Data is not determined as a physical order
There can be more than one non-clustered index on a database table.

 Example: Index in a textbook

Non Clustered Index on Salary_grade in following table


Clustered

Clustering alters the data block into a certain distinct order to match the index, resulting in the row data being stored in order. Therefore, only one clustered index can be created on a given database table.

Clustered indices can greatly increase overall speed of retrieval, but usually only where the data is accessed sequentially in the same or reverse order of the clustered index, or when a range of items is selected.

Since the physical records are in this sort order on disk, the next row item in the sequence is immediately before or after the last one, and so fewer data block reads are required.

The primary feature of a clustered index is therefore the ordering of the physical data rows in accordance with the index blocks that point to them. Some databases separate the data and index blocks into separate files, others put two completely different data blocks within the same physical file(s). Create an object where the physical order of rows is the same as the index order of the rows and the bottom (leaf) level of clustered index contains the actual data rows .

 For example Primary Key Constraint in a table no matter if you enter data in an non sequential order it will always be retrieved sequentially as per clustered index

There can be only one Clustered Index in a table how ever there can be more than one columns in a clustered index in a table thus making it into a composite index.

Example: Telephone Directory

Non Clustered index on salary_grade in following table

Salary_grade      Last_Name            First_Name
2                        Timberwood            Jack
2                        Bibleton                   Mike
5                        Rabbies                    Luna

Clustered Index on salary_grade in following table

Salary_grade    Salary
2                       2000
5                       5000

Types of Indexes in a database

Bitmap index

A bitmap index is a special kind of index that stores the bulk of its data as bit arrays (bitmaps) and answers most queries by performing bitwise logical operations on these bitmaps. The most commonly used indexes, such as B+trees, are most efficient if the values they index do not repeat or repeat a smaller number of times. In contrast, the bitmap index is designed for cases where the values of a variable repeat very frequently. For example, the gender field in a customer database usually contains two distinct values: male or female. For such variables, the bitmap index can have a significant performance advantage over the commonly used trees.

Dense index

A dense index in databases is a file with pairs of keys and pointers for every record in the data file. Every key in this file is associated with a particular pointer to a record in the sorted data file. In clustered indices with duplicate keys, the dense index points to the first record with that key.

Sparse index

A sparse index in databases is a file with pairs of keys and pointers for every block in the data file. Every key in this file is associated with a particular pointer to the block in the sorted data file. In clustered indices with duplicate keys, the sparse index points to the lowest search key in each block.

Reverse index



 

Request data from a server in a different domain

To request data from a different domain we use json with padding

or jsonp(json with padding)

we use Response to come in a callback function

Refer to following urls

http://itfeast.blogspot.in/2012/07/cross-domain-request-using-jquery.html
http://en.wikipedia.org/wiki/JSONP
http://api.jquery.com/jQuery.ajax/


script = document.createElement(”script”);
script.type = text/javascript”;
script.src = http://www.someWebApiServer.com/some-data”;
 
We get data like this
 
<script>
{['some string 1', 'some data', 'whatever data']}
</script>
 
Due to inconvenience in fetching data from script tag jsonp was introduced as follows
 
script = document.createElement(”script”);
script.type = text/javascript”;
script.src = http://www.someWebApiServer.com/some-data?callback=my_callback”;
 
Now since we have passed a parameter to return jsonp data we will always get sth like
 
my_callback({['some string 1', 'some data', 'whatever data']});
 
in the script tags     
 
Let's take an simple example of using the twitter feed.
 
RAW javascript demonstration (simple twitter feed using jsonp) 

<html>
    <head>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
        <script>
        function myCallback(dataWeGotViaJsonp){
            var text = '';
            var len = dataWeGotViaJsonp.length;
            for(var i=0;i<len;i++){
                twitterEntry = dataWeGotViaJsonp[i];
                text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
            }
            document.getElementById('twitterFeed').innerHTML = text;
        }
        </script>
        <script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
    </body>
</html>
 
And Basic jQuery example (simple twitter feed using jsonp)
 
<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
                    dataType: 'jsonp',
                    success: function(dataWeGotViaJsonp){
                        var text = '';
                        var len = dataWeGotViaJsonp.length;
                        for(var i=0;i<len;i++){
                            twitterEntry = dataWeGotViaJsonp[i];
                            text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
                        }
                        $('#twitterFeed').html(text);
                    }
                });
            })
        </script>
    </head>
    <body>
        <div id = 'twitterFeed'></div>
    </body>
</html> 

Wednesday, February 6, 2013

Difference in Buffer and Cache

Buffer:
In computing, a buffer is a region of memory used to temporarily hold data while it is being moved from one place to another. Typically, the data is stored in a buffer as it is retrieved from an input device (such as a keyboard) or just before it is sent to an output device (such as a printer). However, a buffer may be used when moving data between processes within a computer. This is comparable to buffers in telecommunication. Buffers can be implemented in either hardware or software, but the vast majority of buffers are implemented in software. Buffers are typically used when there is a difference between the rate at which data is received and the rate at which it can be processed, or in the case that these rates are variable, for example in a printer spooler.


Cache:
In computer science, a cache (pronounced /ˈkæʃ/, like "cash" [1]) is a collection of data duplicating original values stored elsewhere or computed earlier, where the original data is expensive to fetch (owing to longer access time) or to compute, compared to the cost of reading the cache. In other words, a cache is a temporary storage area where frequently accessed data can be stored for rapid access. Once the data is stored in the cache, future use can be made by accessing the cached copy rather than re-fetching or recomputing the original data, so that the average access time is shorter. Cache, therefore, helps expedite data access that the CPU would otherwise need to fetch from main memory.

Sunday, February 3, 2013

Constants,Configuration Variables in cake php

Many a times we need to use some variables throughout our application.

CakePHP's Configure class can be used to store and retrieve application or runtime specific values. This class can be used to store anything and can be accessed from any part of the application

For the application of the same we define a file in app/config/config.php

To store a configuration variable:

Configure::write('variable_name', 'value') ;

And to read from configuration:
 
Configure::read('variable_name');

Now we can use Configure::write() or we can also use the $config array

as follows

// Create the config array
$config = array();


// Define config variable
$config['from_email'] = '';


//  Or Define variable as follows

Configure::write('from_email', 'abc@abc.com') ;

 
$config['api_key'] = 'http://www.example.com';
$config['default_timezone'] = 'Europe/London'; 
$config['page_limit'] = 6;


Now our Framework must know about this file so add the following code in /app/config/bootstrap.php

Configure::load('config');


Now read the configuration variables anywhere in the application as follows

Configure::read('from_email');
Configure::read('api_key');
Configure::read('page_limit');
 

Sunday, January 27, 2013

Cakephp Auth Component 2.0

Cakephp Auth Component 2.0

Define Auth component to controller as follows

public  $comonents=array(
'Auth'=>array(
                           'loginRedirect' =>array('controller'=>'users','action'=>'index'),
                           'logoutRedirect'=>array('controller'=>'users','action'=>'index'),
                            'authError'=>'Access Denied',
                            'authorize'=>array('Controller'),
                            'loginError'=>'Invalid credentials, please try again.',
                            'allow'=>('index','view');
                       ) ,
'Session'
);

//check for authorization
public function isAuthorized($user)
{
          return true;
}

Now in users controller define the login action

public function login()
{
       if($this->Auth->login())
       {
           $this->redirect($this->Auth->redirect());
       }
     else
    {
       $this->Session->setFlash('Authentication Failed')
   }
}

public function logout()
{
     $this->redirect($this->Auth->logout());
}

create form in login view to provide interface to user for username and password and AuthComponent will automatically validate login.

Make sure fields in the database match cake's cretriea i.e "usename" for User Name and "password" for Password and "Users" table.

register new user 
create a new add method in a controller create a view for the same and then in user model just before save hash the password as follows

$this->data['user']['password']=AuthComponent::password($this->data['User']['Password']);

To check for login status
$this->Auth->loggedIn();
To get current info of loggedin user
 $this->Auth->User;
To Display auth error message
$this->Session->flash('auth');