Monday, December 30, 2013

HTML5, jQuery Animated Fireworks Effect

Hi all,

After long time I am back with one new tutorial and it’s a tutorial mostly based on jQuery, HTML5. I hope you will like it and you will implement it on your sites or blogs etc.

As we know most of the web developers are ready to add some new features to their websites if any occasion comes like New Year eve or Christmas etc. So as a web developer it will be a decent idea if the website is added with a new feature like some blasting effect like fireworks effect. I hope you also one of them who is looking forward to add such kind of effects. If you are then let’s get started.

With new features added in HTML there is a possibility of adding any kind of animated effect. Previously we use to do such kind of effects using flash but with new HTML5, CSS3, and jQuery these are all possible with simple coding.


What you are going to achieve?


Step 1: Prepare the Document

<!doctype html>
<html>
<head>
<title>jQuery Fireworks Animation</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="fireworks-animation.js" type="text/javascript"></script>
<style>
	 body{background: #000000 url('fireworks.jpg') no-repeat; }
     #mblfireworks{display: block;width: 1000px;height: 600px;float: center;color:#6F6F6F;text-align: center;font-size: 12px;}
     #mblfireworks a {color:#6F6F6F;}
</style>
</head>
<body>
<div id="mblfireworks"></div> 
<script>
jQuery(function($){               
Xteam.fireworkShow('#mblfireworks', 100);                 
});   
</script>
</body>
</html>

Step 2: Implement the jQuery code for Fireworks effect


if (!Xteam) var Xteam = {};
Xteam.fireworkShow = function (a, c) {
    function e() {
        a = j(a).eq(0);
        a.css("position") == "static" && a.css("position", "relative");
        h = j("");
        if (!h[0].getContext) return false;
        h.attr({
            height: a.height(),
            width: a.width()
        }).css({
            position: "absolute",
            display: "block",
            top: 0,
            left: 0,
            zIndex: 99999
        }).appendTo(a);
        n = Xteam.Canvas.scene(h[0]);
        l = setInterval(function () {
            Math.random() > 0.75 || Xteam.firework(n)
        }, 1.5 * c);
        k = true
    }
    var d = {}, j = jQuery,
        l, n, h, k = false;
    c = c || 900;
    e();
    d.remove = function () {
        if (k) {
            clearInterval(l);
            n.destroy();
            n = null;
            h.remove();
            a = h = null
        }
    };
    return d
};
Xteam || (Xteam = {});
Xteam.firework = function (a) {
    function c() {
        k = 360 * Math.random();
        f = Xteam.Color.hslToRgb([k, Math.random(), 0.2 + 0.8 * Math.random()]);
        i = (a.getCanvas().width - h * 2) * Math.random() + h;
        m = (a.getCanvas().height / 2 - h) * Math.random() + h;
        o = a.getCanvas().height;
        a.register(j)
    }

    function e() {
        if (o > m) {
            o -= 10;
            l.fillStyle = "rgb(" + f[0] + "," + f[1] + "," + f[2] + ")";
            l.beginPath();
            l.arc(Math.round(i), Math.round(o), 2, 0, 2 * Math.PI, true);
            l.fill()
        } else {
            a.remove(j);
            d()
        }
    }

    function d() {
        for (var p = 40 + Math.floor(50 * Math.random()); p--;) {
            var q = Xteam.Color.hslToRgb([k, Math.random(), 0.2 + 0.8 * Math.random()]);
            new n(a, q, i, m, 10)
        }
    }
    var j = {
        draw: e
    }, l = a.getContext(),
        n = Xteam.FireworkParticle,
        h = 70,
        k, i, m, o, f;
    c();
    return j
};
Xteam.FireworkParticle = function (a, c, e, d) {
    this.scene = a;
    this.color = c;
    this.x = Math.round(e);
    this.y = Math.round(d);
    this.rotate = 2 * Math.PI * Math.random();
    this.opacity = 500;
    this.f = 0;
    this.max = 50 + 10 * Math.random();
    this.size = 0;
    this.speed = 4 * Math.random();
    a.register(this)
};
Xteam.FireworkParticle.prototype = {
    getStyle: function () {
        return "rgba(" + this.color[0] + "," + this.color[1] + "," + this.color[2] + "," + this.opacity / 100 + ")"
    },
    draw: function (a, c) {
        if (this.f < this.max) {
            this.f++;
            this.size += this.speed;
            this.speed *= 0.95;
            if (this.f > 0.8 * this.max) this.opacity -= 6;
            c.lineWidth = 1;
            c.save();
            c.translate(this.x, this.y);
            c.rotate(this.rotate);
            c.strokeStyle = this.getStyle();
            c.beginPath();
            c.moveTo(Math.round(0.85 * this.size), 0);
            c.lineTo(Math.round(this.size), 0);
            c.stroke();
            c.restore()
        } else this.scene.remove(this)
    }
};
Xteam || (Xteam = {});
if (!Xteam.Canvas) Xteam.Canvas = {};
Xteam.Canvas.scene = function (a) {
    function c(f) {
        i.push(f)
    }

    function e() {
        for (var f = m.length; f--;) i[m[f]] = null;
        m = [];
        for (f = i.length; f--;) i[f] || i.splice(m[f], 1)
    }

    function d(f) {
        for (var p = i.length; p--;)
            if (f === i[p]) {
                m.push(p);
                break
            }
    }

    function j() {
        clearInterval(o)
    }

    function l() {
        return k
    }

    function n() {
        return a
    }
    var h = {
        register: c,
        remove: d,
        getContext: l,
        getCanvas: n,
        destroy: j
    }, k = a.getContext("2d"),
        i = [],
        m = [],
        o = setInterval(function () {
            k.clearRect(0, 0, a.width, a.height);
            for (var f = i.length; f--;) typeof i[f].draw == "function" && i[f].draw(h, k);
            e()
        }, 30);
    return h
};
Xteam || (Xteam = {});
if (!Xteam.Color) Xteam.Color = {};
Xteam.Color.hslToRgb = function (a) {
    var c = a[0],
        e = a[1];
    a = a[2];
    if (e == 0) r = g = b = a;
    e = a < 0.5 ? a * (1 + e) : a + e - a * e;
    a = 2 * a - e;
    c /= 360;
    var d = [];
    d[0] = c + 1 / 3;
    d[1] = c;
    d[2] = c - 1 / 3;
    for (c = 3; c--;) {
        d[c] %= 1;
        d[c] = d[c] < 1 / 6 ? a + (e - a) * 6 * d[c] : d[c] < 0.5 ? e : d[c] < 2 / 3 ? a + (e - a) * 6 * (2 / 3 - d[c]) : a;
        d[c] *= 255;
        d[c] = Math.floor(d[c]);
        if (d[c] < 0) d[c] = 0
    }
    return d
};
Xteam.Color.hslToRgb.test = function () {
    function a(e, d) {
        for (var j = e.lenght; j--;)
            if (e[j] !== d[j]) throw Error("Got " + e + ", expected " + d);
        console.log("success")
    }
    var c = Xteam.Color.hslToRgb;
    a(c([0, 1, 1]), [1, 0, 0]);
    a(c([120, 0.5, 1]), [0.5, 1, 0.5]);
    a(c([240, 1, 0.5]), [0, 0, 0.5]);
    c([104.15549071384422, 0.9040453462245244, 0.2855993456480115])
};
Thats it.

Thursday, June 20, 2013

Live Username Availability Checker With PHP, MySQL, AJAX and jQuery

I guess you would have seen various websites which checks username availability on the fly during registration process. For example take “gmail signup” or "twitter signup" or "yahoo signup", their registration process is very flexible, it tells user everything on the fly. Means if i am typing a username it gives suggestions on the fly whether the username is available or not. So in this tutorial i will make an ajax username availability checker powered with jQuery, PHP and MySQL. So let's get started.

How the application will look like?
Check Username availability with php, mysql, jquery

Step 1: Database configuration and its connection settings (connect.php)

<?php
$db="pwd_strength";
$hostname = "localhost";
$user = "root";
$password = "";
$con = mysql_connect($hostname, $user, $password) or die("Could not connect database");
mysql_select_db($database, $con) or die("Could not select database");
?>
Step 2: Application Landing Page (index.php)

<!DOCTYPE html >
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link rel="stylesheet" type="text/css" href="css/style.css" />
    </head>
    <body>
        <div id="container">
            <div id="wrapper">
                <div id="top"> Live Username Availability Checker </div>
                <div id="form">
                    <label>Username</label>
                    <input type="text" autocomplete="off" name="user_name" id="user_id" class="user_name" />
                    <span class="check"  ></span> <br/><br/>
                </div>
            </div>
        </div>
        <!-- js placed at bottom to make page load faster -->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function()
            {
                $('.user_name').keyup(function()
                {
                    var checkname=$(this).val();
                    var availname=remove_whitespaces(checkname);
                    if(availname!=''){
                        $('.check').show();
                        $('.check').fadeIn(400).html('<img src="images/ajax-loading.gif" /> ');

                        var String = 'username='+ availname;

                        $.ajax({
                            type: "POST",
                            url: "username-check.php",
                            data: String,
                            cache: false,
                            success: function(result){
                                var result=remove_whitespaces(result);
                                if(result==''){
                                    $('.check').html('<img src="images/accept.png" /> This Username Is Avaliable');
                                    $(".check").removeClass("red");
                                    $('.check').addClass("green");
                                    $(".user_name").removeClass("yellow");
                                    $(".user_name").addClass("white");
                                }else{
                                    $('.check').html('<img src="images/error.png" /> This Username Is Already Taken');
                                    $(".check").removeClass("green");
                                    $('.check').addClass("red")
                                    $(".user_name").removeClass("white");
                                    $(".user_name").addClass("yellow");
                                }
                            }
                        });
                    }else{
                        $('.check').html('');

                    }
                });
            });
            function remove_whitespaces(str){
                var str=str.replace(/^\s+|\s+$/,'');
                return str;
            }
        </script>
    </body>
