How to detect Internet Explorer with PHP

It is possible to use PHP to check whether your site visitor uses Internet Explorer and output some IE-specific text or HTML/CSS markup.
PHP 4.1.0 or newer

In PHP superglobal array $_SERVER there is usually HTTP_USER_AGENT element which contains browser-specific id string

Internet Explorer uses something like

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)”

as id string

Internet Explorer uses something like

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)”

as id-string, depending on platform and version. Every version of IE has “MSIE” part in HTTP_USER_AGENT string, so it is possible to detect IE simply by scanning $_SERVER[‘HTTP_USER_AGENT’] for string “MSIE”.

Example: function ae_detect_ie below returns true if Internet Explorer has been detected.
source code: php

For a maximum speed, we use strpos function instead of strstr, preg_match or other PHP string-search functions. Note, that if you want to check for IE in several places, it is better to store function value in some variable, to avoid serveral similar string-searches.

Here is the example of detecting Internet Explorer and suggesting user to get another browser:
source code: php

It seems, that your are using MSIE.
Why not to switch to standard-complaint brower, like

PHP 5.0.5 :: Microsoft Internet Explorer 6.0
PHP 5.0.5 :: Firefox 1.5

What’s the basic differance between MVC and HMVC ?

MVC only has 1 controller per request, HMVC can have many.

MVC request processing:

1. bootstrap, determine uri
2. route and load controller
3. display output

HMVC request:

1. bootstrap, determine uri
2. route and load main controller
2a). create request, route, load controller
2b). create request, route, load controller

3. display output

Basically, at any point within an HMVC framework, you can do something like this:

Each request is entirely self-contained, as if someone went to (for users/login) It’s very similar to AJAX, except that all of the requests happen within the main request.

Default MySQL character set and collation

All versions of MySQL on (mt) Media Temple server are installed with the default character set ‘latin1’. The default collation for latin1 is ‘latin1_swedish_ci’ which in most cases does not cause any problems.

You can also change the character set and collation of a database by using the following MySQL command:

ALTER DATABASE db_name CHARACTER SET utf8 COLLATE utf8_general_ci;

You can also change the character set and collation of each table by using the following MySQL command:


In PHP5, what is the difference between using self and $this? When is each appropriate?

Use $this to refer to the current object.
Use self to refer to the current class.
In other words,
use $this->member for non-static members,
use self::$member for static members.

Use self to reference static class properties


class visitors
private static $visitors = 0;

function __construct()

static function getVisitors()
return self::$visitors;


$visits = new visitors();
echo visitors::getVisitors()."

$visits2 = new visitors();
echo visitors::getVisitors().”


PHPDocumentor basics

PHPDoc Documentation

PHPDocumentor is the most advanced automatic documentation system written for PHP, in PHP. This package has many features:

  • ability to parse any PHP file, regardless of documentation format
  • conforms loosely to the JavaDOC protocol, and will be familiar to Java programmers
  • is designed specifically for PHP, and so documents all constants, functions, classes, methods, and class variables
  • *NEW 0.4.1* complete DocBlock tag support. Additions include @var, @magic, @deprec, @todo, and parsing of @param.
  • *NEW 0.4.1* package inheritance in classes
  • *NEW* advanced linking creates a hyperlink for every element in the project
  • *NEW* page-level documentation, package-level documentation
  • *NEW* complete PHPDocumentor spec with extreme detail
  • *NEW* option to document @access private elements
  • *NEW* indexing by package and overall
  • *NEW* Class trees

Note: if this howto looks bad, get a browser that supports css

PHPDocumentor basics

The documentation process begins with the most basic element of PHPDocumentor: a Documentation block or DocBlock. A basic DocBlock looks like this:


