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

Demo

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>
<html>
<head>
    <title>php backbone.js example 2</title>
</head>
<body>    

    <!-- 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>

</body>
</html>

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();
Backbone.history.start();

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();
    console.log(msg.toJSON());
}

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>
</script>

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({

    tagName:"li",

    template:_.template($('#tpl-message-item').html()),

    render:function (eventName) {
        $(this.el).html(this.template(this.model.toJSON()));
        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});
      
    $('#messageList').html(messageListView.render().el);
}

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.

CREATE TABLE IF NOT EXISTS `messages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` int(11) NOT NULL,
  `message` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=8;

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.

getMessages();
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);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    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});
   messageCollection.fetch({
       success: function () {
           $('#messageList').html(messageListView.render().el);
       }
   });
}

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.

Demo

Download Source

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

ZCE Preparation :: PHP 5.3 Security

Introduction

  • 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:
      #!/usr/local/bin/php
      

      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….

    <?php
    // remove a file from the user's home directory
    $username = $_POST['user_submitted_name'];
    $userfile = $_POST['user_submitted_filename'];
    $homedir  = "/home/$username";
    
    unlink("$homedir/$userfile");
    
    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

    <?php
    // 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

    <?php
    // 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);
    fclose($fp);
    
    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:

    <?php
    $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");
    }
    //etc...
    ?>
    
  • 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.

    <?php 
    function existBackPath($file){    
        $file=str_replace("\\\\","/",$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
    <?php
    $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
    <?php
    $file = $_GET['file']; 
    
    // Whitelisting possible values
    switch ($file) {
        case 'main':
        case 'foo':
        case 'bar':
            include '/home/wwwrun/include/'.$file.'.php';
            break;
        default:
            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.

Demo

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>
<html>
<head>
    <title>php backbone.js example 1</title>
</head>
<body>    

    <!-- 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>    

</body>
</html>

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>
<html>
<head>
    <title>php backbone.js example 1</title>
</head>
<body>    

    <!-- 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>

</body>
</html>

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();
msg.get('message');

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({
    routes:{
        "": "displayMessage"
    },
    displayMessage: function() {
        var messageModel = new MessageModel();
        console.log(messageModel.get("message"));        
    }
});

var messageRouter = new MessageRouter();
Backbone.history.start();

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 %>
    </script>

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({

    template:_.template($('#tpl-hello-backbone').html()),

    render:function (eventName) {
        $(this.el).html(this.template(this.model.toJSON()));
        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});        
        $('#msg').html(messageView.render().el);
    }

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.

<?php
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});
        messageModel.fetch({
            success: function () {
                $('#msg').html(messageView.render().el);
            }
        });
    }

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.

Demo

Download Source

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

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

Plugin for speed up coding

Are you using Zen-Coding? if not please try it, i am sure you will fall in love.

Zen Coding is an editor plugin for high-speed HTML, XML, XSL (or any other structured code format) coding and editing. The core of this plugin is a powerful abbreviation engine which allows you to expand expressions—similar to CSS selectors—into HTML code. For example:

div#page>div.logo+ul#navigation>li*5>a

…can be expanded into:

<div id="page">
    <div class="logo"></div>
    <ul id="navigation">
          <li><a href=""></a></li>
          <li><a href=""></a></li>
          <li><a href=""></a></li>
          <li><a href=""></a></li>
          <li><a href=""></a></li>
    </ul>
</div>

download link:: https://code.google.com/p/zen-coding/

download cheat sheet:: https://code.google.com/p/zen-coding/wiki/CheatSheets

tutorial + one video:: http://coding.smashingmagazine.com/2009/11/21/zen-coding-a-new-way-to-write-html-code/

some useful link for practice::
1) http://code.google.com/p/zen-coding/wiki/ZenHTMLElementsEn
1) http://code.google.com/p/zen-coding/wiki/ZenCSSPropertiesEn

Zen Coding support for your favorite editor, so enjoy your front-end coding now 🙂

Current Link:: Emmet

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

ZCE Preparation :: PHP 5.3 Types