</html>

Step 3: The code behind for checking username availability (username-check.php)


<?php
require 'connect.php';
if(isset($_POST['username']) && !empty($_POST['username'])){
      $username=strtolower(mysql_real_escape_string($_POST['username']));
      $query="select * from registration where LOWER(username)='$username'";
      $res=mysql_query($query);
      $count=mysql_num_rows($res);
      $HTML='';
      if($count > 0){
        $HTML='user exists';
      }else{
        $HTML='';
      }
      echo $HTML;
}
?>

Step 4: Applying some styles to the application for better look and feel (style.css)


body {
    padding: 50px;
}
h1 a {
    color: #000;
}
input {

    font-size:12px;
    padding:4px 2px;
    border:solid 1px #aacfe4;
    width:200px;
    margin:0 5px;
}

label {display:block;
       font-weight:bold;
       text-align:right;
       width: 200px;
       float:left;
}

#top{
    margin-left: 75px;
    font-weight: bold;
    font-size:24px;
    color: blue;
    padding: 10px;
}
#wrapper{
    border:solid 2px #b7ddf2;
    background:#ebf4fb;
    width: 700px;
    margin: auto;

    padding:20px;
    min-height:180px;
}

#form{margin-top: 10%;
      margin-left: auto;}

#bottom{
    margin-left: 450px;
    font-size: 24px;
}
.yellow{background-color:yellow;}
.white{background-color:#FFF;}
.green{color:green;}
.red{color:red;}

Thanks for reading. Do regularly visit for more tutorials and subscribe for latest posts below.

Please do find the below link for entire source code.

Download Link : http://www.mediafire.com/?q67okh957ayopcy

Sunday, May 19, 2013

How to Redirect Visitors to a Maintenance Page During Website Maintenance Using .htaccess


Sometimes we come across the websites with messages like "Website is under maintenance", "Website is temporarily shutdown", "We are upgrading our server please come back soon" etc etc. Have you ever come across such kind of things during your web surfing period? I guess everyone would have come across those situations. But have you ever imagined how to achieve this whenever your website needs such kind of work. Now let's do it.

Redirecting visitors to a maintenance page or other temporary page is a must have tool for every webmaster or web developer. We can redirect the visitors to a maintenance page with a simple file called as ".htaccess" file and some code in it. Now let's see the how to redirect the visitors with .htaccess code.

Redirecting all visitors with .htaccess

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.html$ [NC]
RewriteRule .* /maintenance.html [R=302,L]

To redirect your visitors to a maintenance page, place the above code into a .htaccess file located in your site root directory. This will make that all pages and resources contained within your domain will be redirected for visitors.

Now that the .htaccess is in place, you'll need to create and upload your maintenance page, named 'maintenance.html' to the root directory of your site. This file can be just about anything, and does not need to be written in HTML. You can use, say, PHP to make it all dynamic, but remember to change the two instances of the file name in the .htaccess code to match the actual name of your file.

Wow! Amazing .htaccess trick. Its working perfectly. But i have got small problem that me and my client are not able to see the site. For example, assume that you are working for a client and that client wants to see what kind of modifications are going on in the site. Then to achieve this using .htaccess add the below line of code to the file.

RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000

Now the total code looks like below.

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000
RewriteCond %{REQUEST_URI} !/maintenance.html$ [NC]
RewriteRule .* /maintenance.html [R=302,L]

Note: You can add multiple IP addresses to the .htaccess file to give access to the site for the respective IP addresses. Just add the multiple RewriteCond's to the existing .htaccess file. See below code.

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000
RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000
RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000
RewriteCond %{REQUEST_URI} !/maintenance.html$ [NC]
RewriteRule .* /maintenance.html [R=302,L]

The above code sends all users to maintenance.html EXCEPT those with the specified IP, the IP's we mentioned in the code will be able to see the website while the remaining will see the maintenance page during website maintenance.

Thanks for reading this article, please feel free to comment and subscribe for more updates by putting your email in the subscribe box.

Wednesday, April 3, 2013

AJAX Auto Complete Feature Like Google, Facebook With PHP, MySQL

When i am working on one of my project, i need to work on AJAX. So i started googling about AJAX how to's. So i started learning AJAX slowly and steadily. After completion of learning AJAX i started working on AJAX Auto complete suggest feature. So i tried hard to work on that finally i got the solution from one of the online resource. I hope you are also one of the guy who is looking for such kind of solution. So i thought i should share this to my online users. One thing every one should get this in their mind that what actually an AJAX Auto complete is? Perhaps i too didn't have any idea but after working on that i came to know.

So let's see what an AJAX Auto complete suggest is? As a web developer almost all us in our daily life, use Google at its best. When we start googling like "how to" or "AJAX tutorial" etc then the Google will show some results beneath its search text box. See below picture for better understanding. So this feature is called as AJAX Auto complete Suggest Feature. Now a days all of the websites have this feature.


Now Let's see how to design such an application.

Step 1: Design the Database. 

See the below picture for better understanding of database design. In this tutorial, i have just created one table for demonstration purpose. The process is same for the bigger database also. In this tutorial i assumed the database name as "phphunger_ajax_autocomplete" and table name as "games". Change the names as your wish.


Create the table as "games"

CREATE TABLE IF NOT EXISTS `games` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

Dump some data into the table "games"

INSERT INTO `games` (`id`, `name`) VALUES
(1, 'Angry Birds'),
(2, 'Angry Birds Space'),
(3, 'Angry Birds Space Battle'),
(4, 'Babe Rescue'),
(5, 'Ball Defence'),
(6, 'Ball Defence  2');

Once the database design phase is over the next step is to design the front end for the user from where he starts searching the content.

Step 2: Design the HTML Form

Here add one Textbox on the HTML Form which communicates with AJAX and fetches data from the back-end to the front-end. See below picture how the form looks like. Name the file as "index.html"



Step 3: Write AJAX Code

Write some javascript code which includes the AJAX Request, Response logic. See below code. Name the file as "suggest.js"

suggest.js
function getXmlHttpRequestObject() {
 if (window.XMLHttpRequest) {
  return new XMLHttpRequest();
 } else if(window.ActiveXObject) {
  return new ActiveXObject("Microsoft.XMLHTTP");
 } else {
  alert("Your Browser Sucks!");
 }
}

//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();

//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
 if (searchReq.readyState == 4 || searchReq.readyState == 0) {
  var str = escape(document.getElementById('dbTxt').value);
  searchReq.open("GET", 'searchSuggest.php?search=' + str, true);
  searchReq.onreadystatechange = handleSearchSuggest;
  searchReq.send(null);
 }
}

