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.

Wednesday, February 27, 2013

Simple PHP Search Engine Script Tutorial

Generally dynamic websites hosts tons of data with them. Searching for a particular thing is very tedious task if websites don't have proper searching functionality. For such requirement this search tool is perfect if you want a quick and easy way to search your dynamic websites.

Having a search feature on a dynamic website is very handy for helping users find exactly what they are looking for. Almost all users now prefer different search engines to find what they are looking for. Search engines range from something very simple to very complicated as Google, MSN, Bing, Yahoo etc. 

In this tutorial, our scope is limited to searching a simple database table and extract those results from database. I hope it gives a little idea to build bigger search engine for developing more complex search engine like Google.

Simple PHP Search Engine Script Tutorial

This tutorial assumes whatever the data you want to search will be stored in the MySQL Database table. In this tutorial, we will use a simple query to search the data from the MySQL database table. No complex algorithms will be used. Using of such complex algorithms is beyond our tutorial's limit.

Before we start off this tutorial, we need a database. The code below will create a testing database to use as you work through the tutorial.

 Step 1:

Creating a database called "search-engine" and table called "mobiles". See below picture and code snippet.

PHP Search Engine Database


Step 2: 

Now create a search form (index.php) for the users where they start searching for their desired content. See the below code snippet.

Step 3:

The real search script where the real search functionality happens. Name it as (search.php) or whatever it may be. See the below code snippet.

The above is the combined screen shot how you will see the results after searching for something. Hope you have enjoyed it. Keep coming for more tutorials. 

Monday, February 25, 2013

Understanding Operators in PHP - Part 3

Hi all, let's continue with our operators. The next in the series is Bitwise operators:Note: Please go through part 1 and part 2 of php operators here.

Bitwise operators:

Bitwise operators works on the binary representation of integers. Means first the integer operand will be converted to its binary form and then performs its operation based on the operator.

Note: The binary form means zero's(0) and one's(1).

The bitwise operators are as follows: & (AND), | (OR), ^ (XOR), ~ (NOT), << (Shift Left), >> (Shift Right)

Bitwise AND (&) :

If both the bits are set, means both the binary values are 1 then the output will be 1 else 0. Here the bit set means 1 and bit not set means 0. Let's see a small demo on bitwise AND (&).

Demo:

Let's take two numbers 46 and 93 respectively. Now perform binary conversion for these two numbers.

Step 1: 

Converting decimal numbers 46 and 93 into their binary form. 

The binary representation of 46 - 00101110 

The binary representation of 93 - 01011101 

I guess you are little bit confused with the binary form. How the decimal numbers got translated to binary form. You are not alone, even i too confused with these binary form. After recollecting my engineering subjects i got clear solution. See the below tables about how to convert decimal number to binary conversion? 

A decimal number 46 can be represent in binary form like bellow - 
1 Byte ( 8 bits )
Decimal Place 128 64 32 16 8 4 2 1
0 0 1 0 1 1 1 0
27 26 25 24 23 22 21 20
0 0 32 0 8 4 2 0 = 46

A decimal number 93 can be represent in binary form like bellow - 
1 Byte ( 8 bits )
Decimal Place 128 64 32 16 8 4 2 1
0 1 0 1 1 1 0 1
27 26 25 24 23 22 21 20
0 64 0 16 8 4 0 1 = 93
Step 2:


Now perform Bitwise AND Operation on them. The output will be 00001100.

After performing AND operation on both the binary numbers, the bit set occurs at 5th digit and 6th digit in both the binary forms. So the 5th digit is at 23 and 6th digit is at 22 position. Now you may get confusion that how to perform the Bitwise Operation on those numbers. Simply perform the AND operation then you will get the result. See below that how to perform bitwise operation on those two numbers.

Base 2 27 26 25 24 23 22 21 20
Binary 46 0 1 0 1 1 1 0 1
Binary 93 0 0 1 0 1 1 1 0
Result 0 0 0 0 1 1 0 0

Now from the above manipulation, the bit set occurs 5th and 6th position.

Step 3:

Now perform addition operation on these two 23 and 6th digit is at 22. You will get 23 + 22 = 12. Now you may be confused that how this answer 12 came. Don't get confused. Simply multiply the binary number quotient with base 2 and then perform addition on those numbers then you will get the answer.

(27 x 0) + (26 x 0) + (25 x 0) + (24 x 0) + (23 x 1) + (22 x 1) + (21 x 0) + (20 x 0) = 12

Huh...These many steps...its really very frustrating..Don't panic..you don't have to worry about these many steps. Let's see the same in our php code. Its really very simple.

$x=46;

$y=93;

echo $x & $y; // output: 12

Bitwise OR (|) :

If any one of the bit is set, means any one of the binary value is 1 then the output will be 1 else 0. Here the bit set means 1 and bit not set means 0. Let's see a small demo on bitwise OR (|).

Demo:

Let's take two numbers 46 and 93 respectively. Now perform binary conversion for these two numbers.

Step 1:

Converting decimal numbers 46 and 93 into their binary form. 

The binary representation of 46 - 00101110

The binary representation of 93 - 01011101

I guess you are little bit confused with the binary form. How the decimal numbers got translated to binary form. You are not alone, even i too confused with these binary form. After recollecting my engineering subjects i got clear solution. See the below tables about how to convert decimal number to binary conversion?

A decimal number 46 can be represent in binary form like bellow -
1 Byte ( 8 bits )
Decimal Place 128 64 32 16 8 4 2 1
0 0 1 0 1 1 1 0
27 26 25 24 23 22 21 20
0 0 32 0 8 4 2 0 = 46

A decimal number 93 can be represent in binary form like bellow -
1 Byte ( 8 bits )
Decimal Place 128 64 32 16 8 4 2 1
0 1 0 1 1 1 0 1
27 26 25 24 23 22 21 20
0 64 0 16 8 4 0 1 = 93

Step 2:

Now perform Bitwise OR Operation on them. The output will be 01111111.

After performing OR operation on both the binary numbers, the bit set occurs at 2nd, 3rd, 4th, 5th, 6th, 7th and 8th digits respectively in both the binary forms. So these digits are at 26,25,24,23,22,21,and at 20 positions. Now you may get confusion that how to perform the Bitwise Operation on those numbers. Simply perform the OR operation then you will get the result. See below that how to perform bitwise operation on those two numbers.

Base 2 27 26 25 24 23 22 21 20
Binary 46 0 1 0 1 1 1 0 1
Binary 93 0 0 1 0 1 1 1 0
Result 0 1 1 1 1 1 1 1

Now from the above manipulation, the bit set occurs at 2nd, 3rd, 4th, 5th, 6th, 7th, and 8th positions respectively.

Step 3:

Now perform addition operation on these 26,25,24,23,22,21,and at 20 positions. You will get = 127. Now you may be confused that how this answer 127 came. Don't get confused. Simply multiply the binary number quotient with base 2 and then perform addition on those numbers then you will get the answer.

(27 x 0) + (26 x 1) + (25 x 1) + (24 x 1) + (23 x 1) + (22 x 1) + (21 x 1) + (20 x 1) = 127

Huh...These many steps...its really very frustrating..Don't panic..you don't have to worry about these many steps. Let's see the same in our php code. Its really very simple.

$x=46;

$y=93;

echo $x | $y; // output: 127

Bitwise XOR (^) :

If any one of the bit is set, means any of the binary value is 1 then the output will be 1. If both the bits are either 1 or 0 then output will be 0. Here the bit set means 1 and bit not set means 0. Let's see a small demo on bitwise XOR (^).

Demo:

Let's take two numbers 46 and 93 respectively. Now perform binary conversion for these two numbers.

Step 1:

Converting decimal numbers 46 and 93 into their binary form. 

The binary representation of 46 - 00101110

The binary representation of 93 - 01011101

A decimal number 46 can be represent in binary form like bellow -
1 Byte ( 8 bits )
Decimal Place 128 64 32 16 8 4 2 1
0 0 1 0 1 1 1 0
27 26 25 24 23 22 21 20
0 0 32 0 8 4 2 0 = 46