PHP supports eight primitive types. but they are generally divided in two categories: scalar and composite.

A scalar value contains only one value at a time. compound data types are essentially containers of other data.

Four scalar types:

  1. boolean
  2. integer
  3. float (floating-point number, aka double)
  4. string

Two compound types:

  1. array
  2. object

And finally two special types:

  1. resource
  2. NULL

PHP introduces some pseudo-types for readability reasons:

  1. mixed
  2. number
  3. callback
  • The type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.
  • To check the type and value of an expression, use the var_dump() function.
  • To get a human-readable representation of a type for debugging, use the gettype() function.
  • To check for a certain type, do not use gettype(), but rather the is_type functions.
  • To forcibly convert a variable to a certain type, either cast the variable or use the settype() function on it.

Some examples:

<?php
$a_bool = TRUE;   // a boolean
$a_str  = "foo";  // a string
$a_str2 = 'foo';  // a string
$an_int = 12;     // an integer

echo gettype($a_bool); // prints out:  boolean
echo gettype($a_str);  // prints out:  string

// If this is an integer, increment it by four
if (is_int($an_int)) {
    $an_int += 4;
}

// If $a_bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool)) {
    echo "String: $a_bool";
}
?>

If we use gettype() before initializinf any variable it give NULL, for eg.

<?php 
$foo; 
echo gettype($foo); 
?>

it will show:
NULL

Booleans

  • This is the simplest type.
  • A boolean expresses a truth value.
  • A Boolean datum can only contain two values: true or false.
  • Generally speaking, Booleans are used as the basis for logical operations.
  • True is usually given a value of 1, and False is given a value of zero.
    $true_value = 1;
    $false_value = 0;
    

    You can replace the 1 and 0 with the words “true” and “false” (without the quotes).

  • If we echo true then it will display 1.
  • If we echo false then it will display nothing.
  • To specify a boolean literal, use the keywords TRUE or FALSE. Both are case-insensitive.
  • To explicitly convert a value to boolean, use the (bool) or (boolean) casts.
  • When converting to boolean, the following values are considered FALSE:
    1. the boolean FALSE itself
    2. the integer 0 (zero)
    3. the float 0.0 (zero)
    4. the empty string, and the string “0”
    5. an array with zero elements
    6. an object with zero member variables (PHP 4 only)
    7. the special type NULL (including unset variables)
    8. SimpleXML objects created from empty tags
    9. Every other value is considered TRUE (including any resource).
    10. -1 is considered TRUE, like any other non-zero (whether negative or positive) number!

Some Examples:

<?php
var_dump((bool) "");        // bool(false)
var_dump((bool) 1);         // bool(true)
var_dump((bool) -2);        // bool(true)
var_dump((bool) "foo");     // bool(true)
var_dump((bool) 2.3e5);     // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array());   // bool(false)
var_dump((bool) "false");   // bool(true)
?>
<?php
// Consider that the 0 could by any parameters including itself
var_dump(0 == 1); // false
var_dump(0 == (bool)'all'); // false
var_dump(0 == 'all'); // TRUE, take care
var_dump(0 === 'all'); // false

// To avoid this behavior, you need to cast your parameter as string like that :
var_dump((string)0 == 'all'); // false
?>
<?php
$a = !array();      // This will === true;
$a = !array('a');   // This will === false;
$a = !!array();   // This will === false; (as expected)
$s = !"";           // This will === true;
$s = !"hello";      // This will === false;
$s = (true == 'false'); // this will === true;
?>
<?php
echo false;           // will display nothing  
echo (false);         // will display nothing
echo false+false;     // 0, 0+0=0
echo (false+false);   // 0, (0+0)=0
echo intval(false);   // 0
echo '"'.false.'"';   // "", nothing for false

echo true;            // 1
echo (true);          // 1
echo true+true;       // 2, 1+1=2
echo (true+true);     // 2, (1+1)=2
echo intval(true);    // 1
echo '"'.true.'"';    // "1"
?>
<?php
$x=TRUE;
$y=FALSE;
$z=$y OR $x;
echo $z;    // $z=0, display nothing
?>