//Called when the AJAX response is returned.
function handleSearchSuggest() {
 if (searchReq.readyState == 4) {
         var ss = document.getElementById('layer1');
  var str1 = document.getElementById('dbTxt');
  var curLeft=0;
  if (str1.offsetParent){
      while (str1.offsetParent){
   curLeft += str1.offsetLeft;
   str1 = str1.offsetParent;
      }
  }
  var str2 = document.getElementById('dbTxt');
  var curTop=20;
  if (str2.offsetParent){
      while (str2.offsetParent){
   curTop += str2.offsetTop;
   str2 = str2.offsetParent;
      }
  }
  var str =searchReq.responseText.split("\n");
  if(str.length==1)
      document.getElementById('layer1').style.visibility = "hidden";
  else
      ss.setAttribute('style','position:absolute;top:'+curTop+';left:'+curLeft+';width:250;z-index:1;padding:5px;border: 1px solid #000000; overflow:auto; height:105; background-color:#F5F5FF;');
  ss.innerHTML = '';
  for(i=0; i < str.length - 1; i++) {
   //Build our element string.  This is cleaner using the DOM, but
   //IE doesn't support dynamically added attributes.
   var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
			suggest += 'onmouseout="javascript:suggestOut(this);" ';
			suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
			suggest += 'class="small">' + str[i] + '</div>';
			ss.innerHTML += suggest;

  }
 }
}

