Dynamically Adding and Removing TinyMCE

First configure TinyMCE, as you wish

tinyMCE.init({ mode: "none", theme: "advanced" });

Here ‘none’ mode sets up TinyMCE without actually transforming any of the textarea.

To add editor to a textarea

tinyMCE.execCommand('mceAddControl', true, "YOUR_TEXTAREA_ID");

To remove editor from a textarea

var editor = tinyMCE.getInstanceById("YOUR_TEXTAREA_ID");
if(editor) {
  if(editor.isHidden()) tinyMCE.remove(editor);
  tinyMCE.execCommand('mceRemoveControl', true, "YOUR_TEXTAREA_ID");
Posted in Editor, html, Javascript | Tagged , , | Leave a comment

Perl :: some approaches to add commas to a long number to make it more readable.

There are many ways to commify long number, i am trying to list some of those.

  1. A Perl extension “Number::Format” for formatting numbers. Number::Format offers a lot of flexibility and is a good choice But its little bit slow.
  2. Tie::Comma – A simple and easy way to format numbers with commas, using a tied hash.
  3. A quick and easy way is::

    1 while $value =~ s/^[-+]?\d+\K(\d{3})/,$1/;
  4. 1 while $value =~ s/(\d+)(\d{3})/$1,$2/;
  5. Without any loop just with fairly straightforward regex

    $value =~ s/[0-9]{1,3}\K(?=(?:[0-9]{3})++(?:[^0-9]|\z))/,/g;
  6. And this is nice one and even faster

    $value = reverse( (reverse $value) =~ s/[0-9]{3}\K(?=[0-9])/,/gr );
Posted in Perl | Tagged , , | Leave a comment

Perl :: How to subtract any number from all elements of a numeric array

I have a numeric array like below :

my $nums = (100, 200, 300, 400, 500);

Now i want to subtract 10 discount from each elements of this array. So that the result become like :

90, 190, 290, 390, 490

map function is my friend here. Using this function i can do my subtract easily.

my @nums = (100, 200, 300, 400, 500);
my $discount = 10;
@nums = map { $_ - $discount } @nums;

print join(', ', @nums);

Now in “nums” array we have our desired numbers. Check it online:: ideone.com/3fSwGS

Posted in Perl | Tagged , , | Leave a comment

Perl :: How to display error messages in browser

We use “die” to print the given string/list and stop the script;
“die” print the string/list to STDERR.

The common use of die in open file ::

open my $file_handler, '>', $file_name 
    or die 'Can not open file';

here if file open fail then “Can not open file” message will print to STDERR and exit the script.

But when we work on Web Application, sometime we need to display fatal (die, confess) errors to the browser.
Then there is a useful Perl core module “CGI::Carp

To display errors in browser we will import the special “fatalsToBrowser” subroutine of CGI::Carp.

use CGI::Carp qw(fatalsToBrowser);

die "Bad error here";

fatal (die, confess) error messages will display in browser.

You may want to active and inactive “fatalsToBrowser”, when you need and it can be done easily.
CGI::Carp uses the package global $WRAP to decide whether to print errors to the browser. So the quick way to inactive ‘fatalsToBrowser’ is:

$CGI::Carp::WRAP = 0;  # Will inactive display error to browser
$CGI::Carp::WRAP = 1;  # Will active   display error to browser

more details about fatalsToBrowser

Posted in Perl | Tagged , , , , | Leave a comment

Practice Backbone.js with PHP :: Example 2

Here you can find first example of backbone.js and php.

In this Example 2, we will improve Example 1 by:

  • Use collection of backbone.js ( collection is ordered sets of models)
  • Using mysql, PDO we will retrieve message list


Download Source

So first of all create a new directory “example_2” in our project directory “php-backbone”, create a new html file “index.html” in this new “example_2” directory. and write following boilerplate html code in this new “index.html” file.

<!DOCTYPE html>
    <title>php backbone.js example 2</title>

    <!-- JavaScript -->
    <script src="../js/jquery-2.0.3.min.js"></script>
    <script src="../js/underscore-min.js"></script>
    <script src="../js/backbone-min.js"></script>    
    <script src="../js/example_2.js"></script>


We have already included “example_2.js” in our “example_2/index.html”, now we need to create this js file in “js” directory. So create “example_2.js” file in js directory.

Now add “MessageModel” model in this file like below

var MessageModel = Backbone.Model.extend({

    defaults: {
        code: 0,
        message: "Test Message"


add “MessageRouter” router and create an object of this router and start history like below

var MessageRouter = Backbone.Router.extend({

    routes: {
        "": "displayMessages"

    displayMessages: function() {


var messageRouter = new MessageRouter();

now we have to check that our model and router are working well or not, in “displayMessages” function create object of model and log its message value.

displayMessages: function() {
    var msg = new MessageModel();

It should display output “Test Message” browser console.

Now we will add backbone.js collection, it is just an ordered sets of models. so write code in “example_2.js” like below.

var MessageCollection = Backbone.Collection.extend({
    model: MessageModel

To test this “MessageCollection”, we will create some object of “MessageModel” and pass the list of model to collection and use a underscore.js iterator “each” function to retrieve data of “MessageCollection”.
So modify the “displayMessages” function like below.

displayMessages: function() {

    var msg1 = new MessageModel({ code: "001", message: "Registration Successfully " });
    var msg2 = new MessageModel({ code: "002", message: "Registration Failed" });
    var msg3 = new MessageModel({ code: "003", message: "Login Successfully" });
    var msg4 = new MessageModel({ code: "003", message: "Login Failed" });

    var messageCollection = new MessageCollection([ msg1, msg2, msg3, msg4]);

    _.each(messageCollection.models, function (msg) {
        console.log( "code => "+ msg.get("code") +", message => "+ msg.get("message"));


Output in the console will like below.

code => 001, message => Registration Successfully
code => 002, message => Registration Failed
code => 003, message => Login Successfully
code => 003, message => Login Failed

Now we will work for view. so at first in “/example_2/index.html” we will add a div for contain message list and add a template for render each message item.
so add below code in index.html.

<div id="messageList"></div>

<!-- Templates -->
<script type="text/template" id="tpl-message-item">
    <a href="#" id="<%= code %>"><%= message %></a>

In “js/example_2.js” file we will create two views, one for message list and another for message item. So add below two views in this file.

var MessageListView = Backbone.View.extend({

    tagName: "ul",
    render: function(eventName) {
        _.each(this.model.models, function (msg) {
            $(this.el).append(new MessageListItemView({model:msg}).render().el);
        }, this);
        return this;


var MessageListItemView = Backbone.View.extend({



    render:function (eventName) {
        return this;


And change the function “displayMessages” like below.

displayMessages: function() {

    var msg1 = new MessageModel({ code: "001", message: "Registration Successfully " });
    var msg2 = new MessageModel({ code: "002", message: "Registration Failed" });
    var msg3 = new MessageModel({ code: "003", message: "Login Successfully" });
    var msg4 = new MessageModel({ code: "003", message: "Login Failed" });

    var messageCollection = new MessageCollection([msg1, msg2, msg3, msg4]);

    var messageListView = new MessageListView({model:messageCollection});

From browser access “example_2”, then you will get output in our browser like below.

PHP Backbone Output

PHP Backbone Output

Now we have to a simple thing that retrieve message list from mysql database by php and display it, our model, controller, view and router all are all most ready. so in our mysql database create a new table and insert new data using below script.

  `code` int(11) NOT NULL,
  `message` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)

INSERT INTO `messages` (`id`, `code`, `message`) VALUES
(1, 100, 'Continue'),
(2, 101, 'Switching Protocols'),
(3, 102, 'Processing'),
(4, 200, 'OK'),
(5, 201, 'Created'),
(6, 203, 'Non-Authoritative Information'),
(7, 204, 'No Content'); 

You will also find this sql script with source “db/messages.sql”.

Then create a new php file “example_2.php” in api and write code like below.

function getMessages() {
    $sql = "select * FROM messages ORDER BY code";
    try {
        $db = getConnection();
        $stmt = $db->query($sql);
        $messages = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($messages);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
function getConnection() {
    $dbhost="localhost"; // Your Host Name, For Me It localhost
    $dbuser="root";      // User Name, For Me It root
    $dbpass="root";      // Password, For Me It root    
    $dbname="test";      // Database Name, For Me It test
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    return $dbh;

Change $dbhost, $dbuser, $dbpass, $dbname as yours.
In above “getConnection()” function, its simple, we just connect to the database and return the handler using PDO.
In “getMessages” function we just retrieve messages as object and return the json result set.

In example_2.js we have to add the url to the Collection class “MessageCollection ” like below.

var MessageCollection = Backbone.Collection.extend({

    model: MessageModel,
    url: "../api/example_2.php"


Now we have to fetch messages, So change the “displayMessages” function like below.

displayMessages: function() {

   var messageCollection = new MessageCollection();

   var messageListView = new MessageListView({model:messageCollection});
       success: function () {

So if you access this example “example_2” then we will get output like below.

PHP Backbone Output

PHP Backbone Output

If you have any question, feel free to ask in comment.


Download Source

Posted in backbone.js, mysql, PHP, underscore.js | Tagged , , , , , | 6 Comments

ZCE Preparation :: PHP 5.3 Security


  • PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server.
    These properties make anything run on a web server insecure by default.
  • Correct selection of compile-time and runtime configuration options, and proper coding practices will give combination of freedom and security need.
  • A large selection of options guarantees you can use PHP for a lot of purposes, but it also means there are combinations of these options and server configurations that result in an insecure setup.
  • The configuration flexibility of PHP is equally rivalled by the code flexibility.

General considerations

  • A completely secure system is a virtual impossibility, so an approach often used in the security profession is one of balancing risk and usability.

Installed as CGI binary

Possible attacks

  • If the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:
    1. Accessing system files:
      http://my.host/cgi-bin/php?/etc/passwd The query information in a URL after the question mark (?) is passed as command line arguments to the interpreter by the CGI interface.
      Usually interpreters open and execute the file specified as the first argument on the command line.
      When invoked as a CGI binary, PHP refuses to interpret the command line arguments.
    2. Accessing any web document on server:
      http://my.host/cgi-bin/php/secret/doc.html The path information part of the URL after the PHP binary name, /secret/doc.html is conventionally used to specify the name of the file to be opened and interpreted by the CGI program.
      Usually some web server configuration directives (Apache: Action) are used to redirect requests to documents like http://my.host/secret/script.php to the PHP interpreter.
      With this setup, the web server first checks the access permissions to the directory /secret, and after that creates the redirected request http://my.host/cgi-bin/php/secret/script.php.
      Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php, but only for the /cgi-bin/php file.
      This way any user able to access /cgi-bin/php is able to access any protected document on the web server.
      In PHP, runtime configuration directives cgi.force_redirect, doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions.
    3. Under possible attacks, there are attacks on the php file themselves.
      Some php viruses, (injecktor and variations) scan the visible directory tree for php and/or html files, then inject code (such as spam-ware to generate fraudulent page hits) into otherwise harmless and useful .php scripts.
      One way to block this is by using open_basedir to restrict the visible file system directories to directory tree(s) which do NOT contain any .php scripts. (see doc page “Description of core php.ini directives” Note under open_basedir to tighten open_basedir scope from /www/ which would contain .php scripts to /www/tmp/ which would protect any scripts in /www/ from modification.)
      If the php.ini is outside the open_basedir tree, than a malware php script has no way to alter the core web site files, even if it were succesfully uploaded via ftp or other mechanism.
      The damage done by the spam-ware may seem trivial, but as browsers and virus programs eventually recognize the spam-ware the web site becomes effectively completely blocked and un-browsable.
  • Case 1: only public files served
    1. If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options.
    2. If your web server does not allow you to do redirects, or the server does not have a way to communicate to the PHP binary that the request is a safely redirected request, you can specify the option “–enable-force-cgi-redirect” to the configure script.
    3. You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php nor by redirection http://my.host/dir/script.php.
    4. Redirection can be configured in Apache by using AddHandler and Action directives
  • Case 2: using cgi.force_redirect
    1. The configuration directive cgi.force_redirect prevents anyone from calling PHP directly with a URL like http://my.host/cgi-bin/php/secretdir/script.php.
    2. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule.
    3. Usually the redirection in the Apache configuration is done with the following directives:
      Action php-script /cgi-bin/php
      AddHandler php-script .php
    4. If your web server does not support any way of telling if the request is direct or redirected, you cannot use this option and you must use one of the other ways of running the CGI version.
    5. Note that force-redirect doesn’t work with IIS at all; it’ll tell you to go away, as IIS doesn’t supply the right variables to PHP. php.ini tells you to turn it off, so make sure you do.
  • Case 3: setting doc_root or user_dir
    1. To include active content, like scripts and executables, in the web server document directories is sometimes considered an insecure practice.
      If, because of some configuration mistake, the scripts are not executed but displayed as regular HTML documents, this may result in leakage of intellectual property or security information like passwords.
    2. Therefore many sysadmins will prefer setting up another directory structure for scripts that are accessible only through the PHP CGI, and therefore always interpreted and not displayed as such.
    3. Also if the method for making sure the requests are not redirected, as described in the previous section, is not available, it is necessary to set up a script doc_root that is different from web document root.
    4. You can set the PHP script document root by the configuration directive doc_root in the configuration file,
      or you can set the environment variable PHP_DOCUMENT_ROOT.
      If it is set, the CGI version of PHP will always construct the file name to open with this doc_root and the path information in the request,
      so you can be sure no script is executed outside this directory (except for user_dir).
    5. Another option usable here is user_dir. When user_dir is unset, only thing controlling the opened file name is doc_root.
      Opening a URL like http://my.host/~user/doc.php does not result in opening a file under users home directory, but a file called ~user/doc.php under doc_root (yes, a directory name starting with a tilde [~]).
    6. If user_dir is set to for example public_php, a request like http://my.host/~user/doc.php will open a file called doc.php under the directory named public_php under the home directory of the user.
      If the home of the user is /home/user, the file executed is /home/user/public_php/doc.php.
    7. user_dir expansion happens regardless of the doc_root setting, so you can control the document root and user directory access separately.
  • Case 4: PHP parser outside of web tree
    1. A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In /usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:

      as the first line of any file containing PHP tags.

    2. You will also need to make the file executable.
      That is, treat it exactly as you would treat any other CGI script written in Perl or sh or any other common scripting language which uses the #! shell-escape mechanism for launching itself.
    3. To get PHP to handle PATH_INFO and PATH_TRANSLATED information correctly with this setup, the PHP parser should be compiled with the –enable-discard-path configure option.

Installed as an Apache module

  • When PHP is used as an Apache module it inherits Apache’s user permissions (typically those of the “nobody” user).
    This has several impacts on security and authorization.
    For example, if you are using PHP to access a database, unless that database has built-in access control, you will have to make the database accessible to the “nobody” user.
    This means a malicious script could access and modify the database, even without a username and password.
    It’s entirely possible that a web spider could stumble across a database administrator’s web page, and drop all of your databases.
    You can protect against this with Apache authorization, or you can design your own access model using LDAP, .htaccess files, etc. and include that code as part of your PHP scripts.
  • Often, once security is established to the point where the PHP user (in this case, the apache user) has very little risk attached to it, it is discovered that PHP is now prevented from writing any files to user directories.
    Or perhaps it has been prevented from accessing or changing databases.
    It has equally been secured from writing good and bad files, or entering good and bad database transactions.
  • A frequent security mistake made at this point is to allow apache root permissions, or to escalate apache’s abilities in some other way.
  • Escalating the Apache user’s permissions to root is extremely dangerous and may compromise the entire system, so sudo’ing, chroot’ing, or otherwise running as root should not be considered by those who are not security professionals.
  • There are some simpler solutions. By using open_basedir you can control and restrict what directories are allowed to be used for PHP. You can also set up apache-only areas, to restrict all web based activity to non-user, or non-system, files.

Filesystem Security

  • PHP is subject to the security built into most server systems with respect to permissions on a file and directory basis. This allows you to control which files in the filesystem may be read.
    Care should be taken with any files which are world readable to ensure that they are safe for reading by all users who have access to that filesystem.
  • Since PHP was designed to allow user level access to the filesystem, it’s entirely possible to write a PHP script that will allow you to read system files such as /etc/passwd, modify your ethernet connections, send massive printer jobs out, etc.
    This has some obvious implications, in that you need to ensure that the files that you read from and write to are the appropriate ones.
  • Example::
    Consider the following script, where a user indicates that they’d like to delete a file in their home directory.
    This assumes a situation where a PHP web interface is regularly used for file management, so the Apache user is allowed to delete files in the user home directories.
    #1 Poor variable checking leads to….

    // remove a file from the user's home directory
    $username = $_POST['user_submitted_name'];
    $userfile = $_POST['user_submitted_filename'];
    $homedir  = "/home/$username";
    echo "The file has been deleted!";

    Since the username and the filename are postable from a user form, they can submit a username and a filename belonging to someone else, and delete it even if they’re not supposed to be allowed to do so.

  • In this case, you’d want to use some other form of authentication.
    Consider what could happen if the variables submitted were “../etc/” and “passwd”.
    The code would then effectively read:
    #2 … A filesystem attack

    // removes a file from anywhere on the hard drive that
    // the PHP user has access to. If PHP has root access:
    $username = $_POST['user_submitted_name']; // "../etc"
    $userfile = $_POST['user_submitted_filename']; // "passwd"
    $homedir  = "/home/$username"; // "/home/../etc"
    unlink("$homedir/$userfile"); // "/home/../etc/passwd"
    echo "The file has been deleted!";

    There are two important measures you should take to prevent these issues.
    Only allow limited permissions to the PHP web user binary.
    Check all variables which are submitted.

  • Here is an improved script:
    #3 More secure file name checking

    // removes a file from the hard drive that
    // the PHP user has access to.
    $username = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
    $userfile = basename($_POST['user_submitted_filename']);
    $homedir  = "/home/$username";
    $filepath = "$homedir/$userfile";
    if (file_exists($filepath) && unlink($filepath)) {
        $logstring = "Deleted $filepath\n";
    } else {
        $logstring = "Failed to delete $filepath\n";
    $fp = fopen("/home/logging/filedelete.log", "a");
    fwrite($fp, $logstring);
    echo htmlentities($logstring, ENT_QUOTES);
  • However, even this is not without its flaws.
    If your authentication system allowed users to create their own user logins, and a user chose the login “../etc/”, the system is once again exposed. For this reason, you may prefer to write a more customized check:

    $username     = $_SERVER['REMOTE_USER']; // using an authentication mechanisim
    $userfile     = $_POST['user_submitted_filename'];
    $homedir      = "/home/$username";
    $filepath     = "$homedir/$userfile";
    if (!ctype_alnum($username) || !preg_match('/^(?:[a-z0-9_-]|\.(?!\.))+$/iD', $userfile)) {
        die("Bad username/filename");
  • Depending on your operating system, there are a wide variety of files which you should be concerned about, including device entries (/dev/ or COM1), configuration files (/etc/ files and the .ini files), well known file storage areas (/home/, My Documents), etc. For this reason, it’s usually easier to create a policy where you forbid everything except for what you explicitly allow.
  • I note that the php standard error printing includes “filename”, which appears to always be the /full/folder/path/and/filename.
    And on all unix systems and by common practice on many windows systems, the /home/(control panel login id)/ is part of the folder path, and on most hosts the same account login id is the control panel login id.
    So any error message effectively exposes to the world the control panel login id.
    From there a hacker and brute force can break any password in time.
    PHP does not appear to have a way to disable displaying the actual physical directory structure from appearing in error messages, which even is no login id were there, is a security problem.
    One can direct the error to a log file, but that still exposes critical information to contract web programmers.
    Typical practice is to give web programmers limited ftp access to a web directory, but then php defeats this restriction by displaying the entire directory structure in the error message to the web developer who you tried to give restricted access to.
    And 9 time out of ten also gave away the control panel login in id.
    So all the wise script writing in the world cannot obscure the private information the php error printing is giving out. Can it?
  • you should check requested file name for back path.a person can delete your code file by going back to root directory.
    for ex:- deletefile.php?file=../index.php
    if no proper check for / or \\ any user can delete your index page or any usefull file.
    you may use following function to check for back path.

    function existBackPath($file){    
        return preg_match('[\\/]', $file); 

    if existBackPath function returns 1.It means someone is trying to delete file which does not exist in his/her directory rather it exist in your root directory.

  • Whenever you connect to a database with a password hard coded into your script, make sure you put the script off of your web document tree.
    Put the script somewhere where apache won’t serve documents, and then include/require this file in your other scripts.
    That way, if the server ever gets misconfigured, it won’t serve your PHP scripts with passwords, etc. as plain text for all to see.
  • Common and simple way to avoid path attack is separating objectname and filesystem space when possible. For example if I have users on my site and directory per user solution is not “httpdocs/users/$login”, but “httpdocs/users/”.md5($login) or “httpdocs/users/”.$userId

Null bytes related issues

  • As PHP uses the underlying C functions for filesystem related operations, it may handle null bytes in a quite unexpected way.
    As null bytes denote the end of a string in C, strings containing them won’t be considered entirely but rather only until a null byte occurs.\
    The following example shows a vulnerable code that demonstrates this problem:

    #1 Script vulnerable to null bytes
    $file = $_GET['file']; // "../../etc/passwd\0"
    if (file_exists('/home/wwwrun/'.$file.'.php')) {
        // file_exists will return true as the file /home/wwwrun/../../etc/passwd exists
        include '/home/wwwrun/'.$file.'.php';
        // the file /etc/passwd will be included
  • Therefore, any tainted string that is used in a filesystem operation should always be validated properly. Here is a better version of the previous example:
    #2 Correctly validating the input
    $file = $_GET['file']; 
    // Whitelisting possible values
    switch ($file) {
        case 'main':
        case 'foo':
        case 'bar':
            include '/home/wwwrun/include/'.$file.'.php';
            include '/home/wwwrun/include/main.php';

Database Security

  • As you can surmise, PHP cannot protect your database by itself.
  • Keep in mind this simple rule: defense in depth.
    The more places you take action to increase the protection of your database, the less probability of an attacker succeeding in exposing or abusing any stored information.
    Good design of the database schema and the application deals with your greatest fears.

Designing Databases

  • The first step is always to create the database, unless you want to use one from a third party.
    When a database is created, it is assigned to an owner, who executed the creation statement.
    Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.

Note:: World best PHP document is PHP Manual, so almost of all i am taking from there.

Posted in PHP, ZCE | Tagged , , , , , | Leave a comment

Practice Backbone.js with PHP :: Example 1

Assume that you have basic knowledge on php, backbone.js, underscore.js and jquery.
We will use Firefox browser with firebug to test.

Actually here we will learn how to use model, view and router of backbone.js and fetch data from server using php.


Download Source

First of all we will create directory structure.

    |-> php-backbone
        |-> js
            |-> jquery-2.0.3.min.js
            |-> underscore-min.js
            |-> backbone-min.js
        |-> api
        |-> example_1        

create above directory structure in you web_root. and put those js files in js directory (those will be found in source, link at bottom or you can get those by google).

now we will create a Boilerplate in example_1 directory named “index.html”, so create a new index.html file under example_1 directory and write below code in this file.

<!DOCTYPE html>
    <title>php backbone.js example 1</title>

    <!-- JavaScript -->
    <script src="../js/jquery-2.0.3.min.js"></script>
    <script src="../js/underscore-min.js"></script>
    <script src="../js/backbone-min.js"></script>    


Backbone’s only hard dependency is Underscore.js ( >= 1.5.0). For RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View, include jQuery, and json2.js for older Internet Explorer support. (Mimics of the Underscore and jQuery APIs, such as Lo-Dash and Zepto, will also tend to work, with varying degrees of compatibility.)

Now create an new example_1.js file in js directory, and include it at bottom of all script to our Boilerplate index.html file, then our index.html file will look like below.

<!DOCTYPE html>
    <title>php backbone.js example 1</title>

    <!-- JavaScript -->
    <script src="../js/jquery-2.0.3.min.js"></script>
    <script src="../js/underscore-min.js"></script>
    <script src="../js/backbone-min.js"></script>    
    <script src="../js/example_1.js"></script>


and open it with you favorite editor.
In example_1.js, we will first create a “Message” model, and add a default property called “message” like below.

var MessageModel = Backbone.Model.extend({    
    defaults: {
        message: "Text Message"

Now we will access our example_1 to test that is our model working or not. so url http://localhost/php-backbone/example_1/ on FireFox (this url for mine as i follow above directory structure so your url can not be like it, so use your url to access example_1). Open Firebug console, create a object of MessageModel and access its message property like below.

var msg = new MessageModel();

run this and will get output like below screenshot.

backbone.js, php

model default property access

After above model build backbone router like below.

var MessageRouter = Backbone.Router.extend({
        "": "displayMessage"
    displayMessage: function() {
        var messageModel = new MessageModel();

var messageRouter = new MessageRouter();

here we build a router and added a route and assigned a function “displayMessage”, in this function we created a model object for “MessageModel” and print its “message” property in console.
to execute this router we created object of this router. then we start backbone history to ask backbone to monitoring hashchange events, and dispatching routes.

Now if you access this example_1 from browser then you will see output “Text Message” on firebug console.

To create View, first we need to change our index.html under example_1 directory.
in body tag, we will add a div tag in which we will display our message, and a template which will use to contain message text. so add below html come in body tag before script tags.

    <div id="msg"></div>

    <!-- Templates -->
    <script type="text/template" id="tpl-hello-backbone">
        <%= message %>

here in template “<%= … %>” used to interpolate variable message.
So our template is ready, now we will create backbone view. add below code in example_1.js after model code.

var MessageView = Backbone.View.extend({


    render:function (eventName) {
        return this;

here we assigned javascript template and created render function which used to render the view template from model data.
Now we have to call this render function from router function “displayMessage”. change this function as below.

    displayMessage: function() {
        var messageModel = new MessageModel();        
        var messageView = new MessageView({model:messageModel});        

here we created object of MessageView with our messageModel. and called view’s render function and put its output in our “#msg” div. there “el” is a DOM element which created from the view’s tagName, className, id and attributes properties, if specified. If not, el is an empty div.

Now if you access example_1 then you will see “Text Message” in browser.

Above we completed below steps::

1) Build directory structure
2) Created Boilerplate for backbone.js
3) Created backbone.js model
4) Created backbone.js router
5) Created backbone.js view

Now its time to get data from server (using php) and display it, we have already completed most of work, now we will just fetch data from server using our MessageModel.

Create “example_1.php” file in api directory and write one code in it like below.

echo '{"message":"Hello Backbonejs"}';

here we just echo a string followed by json structure.

Then we need modify our model little bit that just add “urlRoot” property with vlaue “../api/example_1.php”, so change our model like below.

var MessageModel = Backbone.Model.extend({
    urlRoot : '../api/example_1.php',
    defaults: {
        message: "Text Message"

Then change the “displayMessage” function in backbone router like below.

    displayMessage: function() {
        var messageModel = new MessageModel();

        var messageView = new MessageView({model:messageModel});
            success: function () {

here we only use “messageModel.fetch()” function to collect data for this model from server. and after successful fetch we are calling render function. now if you access exmaple_1 then you can see output “Hello Backbonejs” in your browser.

if you can see this text then Congratulation 🙂 , if not then you can post comment, we will fix it together.


Download Source

Here you can find Second example of backbone.js and php.

Posted in backbone.js, PHP, underscore.js | Tagged , , , , , | 4 Comments