Integers

  • An integer is a number of the set ℤ = {…, -2, -1, 0, 1, 2, …}.
  • Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +).
  • To use octal notation, precede the number with a 0 (zero).
  • To use hexadecimal notation precede the number with 0x.
  • Binary integer literals are available since PHP 5.4.0.
  • To use binary notation precede the number with 0b.
  • Integer literals
    <?php
    $a = 1234; // decimal number
    $a = -123; // a negative number
    $a = 0123; // octal number (equivalent to 83 decimal)
    $a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
    ?>
    
  • Formally, the structure for integer literals is:
    decimal     : [1-9][0-9]*
                | 0
    
    hexadecimal : 0[xX][0-9a-fA-F]+
    
    octal       : 0[0-7]+
    
    binary      : 0b[01]+
    
    integer     : [+-]?decimal
                | [+-]?hexadecimal
                | [+-]?octal
                | [+-]?binary
    
  • The size of an integer is platform-dependent.
  • 64-bit platforms usually have a maximum value of about two billion is the usual value.
  • 64-bit platforms usually have a maximum value of about 9E18.
  • PHP does not support unsigned integers. UnSigned can hold a larger positive value, and no negative value.
  • Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.
  • If an invalid digit is given in an octal integer (i.e. 8 or 9), the rest of the number is ignored.
    <?php
    var_dump(01090); // 010 octal = 8 decimal
    ?>
    
  • If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead.
    Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

    <?php
    ###Integer overflow on a 32-bit system###
    
    $large_number = 2147483647;
    var_dump($large_number);                     // int(2147483647)
    
    $large_number = 2147483648;
    var_dump($large_number);                     // float(2147483648)
    
    $million = 1000000;
    $large_number =  50000 * $million;
    var_dump($large_number);                     // float(50000000000)
    
    ###Integer overflow on a 64-bit system###
    
    $large_number = 9223372036854775807;
    var_dump($large_number);                     // int(9223372036854775807)
    
    $large_number = 9223372036854775808;
    var_dump($large_number);                     // float(9.2233720368548E+18)
    
    $million = 1000000;
    $large_number =  50000000000000 * $million;
    var_dump($large_number);                     // float(5.0E+19)
    ?>
    
  • There is no integer division operator in PHP.
    1/2 yields the float 0.5.
    The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.

    <?php
    var_dump(25/7);         // float(3.5714285714286) 
    var_dump((int) (25/7)); // int(3)
    var_dump(round(25/7));  // float(4) 
    ?>
    
  • To explicitly convert a value to integer, use either the (int) or (integer) casts.
  • A value can also be converted to integer with the intval() function.
  • Converting from booleans, FALSE will yield 0 (zero), and TRUE will yield 1 (one).
  • When converting from float to integer, the number will be rounded towards zero.
    If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31 on 32-bit platforms and +/- 9.22e+18 = 2^63 on 64-bit platforms), the result is undefined,
    since the float doesn’t have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens!
  • Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.
    <?php
    echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
    ?>
    

    This happens because the result of this simple arithmetic expression is stored internally as 7.999999 instead of 8;
    when the value is converted to int, PHP simply truncates away the fractional part.

  • Converting from other types:
    The behaviour of converting to integer is undefined for other types.
    Do not rely on any observed behaviour, as it can change without notice.
  • Example ::
    $x = "11";
    (int) $x;      // int(11)
    intval($x);    // int(11)
    $x + 0;        // int(11)
    
    $x = "0x11";
    (int) $x;      // int(0)
    intval($x);    // int(0)
    $x + 0;        // int(17) !
    
    $x = "011";
    (int) $x;      // int(11)
    intval($x);    // int(11)
    $x + 0;        // int(11) (not 9)
    
    intval(042);   // 34, convert to octal
    