//Mouse over function
function suggestOver(div_value) {
 div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
 div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
 document.getElementById('dbTxt').value = value;
 document.getElementById('layer1').innerHTML = '';
 document.getElementById('layer1').style.visibility = "hidden";
}

Step 4: Connect to Database and Fetch Results.

This is the file for database connection and fetching results from table. Name it as searchSuggest.php That's what an AJAX Autocomplete feature. Use this code snippet if your requirement matches. Do play with this code. Happy coding.

Sunday, March 31, 2013

Best Tools For Testing PHP Code Online

PHP is such an awesome scripting language for building dynamic web application because it has a huge user base as well as developer base. As it is an open source language so its freely available in the internet without any hassle. And the developer community is contributing towards PHP to increase the user base. Because of constantly adding new features to PHP regularly, the new and fresh tools are coming up in the internet.

While i am browsing for the online resources to test PHP code, i came to know these tools. So i shared these tools to you people. If want to try it once please go ahead. Its not a mandatory that you should use these tools. These tools are just for informational purpose.

Let's see some new tools which are providing online services for running your PHP Code. With these tools the developer can test his/her code online without going for the localhost.

Codepad:

codepad is an online compiler/interpreter, and a simple collaboration tool. The codepad will support many languages like C, C++, D, Haskell, Lua, OCaml, PHP, Perl, Plain Text, Python, Ruby, Scheme, Tcl. You can try out with your favorite language.