A decimal number 93 can be represent in binary form like bellow -
1 Byte ( 8 bits )
Decimal Place 128 64 32 16 8 4 2 1
0 1 0 1 1 1 0 1
27 26 25 24 23 22 21 20
0 64 0 16 8 4 0 1 = 93

Step 2:

Now perform Bitwise XOR Operation on them. The output will be 01110011. After performing XOR operation on both the binary numbers, the bit set occurs at 2nd, 3rd, 4th, 7th and 8th digits respectively. So the 2nd, 3rd, 4th, 7th and 8th is at 26, 25, 24, 21 and 20 positions. See below that how to perform XOR bitwise operation on those two numbers.

Base 2 27 26 25 24 23 22 21 20
Binary 46 0 1 0 1 1 1 0 1
Binary 93 0 0 1 0 1 1 1 0
Result 0 1 1 1 0 0 1 1

Now from the above manipulation, the bit set occurs at 2nd, 3rd, 4th, 7th and 8th digits respectively.

Step 3:

Now perform addition operation on these 26, 25, 24, 21 and 20. You will get 26 + 25 + 24 + 21 + 20 = 115. Now you may be confused that how this answer 115 came. Don't get confused. Simply multiply the binary number quotient with base 2 and then perform addition on those numbers then you will get the answer.

(27 x 0) + (26 x 1) + (25 x 1) + (24 x 1) + (23 x 0) + (22 x 0) + (21 x 1) + (20 x 1) = 115

Huh...These many steps...its really very frustrating..Don't panic..you don't have to worry about these many steps. Let's see the same in our php code. Its really very simple.

$x=46;

$y=93;

echo $x ^ $y; // output: 115

Bitwise NOT(~) :

The Bitwise NOT operator perform on two values and returns true when set bit of one expression is not set in another expression.

Demo:

Let's take two numbers 46 and 93 respectively. Now perform binary conversion for these two numbers.

Step 1:

Converting decimal numbers 46 and 93 into their binary form. 

The binary representation of 46 - 00101110

The binary representation of 93 - 01011101

A decimal number 46 can be represent in binary form like bellow -
1 Byte ( 8 bits )
Decimal Place 128 64 32 16 8 4 2 1
0 0 1 0 1 1 1 0
27 26 25 24 23 22 21 20
0 0 32 0 8 4 2 0 = 46

A decimal number 93 can be represent in binary form like bellow -
1 Byte ( 8 bits )
Decimal Place 128 64 32 16 8 4 2 1
0 1 0 1 1 1 0 1
27 26 25 24 23 22 21 20
0 64 0 16 8 4 0 1 = 93

Step 2:

Now perform Bitwise NOT Operation on them. The output will be 00100010. Now from the above manipulation, the bit set occurs at 3rd, and 7th digits respectively.

Step 3:


Now perform addition operation on these, You will get 25 + 21 = 34.

Now you may be confused that how this answer 34 came. Don't get confused. Simply multiply the binary number quotient with base 2 and then perform addition on those numbers then you will get the answer.

Base 2 27 26 25 24 23 22 21 20
Binary 46 0 1 0 1 1 1 0 1
Binary 93 0 0 1 0 1 1 1 0
Result 0 0 1 0 0 0 1 0
 
(27 x 0) + (26 x 0) + (25 x 1) + (24 x 0) + (23 x 0) + (22 x 0) + (21 x 1) + (20 x 0) = 34

Huh...These many steps...its really very frustrating..Don't panic..you don't have to worry about these many steps. Let's see the same in our php code. Its really very simple.

$x=46;
$y=93;
echo $x &^ $y; // output: 34

Left and Right Shift:



If a and b are two numbers, BIT SHIFTING shifts a bits b number of steps. each step refers to multiply by two if it is BIT SHIFT LEFT. If it is BIT SHIFT RIGHT, then each step refers to division by two.Demo: $x=8;
$y=3;
echo $x >> $y; // output: 1
echo $x << $y; // output: 64