Floating point numbers

  • Floating point numbers known as “floats”, “doubles”, or “real numbers”.
  • Floats are numbers that have a fractional component.
  • like integers, they are also signed.
  • syntaxes ::
    <?php
    $a = 1.234;    // Decimal
    $b = 1.2e3;    // Exponential 
    $c = 7E-10;    // Exponential
    ?>
    
  • Formally, the structure for Float literals is:
    LNUM          [0-9]+
    DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
    EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})
    
  • The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).
  • Examples ::
    <?php
    $a = 1.23456789;
    $b = 1.23456780;
    $epsilon = 0.00001;
    
    if(abs($a-$b) < $epsilon) {
        echo "true";
    }
    
    
    $a = 5.00500;    //5.005
    $b = 30.00;      //30
    ?>
    
  • Some numeric operations can result in a value represented by the constant NAN.
    This result represents an undefined or unrepresentable value in floating-point calculations.
  • Any loose or strict comparisons of this value against any other value, including itself, will have a result of FALSE.
  • Because NAN represents any number of different values, NAN should not be compared to other values, including itself, and instead should be checked for using is_nan().

Strings

  • Strings are, in fact, ordered collections of binary data—this could be text, but it could also be the contents of an image file, a spreadsheet, or even a music recording.
  • A string is series of characters, where a character is the same as a byte.
  • PHP only supports a 256-character set, and hence does not offer native Unicode support.
  • string can be as large as 2GB.

We will study String in a individual article.

Arrays

  • An array in PHP is actually an ordered map. A map is a type that associates values to keys.
  • This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.
  • Arrays are containers of ordered data elements.
  • An array can be used to store and retrieve any other data type, including numbers, Boolean values, strings, objects and even other arrays.
  • As array values can be other arrays, trees and multidimensional arrays are also possible.

We will study Arrays in a individual article.

Objects

  • Objects are containers of both data and code.
  • To create a new object, use the new statement to instantiate a class:
    <?php
    class foo {
        function do_foo() {
            echo "Doing foo."; 
        }
    }
    
    $bar = new foo;
    $bar->do_foo();
    ?>
    
  • If an object is converted to an object, it is not modified.
  • If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.
    <?php
    $obj = (object) 'ciao';
    echo $obj->scalar;  // outputs 'ciao'
    ?>
    
  • If the value was NULL, the new instance will be empty.
  • Arrays convert to an object with properties named by keys, and corresponding values.
    $x = (object) array('a'=>'A', 'b'=>'B', 'C');
    /*
    stdClass Object
    (
        [a] => A
        [b] => B
        [0] => C
    )
    */
    
    $x->a;    // A
    $x->b;    // B
    $x->{0};  // PHP Notice: Undefined property: stdClass::$0
    
    $obj = (object)array("Test" => "bar")
    $var = "Test";
    $obj->$var;    // bar
    

We will study Objects in a individual article.

Resources

  • The resource data type is used to indicate external resources that are not used natively by PHP, but that have meaning in the context of a special operation— such as, for example, handling files or manipulating images.
  • A resource is a special variable, holding a reference to an external resource.
  • Resources are created and used by special functions.
  • As resource variables hold special handlers to opened files, database connections, image canvas areas and the like, converting to a resource makes no sense.
  • a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.
  • Persistent database links are an exception to this rule. They are not destroyed by the garbage collector.

NULL

  • The special NULL value represents a variable with no value. NULL is the only possible value of type null.
  • is the case-insensitive constant NULL.
  • A variable is considered to be null if:
    1. it has been assigned the constant NULL.
    2. it has not been set to any value yet.
    3. it has been unset().
  • There is only one value of type null.
    <?php
    $var = NULL;       
    ?>
    
  • Example ::
    <?php
    $a = array();
    
    var_dump($a == null);    // true
    var_dump($a === null);   // false
    var_dump(is_null($a));   // false
    
    // unset($a)
    $a = 5;
    $b = & $a;
    unset($a);
    print "b $b "; // b 5 
    
    // $a = NULL; (better I think)
    $a = 5;
    $b = & $a;
    $a = NULL;
    print "b $b "; // b 
    print(! isset($b)); // 1 
    
    ///
    $var = "";
    
    empty($var);    // true.
    is_null($var);  // false.
    !isset($var);   // false.
    
    ///
    <?php
    $var = NULL; 
    
    isset($var);    // FALSE 
    empty($var);    // TRUE 
    is_null($var);  // TRUE 
    
    isset($novar);  // FALSE 
    empty($novar);  // TRUE 
    ?>
    