The URL is Codepad.org

Writecodeonine:

This is also one of the online code editor where the developer can paste the code in the code area and run the code online.


The URL is Writecodeonline

OnlinePHPFunctions:

This online tool gives you more options like with which version of PHP you want to work. The developer can select with which version he/she wants to run their PHP code. This is most useful for testing PHP functions online. Try out once.


The URL is Online PHP Functions

codepad.viper-7:

This tool also gives you options like with which version you wants to test the PHP code.


The URL is Codepad Viper-7

PHP Fiddle:

The PHP Fiddle is one of the amazing online code testing tool for testing almost all kind of web technologies like PHP, HTML, CSS, Javascript, MySQL support. This is one of the great tool. I simply love it.


The URL is PHP Fiddle

Exorithm: 

Last but not the least, its also one of the tool to test the PHP code online.


The URL is Exorithm

OK guys, Try out all these at least once just for informational purpose. Use our PHP Developer Journey-Tutorials for testing PHP Code online. All the best.

Friday, March 29, 2013

Displaying Games On the Web. How?

Hello all, today its time for me to tell you something about online games. Have you ever imagined that, in our daily life not all of us, at least some of us use to play online games with an intention to give some relief to our stressed mind. The answer will be of course, yes. But have you ever imagined that how the games you play over the web comes to you.