A DocBlock is an extended C++-style PHP comment that begins with “/**” and has an “*” at the beginning of every line. DocBlocks precede the element they are documenting. To document function “foo()”, type:

* Defies imagination, extends boundaries and saves the world ...all before breakfast!
function foo()

define() statements, functions, classes, class methods, and class vars can all be documented.

A DocBlock contains three basic segments in this order:

  • Short Description
  • Long Description
  • Tags

The Short Description is on the first line, and can be terminated with a period or with a blank line. The Long Description continues for as many lines as desired and may contain html markup for display formatting. Here is a sample DocBlock with a Short and a Long Description:

* return the date of Easter
* Using the formula from "Formulas that are way too complicated for anyone to 
* ever understand except for me" by Irwin Nerdy, this function calculates the 
* date of Easter given a date in the Ancient Mayan Calendar, if you can also
* guess the birthday of the author.


Tags are single words prefixed by a “@” symbol. Tags inform PHPDocumentor how to present information and modify display of documentation. All tags are optional, but if you use a tag, they do have specific requirements to parse properly.

A sample DocBlock showing all possible tags

More tags may be added in the future, not all tags are implemented at this time in phpdocumentor, however they are all recognized as tags and will at least be displayed

* The short description
* As many lines of extendend description as you want {@link element} links to an element
* {@link Example hyperlink inline link} links to a website
* Below this goes the tags to further describe element you are documenting
* @param  	type	$varname	description
* @return 	type	description
* @access 	public or private
* @author 	author name 
* @copyright	name date
* @version	version
* @see		name of another element that can be documented, produces a link to it in the documentation
* @link		a url
* @since  	a version or a date
* @deprecated	description
* @deprec	alias for deprecated
* @magic compatibility
* @todo compatibility
* @exception	Javadoc-compatible, use as needed
* @throws  	Javadoc-compatible, use as needed
* @var		type	a data type for a class variable
* @package	package name
* @subpackage	sub package name, groupings inside of a project

Tag Information:

  • @var [type]

    type is the type of a class variable. Default is “mixed” if not included. Use this tag to document variables with type restrictions.

  • @return [type] [description]

    type is the type of a value returned from a method or function.
    description a brief description of the value returned

  • @param [type] [$varname] [description]
    * return the day of the week
    * @param string $month 3-letter Month abbreviation
    * @param integer $day day of the month
    * @param integer $year year
    * @return integer 0 = Sunday, value returned is from 0 (Sunday) to 6 (Saturday)
    function day_week($month, $day, $year)

    use this tag in a DocBlock preceding a function or method.

    type is the type of parameter$varname, which may be one of: (string, array, integer, double, class, mixed)
    $varname is the name of the parameter, and must be preceded by the $ punctuator
    description a brief description of this parameter, which may be more than one line

    the @param tag can refer to more parameters than the function lists, to allow documenting of functions that use func_get_args

  • @link [url] takes url which must contain the protocol (@link, not @link and outputs a hyperlink
  • @author author name prints author’s name, and parses the email address to display a hyperlink. Multiple authors may be listed on one line, but is not recommended
  • @access [public/private]. elements are public by default. Using “@access private” prevents PHPDocumentor from documenting the private element
  • @see [element] or @see [element1], [element2]…

    element may be the name of any documented element (constant, function, class, class method, class variable). PHPDocumentor recognizes the element type based on the presence of punctuators:

    • $element is a class variable in the current class – the class that contains the DocBlock
    • element() is either a method in the current class or a function in the current file
    • element is either the name of a constant or of a class

    To resolve name conflicts resulting from inheritance, use the :: scope operator classname::method() or classname::$variable.

    * class 1
    * example of {@link Inline linking to a website}
    * example of use of the :: scope operator
    * @see subclass::method()
    class main_class
    	* example of linking to same class, outputs "function main_class::parent_method()
    	* @see function parent_method
    	$var foo = 3;
    	* subclass inherits this method.
    	* example of a word which is either a constant or class name, in this case a classname
    	* @see subclass
    	* @see subclass::$foo
    	function parent_method()
    		if ($this->foo==9) die;
    * this class extends main_class
    * @see main_class
    subclass extends main_class
    	* bar.
    	* example of same class lookup - see will look through parent hierarchy to find the method in {@link main_class}
    	* the above inline link tag will parse as main_class
    	* @see parent_method()
    	var $foo = 9;
  • @package is used to group classes and functions into groups. @package is never assumed, and must be specified to include an element in a package
  • @subpackage is used to group classes and functions into sub-sections of the main package

Inline Tag Information:
Inline tags are formatted like: {@tag params}, where “tag” is the name of the inline tag and params is parameters for the inline tag. Inline tags display their output in the normal flow of the text, and should be used in descriptive areas of the DocBlock.

  • {@link [@see-style element]} or {@link [URL] [optional description of URL]}
    • a @see-style element is described above, and may be the name of a class, function, variable, or constant
    • any valid URL (uniform resource locator) will be output as this html: <a> tag as <a href=”URL”>optional description of URL<\a>
      valid URLS include websites (, ftp sites (, telnet sites (telnet://, etc.
    * class 1
    * example of {@link}
    * displays as "example of"
    class main_class
    	* This function sends the user to {@link The SourceForge Website}
    	* displays as "This function send the user to The SourceForge Website"
    	function goto_sourceforge()
    * this class extends {@link main_class}
    * displays as "this class extends main_class"
    subclass extends main_class
    	* bar.
    	* this class inherits {@link main_class::goto_sourceforge()}
    	var $foo = 9;

Elements that can be documented

Every major reusable element in PHP can be documented:

  • Packages (see below for details)
  • Procedural Pages (see below for details)
  • Classes
  • Class Methods
  • Class Variables
  • Functions
  • Defines (constants)

Packages are collections of elements into a group for documentation and release purposes. They may contain any of the standard PHPDocumentor elements (class, function, class method, class variable, define). A Package-level doc is an html file with the same name as the package that is located in the same directory as one of the physical files that contains a package element. In other words, for package foo that contains class bar in file /php/bar.php, PHPDocumentor will attempt to document “foo.html” by looking for /php/foo.html.

Package-level docs should be in standard html format. The only valid tags in Package-level documentation are inline tags. For this release, that means ONLY {@link} may be used in package-level documentation

Here is some example package-level documentation for package baz that contains classes fooclass and barclass

	<title>Package baz>/title>

This package is essential.  using class {@link fooclass} you can instruct your computer to brush your teeth for you.  Combining this functionality with the back massage given by {@link barclass}, you may truly retire in comfort.  In particular, {@link barclass::footmassage()} is a most exquisite experience.
Please follow this list of links for more help:
	<li><a href=""><The reinstall Windows hotline>
	<li><a href=""><Heaven>
	<li><a href=""><The PHPDocumentor Homepage>
	<li><a href=""><The most beautiful music you've ever heard>


Procedural Pages are physical files that contain at least one function or constant. They may also contain classes, but every class is documented separately from the physical file that contains it. In other words, if foo.php contains function bar() and class baz, bar will be documented as part of Procedural Page _foo_php, and class baz will be documented as class baz. PHPDocumentor interprets the first DocBlock in a file as a Procedural Page-Level DocBlock, or page-level DocBlock, if and ONLY if it does not precede any elements before the next DocBlock.

* Page-level DocBlock
* This procedural page contains many functions that blah blah blah
* function or define DocBlock
function blah()

The following is an example of a NON-page-level DocBlock

* Almost a Page-level DocBlock
* This procedural page contains many functions that blah blah blah
* function or define DocBlock
function blah()

PHPDocumentor will interpret the first DocBlock as belonging to define("screwedup",66), rather than to the page

All other elements are documented by placing the DocBlock before the element. Any valid PHP Code may be placed between a DocBlock and an element as long as it isn’t another element.

* DocBlock will document function blah()
// random comment
$a += strpos(get_another_thingy(66,$ufta));
// etc. etc.
function blah()

A realistic example

The code below is a sample class showing PHPDocumentor in action

PHPDocumentor can parse any valid PHP code, but it is recommended to follow this style for ease of programming for both you and people who will be using your packages

* A sample class
* This class is just random php used as a {@link phpdoc} example
* @version 1.0
* @author Joshua Eichorn <>
* @project test
class phptestclass
	* A sample class variable
	* @access private
	* @var string
	var $sample;

	* The class constructor
	* This sets up the class and does other random stuff
	function phptestclass
		$this->sample = "test";

	* A test function
	* This function returns {@link $sample}
	* @see set(), $sample
	* @return string
	function test()
		return $this->sample;

	* Set the sample var
	* @param string $var
	* @see phptestclass::$sample, phptestclass::test()
	function set($var)
		$this->sample = $var;


How to use href name properties used?

On-page anchors

The anchor () tag isn’t only for creating links.
You can also use them to create places on a page that you can jump to directly from a link.

e.g. You can create an on-page anchor with…

Which you can then link to with…

Skip navigation

Which brings us on to…

HTML Href Property

href stands for “hypertext reference”, and simply means the target of a link.

e.g. A link to another site…

About us

A link to an anchor on this page…

Product One

Or a link to an anchor on a different page…

About Geoff

PHP 4 and PHP 5 Comparison

The first thing that comes to mind when you start to compare PHP 4 and 5 is the:

Object Model
The Object Model was present in PHP 4, but it was completely reworked in PHP 5. Here are some of the most important updates:

* Passed by Reference
This is one of the most important innovations in PHP 5. In PHP 4 everything, including objects, was passed by value. This has been changed in PHP 5 where everything is passed by reference.

PHP Code:
$pObject1 = new Object();

$pObject2 = new Object();

This is a typical PHP 4 code – if you wanted to duplicate an object, you had to copy it and assign a new value to it. In PHP 5 the coder can simply use the “clone”. This also means that you no longer need to use the reference operator (&) for your code.

Here is how the same code will look in PHP 5 :
$pObject1 = new Object();
$pObject2 = clone $pObject1;

Since we were chaning only the name, we “cloned” the first object and simply changed the value that needed changing.

* Class Constants and Static Methods/Properties
With PHP 5 you can safely create class constants that act in very much the same way as do defined constants, but are limited within a class definition and can be accessed with “::”. Have in mind that constants must have a constant expression for a value; they can’t be equal to a variable or a result of a function call.

Here is how you can define a constant:

PHP Code:
const constant = ‘constant value’;

And here is how the constant can be accessed in a defined class:

PHP Code:
class MyClass
const constant = ‘constant value’;

function showConstant() {
echo self::constant . “\n”;

The Static Methods and Properties are also a PHP 5 innovation. When a class member is declared as static, it’s accessible with “::” without an instance.

* Visibility
In PHP 5 another addition is the “visibility” of the class methods and properties. The visibility has 3 levels:
o Public – the most visible. Methods can be read by everyone and properties can be written or read by anyone.
o Protected – the members are visible only by the actual class they are a part of, as well as by subclasses and parent classes.
o Private – members are visible only to the actual class they are a part of.

Here is an example of how members are declared
echo $this->protected;
echo $this->private;

$bor = new ClassA();
echo $bor->public; // Will work
echo $bor->protected; // Will give you a fatal error
echo $bor->private; // Will give you a fatal error
$obj->printHello(); // Will display Public, Protected and Private

* Define ClassB
class ClassB extends ClassA
// we can redeclare both the public and protected method, but we can’t redeclare the private one
protected $protected = ‘Protected2’;

function printHello()
echo $this->public;
echo $this->protected;
echo $this->private;

$obj2 = new MyClass2();
echo $obj2->public; // Will work
echo $obj2->private; // Is now undefined
echo $obj2->protected; // Will display a fatal error
$obj2->printHello(); // Will show you Public, Protected2, Undefined
* Unified Constructors and Destructors
In PHP 4 the constructor was just a method with the same name as the name of the class. So, if you changed the name of the class, you had to go and update it every time it was used.

In PHP 5, to spare the coders this hassle, the PHP developers have created an unified name for the constructors – “__construct()”.

A new addition is the “__destruct()” keyword. When used, the code will be executed only when the object is destroyed.

* Abstract Classes
With PHP 5 you can also create the so called “abstract” classes. These are classes, which are used only as a model to define other classes. If a certain class contains abstract method, it must be defined as abstract.

Here is how a normal class is defined:
class Message{

and here is how an abstract class is defined:
abstract class Message{
* Interfaces
Another new addition in PHP 5 is the “Interfaces”, which can help you design an API. The interface will define the methods, which must be implemented in a class. Have in mind that all methods which are defined in an interface must be public.

A big advantage of this new addition is that in a class you can implement any number of interfaces.

Here is how it all works :

an example of a simple class:
class cow {
function moo() {
echo “moo, moo, moo …”;

and now we implement the interface in the class:
class cow implements animal{
function moo() {
echo “moo, moo, moo …”;
function breath() { echo “cow is breathing …”;}
function eat() { echo “cow is easting …”;}
When an interface is implemented in a class, the class MUST define all methods and functions of the interface, otherwise the php parser will show a fatal error.

* Magic Methods
All methods, starting with a double underscore (“__”) are defined as “Magic Methods”. They are set to additional functionality to the classes. It’s recommended that you don’t use methods with the same naming pattern.

Some of the most used magic methods are: __call, __get, __set and __toString.

* Finality
The “final” keyword has been introduced, so that a method cannot be overridden by a child now. This keyword can also be used to finalize a class in order to prevent it from having children.

* The __autoload function
A very useful function added in PHP 5, which can save the usage of several includes in the begging of the file. The __autoload function will load object files automatically when PHP encounters an undefined yet class.
function __autoload($class_name) {
require_once “./includes/classes/$”;

PHP 5 also introduces several completely new features

* Introduction of Standard PHP Library (SPL)
The Standard PHP Library (SPL) is a set of interfaces for PHP, whose aim is to implement more efficient data access interfaces and classes. This functionality is designed to ease the access to aggregate structures, such as arrays, database result sets, XML trees, directory listings or any other lists. At the moment, SPL works mainly with Iterators.

The main benefit of this is that, since now it is set as Standard, it can be used by everybody to provide better coding practices.

* Miscellaneous Features and Updates
Here are the rest of the features, which do not fall into the previous categories.
o Type Hinting
Limited Type Hinting is introduced in PHP 5. Now the coder can select which kinds of variables can be passed to class methods or functions. For the moment, this feature works with classes or arrays only – integers and strings are not supported.
function echo_user(User $user) {
echo $user->getUsername();
A fatal error will appear if the passed parameter is not User or a subclass of User.

o Exceptions
Exceptions are finally added in PHP in the 5th revision of the programming language. While the exception is basically an error, by using it you can control the simple trigger_error notices, which were unchangeable in PHP 4.
try {
} catch (AccessDeniedException $e) {
die(‘Unable to write the cache, access denied.’);
} catch (Exception $e) {
die(‘Unknown error occurred : ‘ . $e->getMessage());
The exceptions are basically just objects. When an error occurs you can use an exception in its place. This way, when an exception is used, the rest of the following PHP code will not be executed.

If you are about to do something, the result of which you are unsure, you can surround it with a “try” block and this way, if something happens, your catch block is there to catch the error message and handle it respectively.

o E_STRICT Error Level
In PHP 5 a new error lever is introduced – the E_STRICT error level. It’s not included in E_ALL by default, so in order to use it, you will have to specify it. Its function is to notify you when deprecated code is used.

o New Extensions
Several new extensions are added in PHP 5. Among them, the most useful are:
+ SimpleXML – for an easier processing of XML data
+ DOM and XSL – their goal is to act in the place of DOMXML in PHP 4. With them, XML usage is much easier.
+ PDO – a very good OO interface for interacting with databases
+ Hash – you now have access to a lot of hash functions beside the most popular ones – md 5 and sha1

o New Functions
A lot of new functions are added to PHP 5. Here is a short list of the new additions:

+ array_combine() – it will create one array, using another two arrays – one for the keys and one for their values
+ array_walk_recursive() – a user function is applied recursively to all of the array members

+ ibase_db_info() – it will request the statistics for a database
+ ibase_name_result() – it will assign a name to a set of results
+ ibase_service_attach() – this function will connect you to the service manager
+ ibase_affected_rows() – it will return the number of rows affected by the previous query

+ iconv_strlen() – it will return the character count of a string
+ iconv_substr() – it will cut a part of a string
+ iconv_mime_decode_headers() – this function will decode several MIME headers at the same time

+ stream_copy_to_stream() – it will copy the data from one stream to another stream
+ stream_socket_get_name() – it will find the names of the local and remote sockets
+ stream_socket_sendto() – it will send a message to a socket, no matter if this socket is connected or not

Date and time related:
+ date_sunset() – it will give you the time of the sunset for a given day and location
+ idate() – it will format the local time and date as an integer
+ date_sunrise() – it will give you the time of the sunrise for a given day and location

+ str_split() – it will convert a string to an array
+ strpbrk() – it will search the string for any set of characters specified

For a full list of the new functions, you can visit the PHP Manual page

* Compatibility Issues
A section, which is vital to a lot of users. PHP 5, for the most part, is backwards compatible with PHP 4. However, there are some things that coders should bear in mind. Here is a set of the most commonly encountered issues:
o array_merge() will now give you warnings if any of the parameters are not arrays. In PHP4, you could get away with merging non-arrays with arrays (and the items would just be added if they were say, a string). Of course it was bad practice to do this to begin with, but it can cause headaches if you don’t know about it.
o As discussed above, objects are now passed by references. If you want to copy an object, make sure to use the clone keyword.
o get_*() now returns names as they were defined. If a class was called MyTestClass, then get_class() would return that — case sensitive! In PHP4, they were always returned in lowercase.
o An object with no properties is no longer considered “empty”.
o In some cases classes must be declared before use. It only happens if some of the new features of PHP 5 (such as interfaces) are used.

Here are some differences I’ve run into during a recent php4 to php5 conversion:

Constructors (+1 for php5)
php4: Constructors are named after their class. If you change the name of a class, you have to find all callers of the constructors. Ew!
php5: Constructors are named __construct. If no __construct method is found, falls back to php4 behavior.

Destructors (+1 for php5)
php4: No such concept.
php5: Destructors are named __destruct.

$this = new Class(…); (+2 for php4)
php4: $this can be reassigned, allowing one to change the class implementing an object. A very useful feature and one I used quite a lot.
php5: Assignment to $this is explicitly forbidden. Factory methods are the recommended substitute, but they’re ugly.

array_shift($args = func_get_args()); (+1 for php4)
php4: If func_get_args() returns [a, b, c], $args is [b, c]–as expected.
php5: If func_get_args() returns [a, b, c], $args is [a, b, c]. Good luck hunting down that bug.

Copying through Assignment (+1 for php4)
$o1 = new Object(…); $o2 = $o1;
$o1->setThing(‘x’); $o2->setThing(‘y’);
php4: $o1 and $o2 are different objects, with Thing set to ‘x’ and ‘y’, respectively. This behavior matches that of strings, numbers, and other non-object types, which are also copied on assignment.
php5: $o1 and $o2 are the same object, with Thing set to ‘y’. This behavior contradicts that of strings, numbers, and other non-object types which do produce copies. A clone operator was introduced to work around this (provided your objects also implement __clone methods); however, the clone operator only works on objects, not strings or numbers, so ensuring you’ve produced a copy is now along the lines of $o2 = is_object($o1) ? clone $o1 : $o1;. Ick.

And some differences which might get used now that I’ve transitioned to php5:

Public, Protected, Private Class Variables (no point)
php4: All class variables are public.
php5: Class variables can have differing access levels. This annoys me, but some people like it.

Class Constants (+0.5 for php5)
php4: No such thing. I work around this, and the lack of namespacing in general, by using Class__CONSTANT.
php5: Has them as Class::CONSTANT. It isn’t namespace support, and has quite a few caveats, but it’s sort of an improvement if you squint just right.

Autoloading (+1 for php5)
php4: No such thing. If you want to load classes, you’d better make sure there are require_once statements all over the place. Or write an object-creation function (make_instance) which automatically loads any class that doesn’t exist. make_instance(‘Class’, …) isn’t nearly as pretty as new Class(…), though.
php5: Autoloading exists, provided you write an __autoload function. No more does require_once need to be littered around one’s code. A marginal savings overall, but still an improvement.

Increase Size of import File in phpmyadmin

Try these different settings in C:\wamp\bin\apache\apache2.2.8\bin\php.ini

post_max_size = 8M
upload_max_filesize = 2M
max_execution_time = 30
max_input_time = 60
memory_limit = 8M

Change to:
post_max_size = 750M
upload_max_filesize = 750M
max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M

Then restart wamp to take effect

FAQs about CakePHP’s Additional Features

1. How can I make my application more secure?

The examples in this article are inherently insecure. Luckily, CakePHP comes with a Sanitize class, which can be used in Cake applications to filter strings or arrays to make them safe for display or insertion into the database.
More information about sanitizing can be found in the CakePHP manual

Regarding validation, it’s possible to make sure that the entered data satisfies particular rules or patterns by adding some validation rules to our model, like this:


VALID_NOT_EMPTY is a constant defined in /cake/libs/validators.php, and can be used to make sure that a particular field is not left blank. CakePHP comes with some predefined constants, but custom constants can be created.

After you define validation rules, all relevant actions and views should be modified accordingly. More information and examples are available in these pages of CakePHP manual

2. Is there any way to turn off Cake’s ‘debugging mode’? Is there a main configuration file?

Yes. A main configuration file, which governs some of CakePHP’s core settings, is located in /app/config/core.php. Some of the settings that can be modified via this file include:

* CakePHP’s debugging verbosity and type
* logging level
* cookies and session duration
* session storage location

3. All the business logic should go in my controllers, but what if I want to re-use something elsewhere?

Good question. You will almost always have to create some complex logic for an application, and you usually want to re-use part of that logic. The most common way to include an application-wide function or variable so that it’s available in every controller is to define it in your AppController file. This file basically consists of an empty class that extends Cake’s internal Controller class, and is located in the /cake/ directory. You can move it to your /app/ directory and create methods that will be available in all of your custom controllers that extend AppController. Even if you’re not planning to use an AppController at first, it’s often wise to create custom controllers which extend AppController rather than the Controller class.

An easy way to create custom classes handling a specific task is to create a component. Components can be loaded automatically in controllers (and only inside controllers) by adding a variable named $components:

var $components = array(‘Session’, ‘MyCustomComponent’);

CakePHP comes with some default components such as Session, which offers convenient ways to organize session data, or RequestHandler, which can be used to determine more information about HTTP requests. These are documented in the CakePHP manual:

* Session component manual pages [13]
* Request Handler component manual pages [14]

4. Does CakePHP require PHP5?

No. CakePHP is 100% compatible with PHP4. Personally, I think this is one of Cake’s main strengths. For example, the __construct() method can be used on PHP4 on all classes extending the Object core class, which is to say nearly everything in CakePHP. Similar patches have been included in the core libraries to offer additional functionality in PHP4 as well. Unfortunately, variables and methods don’t support access modifiers, and a private method should be prefixed with an underscore. This is not just a convention: in a controller, it really means that the method is private. If someone tries to access it (e.g. via http://localhost/notes/_privatemethod/), Cake will return an error.

5. What are CakePHP’s default helpers?

CakePHP comes with some very handy helpers that can really make your life easier when it comes to creating views:

* HTML — allows quick creation of HTML tags, including links and input fields
* JavaScript — offers an easy way to manage JavaScript code
* Number — a set of useful methods to format numeric data
* Time — functions to format time strings and timestamps
* Text — auto-link URLs, truncate strings, create excerpts, highlight, strip links and more
* AJAX — a truly amazing AJAX helper, to be used in conjunction with the popular Prototype and libraries; this helper can really speed up the creation of AJAX interfaces

More information about helpers is available in the CakePHP manual [15].

6. Is there any way to include my custom function/class in Cake?

Sure there is. If you want to use a custom external class, you can put it in the /vendors/ directory and load it into your controller like this:


If you need to define custom application-wide constants or functions, you can place them in /app/config/bootstrap.php, which will make them available everywhere in your application.

You can adapt your code and create a helper or a component to be used in conjunction with views or controllers.

You can also try to integrate other software packages into Cake. An example? Check out the CakeAMFPHP project [16].

7. What if I need to work with more than one table simultaneously?

By default, a NotesController will try to locate and load a Note model class. If your controller needs to access more than its default model, you can define additional models by setting the $uses array, like this:

var $uses = array(Note, AnotherModel, YetAnotherModel);

In some cases, two or more tables might be closely related and would therefore be used with JOIN statements: your notes may have been submitted by different people listed in an authors table, for example. In these cases, CakePHP’s Associations can be used to define complex table relationships directly in your Model class. More information is available in CakePHP manual

8. Is it possible to further customize my application’s URLs?

Yes. Check out the /app/config/routes.php file, and feel free to define or modify your custom routes. For example:

$Route->connect (‘/’, array(‘controller’=>’notes’, ‘action’=>’index’));

This creates a default route for http://localhost/ to:


9. Is there an authentication mechanism in Cake?

Yes and no. There’s no official authentication component, simply because needs can be very different depending on the type of application being developed. There is, however, a built-in Access Control List mechanism involving flat files or databases. More information can be found in CakePHP manual