Callbacks

  • A callback is a piece of code that is passed to a function that is later executed by that function.
  • Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter.
  • Callback functions can not only be simple functions, but also object methods, including static class methods.
  • Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().
  • A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.
  • Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0.
    As of PHP 5.2.3, it is also possible to pass ‘ClassName::methodName’.
  • Apart from common user-defined function, create_function() can also be used to create an anonymous callback function.
    As of PHP 5.3.0 it is possible to also pass a closure to a callback parameter.
  • Callbacks registered with functions such as call_user_func() and call_user_func_array() will not be called if there is an uncaught exception thrown in a previous callback.
  • The function to which the callback refers must be defined earlier in the source stream. So for example:
    function main() {...; usort($array, 'sortfunction'); ... }
    function sortfunction($a, $b){ return 0; }
    
    ///Will NOT work, but this will:
    
    function sortfunction($a, $b){ return 0; }
    function main() {...; usort($array, 'sortfunction'); ... }
    
  • Callback function examples ::
    <?php 
    
    // An example callback function
    function my_callback_function() {
        echo 'hello world!';
    }
    
    // An example callback method
    class MyClass {
        static function myCallbackMethod() {
            echo 'Hello World!';
        }
    }
    
    // Type 1: Simple callback
    call_user_func('my_callback_function'); 
    
    // Type 2: Static class method call
    call_user_func(array('MyClass', 'myCallbackMethod')); 
    
    // Type 3: Object method call
    $obj = new MyClass();
    call_user_func(array($obj, 'myCallbackMethod'));
    
    // Type 4: Static class method call (As of PHP 5.2.3)
    call_user_func('MyClass::myCallbackMethod');
    
    // Type 5: Relative static class method call (As of PHP 5.3.0)
    class A {
        public static function who() {
            echo "A\n";
        }
    }
    
    class B extends A {
        public static function who() {
            echo "B\n";
        }
    }
    
    call_user_func(array('B', 'parent::who')); // A
    
  • Callback example using a Closure ::
    <?php
    // Our closure
    $double = function($a) {
        return $a * 2;
    };
    
    // This is our range of numbers
    $numbers = range(1, 5);
    
    // Use the closure as a callback here to 
    // double the size of each element in our 
    // range
    $new_numbers = array_map($double, $numbers);
    
    print implode(' ', $new_numbers);
    ?>
    
  • Examples ::
    <?php 
    class MyClass { 
        public $property = 'Hello World!'; 
    
        public function MyMethod() { 
            call_user_func(array($this, 'myCallbackMethod')); 
        } 
    
        public function MyCallbackMethod() { 
            echo $this->property; 
        } 
    } 
    ?>
    
    <?php
        function myCallback($arg1) {
            echo $arg1;
        }
     
        $callback = 'myCallback';
     
        if (is_callable($callback)) {
            call_user_func($callback, 'Hello');
        }
    ?>
    

mixed

mixed indicates that a parameter may accept multiple (but not necessarily all) types.

number

number indicates that a parameter can be either integer or float.

void

void as a return type means that the return value is useless. void in a parameter list means that the function doesn’t accept any parameters.

…

$… in function prototypes means and so on. This variable name is used when a function can take an endless number of arguments.

Type Juggling

  • The behaviour of an automatic conversion to array is currently undefined.
  • because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:
    <?php
    $a    = 'car'; // $a is a string
    $a[0] = 'b';   // $a is still a string
    echo $a;       // bar
    ?>
    
<?php
$foo = "0";  // $foo is string (ASCII 48)
$foo += 2;   // $foo is now an integer (2)
$foo = $foo + 1.3;  // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs";     // $foo is integer (15)
?>