Let's see how the games comes on the website. Now a days where ever you go people are addicted to playing games on the web. According to comScore.com, the percentage of online game players has crossed over 200 Million. Can you believe it? Now let's see in how many ways we can show the game content to the end user.

Generally as of now the game content has come up in 3 variety of forms. They are as follows:
  1. Adobe Flash SWF Format
  2. Adobe Shockwave Format
  3. Unity3D Format
 Adobe Flash SWF Format (.swf):

This file comes up with a .swf file extension. The online gaming revolution on the web has started with this version. The inventors of this .swf file format are Adobe. The code for displaying flash content on the web page is as follows:

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="100%" height="100%">
    <param name="movie" value="swf/gamename.swf" />
    <param name="quality" value="high" />
    <param name="allowScriptAccess" value="always" />
<object type="application/x-shockwave-flash" data="swf/gamename.swf" width="100%" height="100%"></object>
</object>

Adobe Shockwave Format (.dcr): 

This file comes up with a .dcr file extension. With this DCR files the 3D features has been incorporated in the online gaming revolution on the web. The inventors of this .dcr file format are also Adobe. The code for displaying shockwave director content on the web page is as follows:

<object width="100%" height="100%" classid="clsid:166B1BCA-3F9C-11CF-8075-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=7,0,2,0">
    <param name="src" value="shockwave/gamename.dcr" />
    <embed src="shockwave/gamename.dcr" width="100%" height="100%" type="application/x-director" />
</object>

Unity3D Format (.unity3d):

This file comes up with a .unity3d file extension. With this Unity3D files the 3D features has been incorporated in the online gaming revolution on the web. The gamer can feel the PC gaming experience with Unity 3D games. The inventors of this .dcr file format are also Adobe. The code for displaying Unity 3D content on the web page is as follows:


<object id='UnityObject' classid='clsid:444785F1-DE89-4295-863A-D46C3A781394' width='100%' height='100%' codebase='http://webplayer.unity3d.com/download_webplayer/UnityWebPlayer.cab#version=2,0,0,0'>
    <param name='src' value='unity/gamename.unity3d' />
    <embed src='unity/gamename.unity3d' width='100%' height='100%' type='application/vnd.unity' pluginspage='http://www.unity3d.com/unity-web-player-2.x' />
</object>

Thursday, March 21, 2013

Understanding Operators in PHP - Part 5

Hi all, as we are trying to understand the operators concepts. This is the last article in the Operators series. In our PHP Developer Journey tutorials, let's continue with our Understanding Operators part 5. If you are unaware of the initial parts then please go through the below links.

Assignment operators, Arithmetic operators, Array operators - Part 1

String operators, Logical Operators - Part 2

Bitwise Operators - Part 3

Comparison Operators - Part 4

Error Control Operators:

PHP language is very handy when dealing with errors. Sometimes its necessary for the developer not to display the error messages to the end user which actually occurs when something goes wrong with the code. This can be accomplished in PHP with the help of an operator called "Error Suppression" Operator (@).

How to use Error Control Operator (@):

We can prevent the errors by not showing to the end user by putting in front of the operation. Like wise, for example, Divide-By-Zero is an infinity number, if you output then it will print some error. With the @ operator, however, we can prevent the error from being printed out, but not from occurring it. Let's see a simple example.

Demo Without using Error Control Operator in the expression:

$a = 1 / 0;

echo $a;

echo "hi";

From the above code, the following output will come if you execute at your localhost. See the below picture.
Demo With using Error Control Operator in the expression:

@$a = 1 / 0;

echo $a;

echo "hi";

Piece Of Advice for Error Control Operators:

This operator can be very dangerous because it prevents PHP from notifying you that something has gone wrong. You should, therefore, use it only whenever you want to prevent errors from propagating to a default handler because you have a specialized code segment that you want to take care of the problem. Generally speaking, it’s a bad idea to use this approach simply as a way to “silence” the PHP interpreter, as there are better ways to do so (for example, through error logging) without compromising its error reporting capabilities. 

Note that not all types of errors can be caught and suppressed using the @ operator. Because PHP first parses your script into an intermediate language that makes execution faster and then executes it, it won’t be capable of knowing that you have requested error suppression until the parsing phase is over and the execution phase begins. As a result, syntax errors that take place during the parsing phase will always result in an error being outputted, unless you have changed your php.ini settings in a way that prevents all errors from being outputted independently from your use of the @ operator.

Execution Operators:

PHP supports one execution operator: backticks (``). Note that these are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned (i.e., it won't simply be dumped to output; it can be assigned to a variable). Use of the backtick operator is identical to shell_exec().

As i haven't worked with this operator in my PHP's life span. So i just grabbed this content from php.net manual.

$output = `ls -al`;

echo "
$output
";
Type casting: 

As we know PHP is a loosely typed language and assigns types to variables depending what is assigned to it. Even though PHP handles data types automatically most of the time, you can still force it to convert a particular datum to a specific type by using a typecasting operator. There are two ways to cast a variable in PHP as a specific type: using the settype() function, or using (int) (bool) (float) etc. 

Using the settype() function you can do this: These are 

settype($foo, "array");

settype($foo, "bool");

settype($foo, "boolean");

settype($foo, "float");

settype($foo, "int");

settype($foo, "integer");

settype($foo, "null");

settype($foo, "object");

settype($foo, "string");


Using (int) etc you can do this instead:

  • (int) to cast a value to its integer equivalent 
  • (float) to cast a value to its floating-point equivalent 
  • (string) to cast a value to its string equivalent 
  • (array) to force the conversion of the operand to an array if it is not one already 
  • (object) to force the conversion of the operand to an object if it is not one already

$foo = (array)$foo;

$foo = (boolean)$foo;

$foo = (double)$foo;

$foo = (float)$foo;

$foo = (int)$foo;

$foo = (integer)$foo;

$foo = (object)$foo;

$foo = (real)$foo;

$foo = (string)$foo;

Note: php.net manual says "PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used."

Operator Precedence: 

Operator precedence refers to the order in which operators execute within an expression. For example, one of the basic rules of arithmetic is that multiplications and divisions are executed before additions and subtractions. With a large number of types of operations available, things get a bit more complicated, but are by no means complex.

Operator Precedence and associvity
For Example,

$foo = 5 * 10 - 1; // output: 49

Should $foo be 49 or 45? If you cannot see why there are two possibilities, it might help to break them up using brackets, like this:

$foo = (5 * 10) - 1; output: 49
$foo = 5 * (10 - 1); output: 45

Case 1:

$foo = (5 * 10) - 1

In case 1, five is multiplied by ten then one is subtracted from the result.

Case 2:

$foo = 5 * (10 - 1);

In case 2 ten has one subtracted from it, making nine, then that result is multiplied by five. If there is any ambiguity in your expressions, PHP will resolve them according to its internal set of rules about operator precedence, that is, which operators are calculated first.

Ok that's all about operators. Keep coming for more stuff..

Thursday, March 14, 2013

Understanding Operators in PHP - Part 4

In our PHP Developer Journey tutorials, let's continue with our Understanding Operators part 4. If you are unaware of the initial parts then please go through the below links.

Assignment operators, Arithmetic operators, Array operators - Part 1

String operators, Logical Operators - Part 2

Bitwise Operators - Part 3

Comparison Operators:

Comparison operators, as the name itself says that, they will allow you to compare two values. Simply the comparison operators are used to determine the relationship between two variables.

Let's see the different types of comparison operators:

1. == (Equal): The == operator determines if two values are equal or not.

Demo of Equal (==) Operator:
$x = 46; // integer variable
$y = "46"; // string variable
var_dump($x == $y); // output: TRUE

Explanation: From the above code, we have one integer variable and another is string variable, So  the PHP interpreter will first convert the string variable to integer variable then perform comparison. Because the integer will have the higher priority than string. So the conversion takes place before the comparison. Since the two variables hold the same values but are of different type. 

2. != (Not Equal): The != operator determines if two values are different.

Demo of Not Equal (!=) Operator:
$x = 46; // integer variable
$y = "46"; // string variable
var_dump($x != $y); // output: FALSE

Explanation: From the above code, we have one integer variable and another is string variable, Since the two variables hold the same values but are of different type. Even though they are of different type the PHP interpreter returns FALSE.

3. < (Less than): The < operator determines whether the left operand’s value is less than the right operand’s.

Demo of Less than (<) Operator:
$x = 46; //integer
$y = 100; //integer
var_dump($x<$y); //output: TRUE

Explanation: From the above code, we have two integer variables, Since the two variables hold the different values but are of same type. Based on the comparison operator the PHP interpreter returns TRUE. Since 46 is less than 100.

4. > (Greater than): The > operator determines whether the left operand’s value is greater than the right operand’s.

Demo of Greater than (>) Operator:
$x = 46; //integer
$y = 100; //integer
var_dump($x>$y); //output: FALSE

Explanation: From the above code, we have two integer variables, Since the two variables hold the different values but are of same type. Based on the comparison operator the PHP interpreter returns FALSE. Since 46 is less than 100.

5. <= (Less than or Equal): The <= operator determines whether the left operand’s value is less than or equal to the right operand’s.

Demo of Less than or Equal (<=) Operator:
$x = 46; //integer
$y = 100; //integer
var_dump($x<=$y); //output: TRUE

Explanation: From the above code, we have two integer variables, Since the two variables hold the different values but are of same type. Based on the comparison operator the PHP interpreter returns TRUE. Since 46 is less than or equal 100.

6. >= (Greater than or Equal): The >= operator determines whether the left operand’s value is greater than the right operand’s.

Demo of Greater than or Equal (>=) Operator:
$x = 46; //integer
$y = 100; //integer
var_dump($x>=$y); //output: FALSE

Explanation: From the above code, we have two integer variables, Since the two variables hold the different values but are of same type. Based on the comparison operator the PHP interpreter returns FALSE. Since 46 is neither greater than nor equal to 100.

7. === (Identical): The === operator determines whether the value and the type of the two operands is the same.

Demo of Identical (===) Operator:

$x = 46;
$y = "46";
var_dump($x===$y);

Explanation: From the above code, we have one integer variable and another is string variable, Since the two variables hold the same values but are of different type. The above php code returns FALSE as strict equal operator will compare both value and type of $x and $y.

8. !== (Not Identical): The !== operator determines whether either the value or the type of the two operands is different.


Demo of Not Identical (!==) Operator:

$x = 46;
$y = "46";
var_dump($x!==$y);

Explanation: From the above code, we have one integer variable and another is string variable, Since the two variables hold the same values but are of different type. The above php code returns true though their values are equal but type of $x and $y are not equal (first one is integer type and second one is character type).

Note: All the comparison operators returns the Boolean value as a result.

While performing comparisons with the variables, the PHP interpreter first convert them if they are not of the same type. If the variables have the same type then no conversions will take place  These conversions will take place automatically by the PHP interpreter. Keep a note that, these conversions will be done based on the priority of the "Data Type". Means whatever the data type has the highest priority it will be taken first and so on. The Data Type here either integer, floating point, string, character like that.

Thanks for reading. Keep visiting for more stuff.