Type Casting

  • Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.
    <?php
    $foo = 10;   // $foo is an integer
    $bar = (boolean) $foo;   // $bar is a boolean
    ?>
    
  • The casts allowed are:
    1. (int), (integer) – cast to integer
    2. (bool), (boolean) – cast to boolean
    3. (float), (double), (real) – cast to float
    4. (string) – cast to string
    5. (array) – cast to array
    6. (object) – cast to object
    7. (unset) – cast to NULL (PHP 5)
    8. (binary) casting and b prefix forward support was added in PHP 5.2.1
  • Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:
    <?php
    $foo = (int) $bar;
    $foo = ( int ) $bar;
    ?>
    
  • Casting literal strings and variables to binary strings:
    <?php
    $binary = (binary) $string;
    $binary = b"binary string";
    ?>
    
  • Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.
    <?php
    $foo = 10;            // $foo is an integer
    $str = "$foo";        // $str is a string
    $fst = (string) $foo; // $fst is also a string
    
    // This prints out that "they are the same"
    if ($fst === $str) {
        echo "they are the same";
    }
    ?>
    
  • <?php
    $a = TRUE; 
    echo ($a++).$a;    // 11
    ?>
    

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

ZCE Preparation :: PHP 5.3 Basic syntax

PHP tags

  • When PHP parses a file, it looks for opening and closing tags, which are <?php and ?>, which tell PHP to start and stop interpreting the code between them.
  • everything outside of a pair of opening and closing tags is ignored by the PHP parser
  • If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag
  • There are four types of tags available:
    1. Standard Tags, they are the best solution for portability and backwards compatibility, because they are guaranteed to be available and cannot be disabled by changing PHP’s configuration file.
      <?php
      ... code
      ?>
      
    2. Short Tags were, for a time. which allows you to print the result of an expression directly to the script’s output. (only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the –enable-short-tags option.
      <?
      ... code
      ?>
      <?= $variable ?>
      
    3. Script Tags
      <script language=“php”>
      ... code
      </script>
      
    4. ASP Tags
      <%
      ... code
      %>
      
  • <?php ?> and <script language=”php”> </script>, are always available.
  • Short tags, script tags and ASP tags are all considered deprecated and their use is strongly discouraged.
  • If you are embedding PHP within XML or XHTML you will need to use the <?php ?> tags to remain compliant with standards.
  • Using short tags should be avoided when developing applications or libraries that are meant for redistribution, or deployment on PHP servers which are not under your control, because short tags may not be supported on the target server. For portable, redistributable code, be sure not to use short tags.
  • In PHP 5.2 and earlier, the parser does not allow the <?php opening tag to be the only thing in a file. This is allowed as of PHP 5.3 provided there are one or more whitespace characters after the opening tag.
  • Starting with PHP 5.4, short echo tag <?= is always recognized and valid, regardless of the short_open_tag setting.
  • Example of PHP Tags
    <?php echo 'if you want to serve XHTML or XML documents, do it like this'; ?>
    
    <script language="php">
        echo 'some editors (like FrontPage) don\'t
        like processing instructions';
    </script>
    
    <? echo 'this is the simplest, an SGML processing instruction'; ?>
    <?= expression ?> This is a shortcut for "<? echo expression ?>"
    
    <% echo 'You may optionally use ASP-style tags'; %>
    <%= $variable; # This is a shortcut for "<% echo . . ." %>
    
  • Advanced escaping using conditions
    <?php if ($expression == true): ?>
      This will show if the expression is true.
    <?php else: ?>
      Otherwise this will show.
    <?php endif; ?>
    

Instruction separation

  • PHP requires instructions to be terminated with a semicolon at the end of each statement.
  • The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block.
  • The closing tag for the block will include the immediately trailing newline if one is present.

Comments

PHP gives you multiple choices for your comments:

  1. // Single line comment
  2. # Single line comment
  3. /* Multi-line
    comment
    */
  4. /**
    * API Documentation Example
    *
    * @param string $bar
    */

Whitespace

  • You can’t have any whitespace between <? and php
  • You cannot break apart keywords (e.g.: whi le, fo r, and funct ion)
  • You cannot break apart variable names and function names, (e.g.: $var name and function foo bar())

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