Friday, April 12, 2013

PHP unset()

Unset destroys specified variables. I am going to show some good examples to explain how unset is applied to variables and the outcome.

Example 1 :
<?php
$foo = 'bar';
echo "At first : [$foo]";    // bar
modify_foo();
echo "<br>After modify_foo : [$foo]";  // Modified foo

destroy_foo();     // foo destroyed 

echo "<br> After destroy_foo foo is :: $foo";  
// Modified foo ... outside variable retains its value

destroy_foo_reference($foo);     // foo reference destroyed

echo "<br> At Last foo is :: $foo";  
// Modified foo ... outside variable retains its value

function destroy_foo()
{
    global $foo;
    echo "<br>Before [$foo]";  // Modified foo
    unset($foo);
    echo @"<br>After [$foo]";  

   // Outputs nothing as $foo is unavailable to this function
}

function destroy_foo_reference(&$foo)
{

    echo "<br>Before [$foo]";  // Modified foo
    unset($foo);
    echo @"<br>After [$foo]";  

   // Outputs nothing as $foo is unavailable to this function
}

function modify_foo()
{
    global $foo;
    $foo = "Modified foo";
}
?>


Output :
At first : [bar]
After modify_foo : [Modified foo]
Before [Modified foo]
After []
After destroy_foo foo is :: Modified foo
Before [Modified foo]
After []
At Last foo is :: Modified foo

The following points need to be noted.
a. Unlike some programming languages like Python, PHP functions can be declared anywhere within the code. C, C++ also have the similar structure. Functions may be declared after actual calls to them.
b. The keyword "global" brings the global version of a variable available for use and modification within any function. The function modify_foo() changes the value of $foo to "Modified foo".
c. In the destroy_foo() function, we get the modified value "Modified foo", but then the variable $foo is unset. As a result, the $foo variable in calling context is not destoyed, rather a local version destroyed so that $foo is no more available within destroy_foo() function after the unset call.
d. Next, we called a destroy_foo_reference() function which accepts $foo as a reference. In this function also, unset actually removes a local copy of $foo variable from the scope of called function only. After the function call, the $foo variable in the calling environment with old value is still available to the following part of the script. After unset call in both the above functions, we have used a "@" character with statement just to suppress the errors :

echo @"<br>After [$foo]";  // $foo is no more available. Hence this cause errors.

Example 2:
Unset() with Static variables bahave the same way as shown in previous examples. Static variables get their original value even they are unset within the function. Checkout the example below, it is self-explanatory.

<?php
function f()
{
 static $foo = 1;
 echo "<br>Beginning of f() function : [$foo]";
 $foo++;
 unset($foo);
 echo @"<br>End of f() function : [$foo]";
}

f();
f();
f();
?>


Output :
Beginning of f() function : [1]
End of f() function : []
Beginning of f() function : [2]
End of f() function : []
Beginning of f() function : [3]
End of f() function : []

$foo gets incremented in each function call and its original value is restored even after unset is called upon.

Note : Unset can not be used with variable functions. It is not a function rather a function construct.
 

<?php
$foo = "unset";
$foo();   //// Would give undefined function unset() error.
?>


Example 3:
Check out another example where unset has been used with objects and classes

<?php
class test
{
  var $foo = 1;             /// Instance Variable
 
  public function show()    /// Display
  {
    echo @"<br> \$foo is now : $this->foo";
  }
 
  public function incr()   /// Increment
  {
    $this->foo++;
    unset($this->foo);  /// Unset
  }
}

$a = new test();
$a->show();     /// 1     
var_dump($a);  
$a->incr();     /// Unset 
$a->show();     /// $foo is already gone
var_dump($a);
?>


Output:
$foo is now : 1
object(test)#1 (1) { ["foo"]=> int(1) }
$foo is now :
object(test)#1 (0) { }

The output is quite expected. The two var_dump calls show it all. The object variable $foo was removed in the incr() function call which is captured in the 2nd var_dump call.

Thursday, April 11, 2013

Variable Expansion in PHP Strings

Check out the example below. It shows how to expand variables within souble-quoted strings. Single quoted strings do not expand variables in them.

example 1:
<?php
$foo = "bar";

// To print "bar"
echo "{$foo}";

// To print "{bar}"
echo "{{$foo}}";
?>


What will be output of the following php code?

example 2:
<?php
$a = "php";
$php = "is";
$is = "really";
$really = "good";
$good = "language";
echo "This is the TEXT :: {${${${${$a}}}}}";
?>

Answer : language

Explanation : The variables are being expanded within the string, the $a giving "php" and eventually making it to $php resulting to $is and ultimately the value of $good is evaluated and its value gets printed on screen. Checkout some more complex string statements below.

example 3:
<?php
$arr['foo'][1]['bar'][2] = "general";
$general = "PHP is great";
echo "Text is :: ${$arr['foo'][1]['bar'][2]}";
?>


Output :
Text is :: PHP is great

example 4:
<?php
function a()
{
  return "a function";
}
echo "This is {a()}";  /// Does not expand
?>


Output :
This is {a()}

PHP tokenizer looks for a dollar sign ($) inside double quoted strings when to expand.

example 5:
<?php
class a
{
  public function extra()
{
  return "Extra String";
}
}

$aa = new a();
echo "Text is :: {$aa->extra()}";  // This expands
?>


Output :
Text is :: Extra String

example 6:
<?php
echo "Text is :: {$this}";  // Error :: $this undefined
?>


Output :
Text is ::

$this is available when a method is called from within an object context. "this" pseudo-variable is not available in non-OOP structure. Check out some more examples below.

example 7:
<?php
class a
{
  public static $n = 0;
  const method = "concrete";
}
$concrete = "Sample";

echo "Text is :: {a::method}";
// Does not Expand.

echo "Text is :: {${a::method}}";
// But this expands, Output 'Text is :: Sample'
?>


"Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables." - from php.net. Simple constants are also not expanded within strings. Check out the example below.

example 8:
<?php
define ("fuss", "foo");   
echo "{fuss}"; // Does not expand
?>


Now check some other examples.

example 9:
<?php
$b = 100;
$a = 40 + " {$b} floating point";
echo $a;
?>


Output : 140

example 10:
<?php
function f($s)
{
  echo  $s;
}
$var = "it";
$it  = "is";
$is  = "PHP";

f( <<
<
${${$var}}
EOD
);
?>


Output : PHP


The construct
${${$var}} ultimately evaluates to "$is" . So, the f() function is called with "PHP" as argument. One thing to be noticed here is that, the heredoc ends with "EOD", not "EOD;". Giving a semi-colon would cause a syntax error. 

Another very interesting part is that PHP also allows function calls inside stings. The syntax is a little complex ... this is shown below.

<?php
$john = 'JEFF SMITH';
$young_jeff_smith = 'Mr. Henry Illinois';

print "$john's real name was ${"young_".strtolower(str_replace(" ","_","$john"))}.\n";
?>


The output is : JEFF SMITH's real name was Mr. Henry Illinois.

The print statement above is a little complex and it contains some unnatural parts, however it runs perfectly. This statement also involves function calls inside string. Notice how we have used multiple double quotes inside curly braces without breaking the string construct.

str_replace(" ","_","$john") => This replaces all spaces with underscores in variable $john. This makes the string 'JEFF SMITH' become 'JEFF_SMITH'. Next, the strtolower() function converts it to 'jeff_smith' and finally when it is appended to 'young_', it becomes 'young_jeff_smith'. Now ${young_jeff_smith} can be easily expanded. So, "$john's real name was ${young_jeff_smith}" finally becomes "JEFF SMITH's real name was Mr. Henry Illinois".


Some more examples given below.

<?php
$plum = "sweet";
echo "{${strtolower("PLUM")}}"; // sweet

$p = 'is';
$lop7 = "Cheaper";

// Below line does not expand as '$' is missing
echo "Salt {strtolower('P')}";  // Salt {strtolower('P')} 

echo " ";
echo "{${strtolower('P')}}"; // is
echo " ";

// The below line expands and evaluates to '$lop7'
echo "{${"lop" . strlen("chandan")}}";  // Cheaper
?>

Functions are expanded within string if '$' and curly braces are placed properly.  The last statement ultimately evaluates to "$lop7" which is then searched for a variable with the same name and its value is printed.

Wednesday, April 10, 2013

Basic Regular Expression Patterns VII


1. Problem : Check if the given string is a valid IP adderss. IP addresses (IPv4) are represented in dot-decimal notation consisting of 4 decimal parts where each part ranges from 0 to 255.
  
   answer  :
 var patt = /^((2[0-4][0-9]|25[0-5]|[1]?[0-9]?[0-9]{1})\.){3}(2[0-4][0-9]|25[0-5]|[1]?[0-9]?[0-9]{1})$/;
 patt.test("200.10.0.1");  //true
 patt.test("100.100.0.1"); //True
 patt.test("340.100.0.1"); //False

  
   Explanation :
   First, we would be looking at ((2[0-4][0-9]|25[0-5]|[1]?[0-9]?[0-9]{1})\.){3} part. The next part will be automatically understood.
   ((2[0-4][0-9]|25[0-5]|[1]?[0-9]?[0-9]{1})\.){3} means a pattern is repeated 3 times. In an IP address, "{digits}." (digits and dot) are repeated 3 times and then one sequence of digits appear. For example in "255.255.255.123", "255." is repeated thice. Let's break up the RegExp.
   a. 2[0-4][0-9] means the number may be between 200 to 249
   b. | means OR
   c. 25[0-5] means the number may be 250 though 255. Till this point, 200 to 255 numbers are clready checked
   d. [1]?[0-9]?[0-9]{1} checks whethe the number is between 0 to 199. Hence till this point, all numbers between 0 to 255 are checked and captured. This REGEXP is discussed in Basic Regular Expression Patterns IV
   e. \. means dot
   f. So, together ((2[0-4][0-9]|25[0-5]|[1]?[0-9]?[0-9]{1})\.){3} means a sequence of numbers from 0 to 255 and a dot would appear thrice
   g. The last (2[0-4][0-9]|25[0-5]|[1]?[0-9]?[0-9]{1}) means another number from 0 to 255 would appear at the end.

   Google also provides a very handy tool for generating RegEx for validating any specific IP address range.

2. Problem : How to check for doubled words and remove them from a given string in Javascript
   Suppose, we have the following string which have some words repeated inside it.
    

 var str = "We love love our our God God";
  

  Problem is how to remove the duplicated words.

   answer :
   var patt = /\b(\w+)\s+\1/g ;
 var str = "We love love our our God God";
 var c = str.replace(patt, "$1");
 console.log( c );


   Output :
   We love our God

   Explanation :
   a. \b means a word boundary. This is for identifying "love" as a whole word.
   b. (\w+) means a sequence of alphanumeric word characters
   c. \s+ means one or more whitespaces comes next
   d. \1 means we want to use the backreference. This is to detect " love love ", " our our "," the the "  etc. The first match will be refered to as \1 by REGEXP engine.
   e. /g means we want a global search. Otherwise the search would stop after it found the first doubled word "love love".

   When we use the javascirpt replace function, we need to provide the new string also which would be taking the place of old words/characters. By specifying $1 as the second argument, we tell "replace" function to use the first matched element or first capture as replace string for each match. This means, when the REGEXP engine finds "love" as a doubled word, "$1" refers to that "love" itself and hence "love love" is replaced with a single "love". Similar thing happens for the word "our" due to the usage of global flag /g. The REGEXP engine again looks for doubled word and it finds "our" as a doubled word; "$1" in replace function refers to that "our" itself as a first capture and hence "our our" is replaced with a single word "our".

Tuesday, April 09, 2013

Basic Regular Expression Patterns VI

1. Problem : Write validators for Visa Credit Cards
   Visa credit card numbers are composed of 16 digits and they start with digit 4
  

  answer :
   var patt = /^4[0-9]{15}$/;
    

  Explanation :
   a. 4 means the string starts with '4'
   b. [0-9]{15} means any digit between 0 to 9 should appear 15 times

   New Visa cards have 16 digits while the old cards used to have 13 digits. Let's write a REGEXP which captures both the old and new valid cards.
   

 var patt = /^4[0-9]{12}([0-9]{3})?$/;
    

  Explanation :
   a. 4 means the card number must start with '4'
   b. [0-9]{12} means, any digit between 0 to 9 should appear 12 times. So, up this point, already 13 digits have been tested for old cards
   c. ([0-9]{3})? means, a sequence of 3 digits may or may not appear. ? means either zero or one occurence. This point would validate if this is a new 16 digits card number.

2. Problem : Write validators for MasterCard Credit Cards
   Visa credit card numbers are composed of 16 digits and they start with numbers 51 thorugh 55
   

   answer :
   var patt = /^5[1-5][0-9]{14}$/;
    

  Explanation :
   a. 5[1-5] means the string starts with '5' and then anything between 1 and 5. This ensures the number always have 51,52,53,54 or 55 at the beginning.
   b. [0-9]{14} means any digit between 0 to 9 should appear 14 times
  
3. Problem : Write validators for AMEX [American Express] Credit Cards
   American Express credit card numbers are composed of 15 digits and they start with numbers 34 or 37
   

  answer :
   var patt = /^(34|37)[0-9]{13}$/;
  

  Explanation :
   a. (34|37) means the number must start with '34' or '37'
   b. [0-9]{13} means any digit between 0 to 9 should appear 13 times
  
   We can write the above REGEXP slight differently as shown below.
  

 var patt = /^3[47][0-9]{13}$/;
    

  Explanation :
   a. 3 means the number must start with '3'
   b. [47] means the next digit should be either '4' or '7'
   c. [0-9]{13} means any digit between 0 to 9 should appear 13 times


Check the next part of this article here

Basic Regular Expression Patterns V

1. Problem : Check whether a number is between 1 to 999
   answer  :
   var patt = /^[1-9][0-9]{0,2}$/;    
 patt.test("1001"); //false
 patt.test("100");  //True


  Explanation :
   a. [1-9] means the string may only start with 1 to 9 only. Zero won't be captured here.
   b. [0-9]{0,2} means, next any sequence of digits may or may not appear. If appears, maximum length of that would be 2.
      So, for a number like 100, the starting "1" is captured in point a above, and two zeros will be captured in point b.
      Number like 34, the starting "3" is captured in point a above, and "4" will be captured in point b.
      Number like 7, the starting "7" is captured in point a above, and rest "" will be captured in point b as the length can be zero.
  
   c. If we want to modify the requirement as "Check whether a number is between 1 to 9999", we would simply change the range from {0,2} to {0,3} as shown in the example below.
   var patt = /^[1-9][0-9]{0,3}$/;    
 patt.test("10010"); //false
 patt.test("100");   //True
 patt.test("9990");  //True

 

2. Problem : Find number of HTML tags used in the given HTML text [Closing Tags excluded]
   answer  :
  var patt = /<([a-z][a-z0-9]*)>/g;
 var text = "<html>
<b>Bold</b><i>Italics</i><u>underlined</u></html>";
 var c = text.match( patt );
 console.log( c.length );  // 4
 console.log( c );         // "
<html>","<b>","<i>","<u>"

 Explanation :
   a. Capture HTML tags starting with '<'
   b. ([a-z][a-z0-9]*) means the capturing group must find any alphanumeric character that follows "<"
   c. '>' means the HTML tag ends with this character
   d. /g means we want it to be a global search, means we don't want to quit after one match is found somewhere before the string ends.

   The above REGEXP only finds simple HTMP opening tags, it does not look for closing tags. But our next REGEXP does that too.


3. Problem : Find number of HTML tags used in the given HTML text [Closing Tags included]
  answer  :
 var patt = /<([^>]*)>/g;
 var text = "<html><b>Bold</b><i>Italics</i><u>underlined</u></html>";

 var c = text.match( patt );
 console.log( c.length );  // 8
 console.log( c );         // "<html>","<b>","</b>","<i>","</i>","<u>","</u>","</html>"
  

  Explanation :
   a. Capture HTML tags starting with '<'
   b. [^>]* means the capturing group must find anything that is not a ">". This also captures closing tag literals like "/a", "/i" , "/html" etc.
   c. '>' means the tag ends with this character
   d. /g means we want it to be a global search


Check the next part of this article here.

Monday, April 08, 2013

Basic Regular Expression Patterns IV

1. Problem : Check for a 10 digit long mobile phone number that starts with either 9 or 8
   Answer  :
   var patt = /^(8|9)[0-9]{9}$/;
 patt.test("6547896520");  // False
 patt.test("9547896520");  // True


  Explanation :
   a. (8|9) means the string must start with either 8 or 9
   b. [0-9]{9} means after the initial digit 8 or 9, a sequence of 9 digits should appear.
     
2. Problem : Check whether a number is between 0 to 199
   Answer  :
   var patt = /^[1]?[0-9]?[0-9]{1}$/;
 patt.test("500"); //false
 patt.test("100"); //True


   Explanation :
   a. [1] means the string may start with 1 at hundreds position. Remember the number can go maximum 199.
   b. [0-9]? means, next digit at tens position can be any digit between 0 and 9. "?" means this may or may not appear.
   c. [0-9]{1} means at unit position, 1 digit must appear.

   So, numbers like "1" or "33" or "167" is captured as valid whereas "234" would be treated as invalid. The above REGEXP would allow "0" or "00" as a valid. To make the range 1 to 199 we would require some more complex REGEXP which will be discussed next.

3. Problem : Check whether a number is between 1 to 199
   Answer  :
   var patt = /^([1-9]{1}|[1-9][0-9]|[1][0-9][0-9])$/; 
 patt.test("210"); //false
 patt.test("100"); //True


   Explanation :
   a. [1-9]{1} means the string may be a single digit number ranging from 1 to 9 only. Zero won't be captured here.
   b. | means OR. We are checking multiple patterns at a time, if any of them is matched the result is TRUE.
   c. [1-9][0-9] means the string may be a double digit number ranging between 10 to 99.
   d. [1][0-9][0-9] means the string may be a 3-digit number ranging between 100 to 199 only, as [1] ensures the number must start with 1. Hence number 200 onwards are discarded.


Check next part of this article here.

Friday, April 05, 2013

Running WordPress on IIS Server

Earlier, I had faced a problem while running WordPress on a GoDaddy server which runs on IIS. The homepage was coming properly but other permalinks were mostly giving 404 error. Thank god, the admin panel was opening. I had tried rebuilding the permalinks from Settings>Permalinks option which actually modifies the .htaccess did not help because on IIS sever, .htaccess file remains inactive. Rebuilding permalinks showed me one message saying "You need to update web.config file" which reminded me of the fact that the substitute for .htaccess on IIS server is web.config file which resides at the root folder, similar to where .htaccess is placed on an Apache server. I got the following code after googling a bit regarding the web.config, and once I put the new web.config file with the content shown below everything simply changed back to normal. This is worth checking ...

<?xml version="1.0"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Main Rule" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.php" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Wednesday, April 03, 2013

Basic Regular Expression Patterns III

1. Problem : Trim a string i.e remove multiple whitespaces from both end of the string.
    Answer :
   var patt = /^\s+|\s+$/
 var str  = "   (This needs to be trimmed)     ";
 str = str.replace(patt, "");
 console.log(str); //(This needs to be trimmed)

  
   Explanation :
   a. ^\s+ means one or more whitespaces at the beginning of the string
   b. | means OR
   c. \s+$ means one or more whitespaces at the end of the string
   So, the whole pattern tries to match with one or more whitespaces at the beginning of the string OR one or more whitespaces at the end of the string and REPLACES them with "" [The second parameter of the function replace()].

2. Problem : Remove all digits from a given string
    Answer :
   var str = "AVF67H90-TGSE23JU-O7T6E32";
  var patt = /[0-9]/;
  str = str.replace( patt, "" );
  console.log(str); //AVF67H90-TGSE23JU-O7T6E32


   Explanation : The problem with the above REGEXP Pattern is that is only replaces the first occurrence of any digit from the string. As a result, the fouth character '6' is replaced from the whole string. We just need to change the pattern as shown below.
   

 var patt = /[0-9]/g;  
// We added a global modifier by mentioning 'g'

 By using modifier 'g', we mean that all occurrences of the matching pattern should be changed/replaced.
 The answer is : AVFH-TGSEJU-OTE

3. Problem : Remove all non-digits from a given number
     Answer :
  var str = "#$%AV^^&?.>-=+_)(*&F67H90-TG{}\'|}{~!@#$%SE23JU-O7T6E32";
  var patt = /[^\d]/g;
  str = str.replace( patt, "" );
  console.log(str); //6790237632


   Explanation :
   a. \d means all digits
   b. [^\d] means capture all those single character which is not a digit. "^" inside [] means we don't want to capture the specified character(s)
   c. /g means global replacements


Check out the (xxx)xxx-xxx formatted phone number validation in Javascript.

Check out the next part of this article here.

Thursday, March 28, 2013

Basic Regular Expression Patterns II

Here I'll be discussing some common problems which can be solved with Regular expressions in Javascript.


1. Problem : Check whether a given phone number is in (xxx)xxx-xxx format.
   Answer :
   var patt = /^\([0-9]{3}\)[0-9]{3}-[0-9]{3}$/;
 patt.test("(123)456-678");  // true

  
   Note : The character "(" has been denoted as "\("; similarly the character ")". Both were escaped. This can be changed to "[(]" and "[)]" as shown in the example below.
  
   var patt = /^[(][0-9]{3}[)][0-9]{3}-[0-9]{3}$/;
  patt.test("(123)456-678");  // true


   Equivalent PHP statement would be as shown below :
  
   $patt = "/^\([0-9]{3}\)[0-9]{3}-[0-9]{3}$/";
  echo preg_match($patt,"(234)234-456");  // 1
  $patt = "/^[(][0-9]{3}[)][0-9]{3}-[0-9]{3}$/";
  echo preg_match($patt,"(234)234-456");  // 1

  
2. Problem : Check whether a given location is in city_name, state format. Example : New York, NY
   

   Answer :
   var patt = /^(.*),\s[A-Z]{2}$/;
 patt.test("Saint George Island, AK"); // true
 patt.test("Saint George Island,AK");  // false, a space was expected after comma


3. Problem : Check whether a given email is in name@domain.com format.
   

    Email formats can be of various types. It is really difficult to build a small REGEX to catch right formatted email addresses. The domain names can be like gmail.com or yahoo.ac.in, or 1234.com. Email addess can be as complex as  !#$%&'*+-/=?^_`{}|~@example.org or "()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a"@example.org or even " "@example.org. We would keep it to simple addresses like john.smith@dert.com or john.smith@yahoo.ac.in which falls within most used email formats.
   

   Answer :
   var patt = /^[A-Za-z0-9]{1}([A-Za-z0-9_]*)(\.[A-Za-z0-9_]+)*[a-zA-Z0-9_]*@([A-Za-z0-9]+)([A-Za-z0-9_]*)(\.[A-Za-z0-9]+)+$/;
 patt.test("john.smith@edu.co.au");

   

   Explanation ::
   a. ^[A-Za-z0-9]{1} means the string should start with alphanumeric character only. No dot or underscore is allowed at the beginning of email address.
   b. ([A-Za-z0-9_]*) means, next any alphanumeric or underscore may occur
   c. (\.[A-Za-z0-9_]+)* means, next a sequence of dot(.) and a series of characters may occur. For example, in j.g.h@gmail.com, the [.g] and [.h] portions are matched by this pattern. a._a._@gmail.com is a valid address but a._a._.@gmail.com is invalid and the local part [part before @] can not end with a dot (.).
   d. @ means the string should have a '@' character.
   e. ([A-Za-z0-9]+) means, after '@', alphanumeric character should only appear immediately. No dot(.) or underscore should appear immediately after '@'. For example, abc@_23.com is not valid address as underscore has appeared immediately after @.
   f. ([A-Za-z0-9_]*) means, after that, any length of alphanumeric characters including underscore may appear.
   g. (\.[A-Za-z0-9]+)+ means, next, any series of dot (.) and characters i.e ".ac", ".in" etc may occur minimum 1 time.
  
   However, we did not put a check on the following points.
   i. Domain names must end with ".com",".biz",".me", ".org",".net" etc.
   ii. Complex email addresses like "()<>[]:,;@\\\"!#$%&'*+-/=?^_`{}| ~.a"@example.org can not be tested with the pattern above.


Check the 1st part of this article here 
Check the 3rd part of this article here

Friday, March 22, 2013

Check stucture of any DB table in PHP

We can use two SQL commands to get the structure of any table as shown in the code below :

Command format :
1. EXPLAIN  table_name;
2. DESCRIBE table_name;

PHP Code :


<?php
// MySQL Connect
$con = mysql_connect("localhost","root","");


// Select DB
mysql_select_db("test_db", $con);


// RUN QUERY
$res = mysql_query("EXPLAIN employee");


// Fetch Data
while( $row = mysql_fetch_assoc($res))
{
  print_r($row);
}
?>


Output :
Array
(
    [Field] => fname
    [Type] => varchar(100)
    [Null] => NO
    [Key] =>
    [Default] =>
    [Extra] =>
)
Array
(
    [Field] => mname
    [Type] => varchar(100)
    [Null] => NO
    [Key] =>
    [Default] =>
    [Extra] =>
)

...

The above output clearly displays details of a table 'employee' within the DB 'test_db'. The  columns are 'fname', 'lname' and do on ... 

Thursday, March 21, 2013

Ajax Problem in IE

I am sharing an Ajax problem that I had faced earlier with IE. Check the following Javascript code out.

<script>
var site_url = "http://example.com/";
// A function which fetches content thru Ajax
function load_cities_for_state(statename, target_elem)
{
  jQuery.ajax({
        url:  site_url + "ajax.php",
        type: 'POST',
        data: "load_city_for_state=1&state_name=" + statename,
        success: function(response) 

        {
            jQuery('#'+target_elem).html(response);
        }
    });
}
//// Function ends here

</script> 

Very simple code; its purpose is to call ajax.php, get the response and place the response in a target element. Problem was it was not running on IE. Even though it ran perfectly on local Xampp installation, it severely failed when ran from an online server.

The problem was with the "url" parameter in the Ajax call, which has "http://" in it. This made the whole Ajax calling process fail. Probably IE assumes that it is a cross-domain ajax call.

Rewriting the function following way fixed this issue.

function load_cities_for_state(statename, target_elem)
{
  jQuery.ajax({
        url:  "ajax.php",
        type: 'POST',
        data: "load_city_for_state=1&state_name=" + statename,
        success: function(response) {
          jQuery('#'+target_elem).html(response);
        }
    });
}


But this won't be a solution when you use custom URL in your website i.e http://www.findpeople.com/state/CA/city/San_Jose. Calling "ajax.php" would mean the path of the said file is  http://www.findpeople.com/state/CA/city/San_Jose/ajax.php which is wrong. The solution to it would be to declare a <base> tag in the header of your website as shown in the line below.

<base href='http://www.findpeople.com/' />

Mentioning a base URL for all the pages of your site, calling "ajax.php" through Ajax would always give "http://www.findpeople.com/ajax.php" as server URL.

Tuesday, March 05, 2013

Default Parameters in PHP

Using default parameters with functions is same as using it in C++. Only difference is in the function declaration. In C++, you must define default values from right end. 

For example :

// Valid in C++
int test( int i , long j = 10) {}   


// Invalid in C++, you must start providing the default value from right end
int test( int i = 10, long j ) {}   



But in php, the second statement above is a valid function declaration but you need to call the function as shown below:

// Function Definition
function test( int i = 10, long j ) {}

// Valid call
test(2,4); 

// Invalid, will give "Missing argument 2 for test()"
test(1); 


The calling rules are same for both php and c++ function calls.

Another example :


// Function Declaration
function test($a = 4, $b, $c = 10) {}  


// $c gets 10 from default parameters
test(8,9);           


// Invalid call as Argument 2 is missing
test(9);                

Thursday, December 20, 2012

PHP Include and Include_once

What will be the output of following PHP code snippet?

<?php
$i=0;
include_once( "inc.php");
echo "$i";
include( "inc.php");
echo "$i";
include_once( "inc.php");
echo "$i";
include( "inc.php");
echo "$i";

?>

Content of "inc.php" is given below..


<?php
$i++;
echo "Included :: $i";
?>


Answer ::
---------------
Included :: 1
1
Included :: 2
2
2
Included :: 3
3

Discussion ::
-------------
The first "include_once()" includes the file once which increments the value of $i to 1. Hence the first output is shown from first inclusion of inc.php.

Next "include()" statement again includes the inc.php which increments the $i to 2 and the output follows.

Next "include_once()"  does not include the "inc.php" as it was previously included... Hence the old value of $i [2] is retained.

The last "include" again includes the "inc.php" and hence increments the $i again to make it to 3.

AGain check the output of the following code snippet

<?php

$i=0;
include( "inc.php");
echo "$i";
include_once( "inc.php");
echo "$i";
?>


The output ::
---------------
Included :: 1
1
1

Discussion ::
---------------
The first "include()" includes the file "inc.php" which increments the value of $i to 1 and prints the  first line as shown in the output above.
Next "include_once()" does not include the file again ... hence the last value of $i (1) is retained.

Friday, December 14, 2012

How to create stylish SelectBox with HTML and Javascript

We can create good-looking selectbox in various ways ... one of them is described below.

1. We'll use a DIVwith a background image which will represent the finally good looking selectBox
2. We'll put a SelectBox inside the DIV and make the SelectBox completely invisible by setting its opacity to zero and Z-index to 100
3. We'll have a SPAN [Sibling to SelectBox] inside the DIV, which will show the final text after we select an Item from the SelectBox

Process ::

1. We are shown the SPAN with a default text
2. When we click on the DIV, the SelectBox receives the click because of having the highest z-index
3. One JS function runs when click event is captured on the SelectBox and that function extracts the textContent from the SelectBox and puts it in the SPAN


 -----OUTER DIV ----------------------------------------
|  -- SelectBox [Invisible but stays at the top] -----  |
| |                                                   | |                            
| |___________________________________________________| |
|                                                       |
|  -- SPAN [Holds the text] --------------------------  |
| |                                                   | |                            
| |___________________________________________________| |
|                                                       |
|-------------------------------------------------------|


Check the code below and see the effect

<script type='text/javascript'>
  function run(elem)
  {
    var p = elem.nextElementSibling;
    if( elem.value!='')
     p.innerHTML = elem.options[elem.selectedIndex].textContent;
    else
     p.innerHTML = "Select Order";   
  }
 </script>

<div>
  <!-- OUTER DIV STARTS -->
  <div class="select1" style='height:25px;display:block; background: url("bg_select.png") no-repeat scroll 1px 2px transparent;'>
        <!-- SELECTBOX Starts -->
    <select title="Select Order" class="select2" id="select" onchange="run(this)" name="data[productsortoforder]" style="z-index: 10; opacity: 0;">
        <option value="">Select Order</option>
        <option value="name-asc">Name: Ascending</option>
        <option value="name-desc">Name: Descending</option>
        <option value="price-lowtohigh">Price: Low To High</option>
        <option value="price-hightolow">Price: High To Low</option>
    </select>
        <!-- SPAN STARTS -->
    <span style='border:0px solid red; margin-left:-137px;margin-top:3px; position:absolute; font-family:helvetica; font-size:12px'>Select Order</span>      
  </div>
</div>


Check the final getUp as displayed below ::



Save the picture below as bg_select.png and run the above code to check the effect.


Friday, November 23, 2012

Basic Regular Expression Patterns I

Here, I'll discuss on the usage of Regular Expressions in various validation checking. We are using Javascript Regular expression patterns. These patterns can be tested on any input end-user provides.

Example 1. Input NUMBER

Conditions :
1. The input number must be 8 digit long
2. It should start with '5', '6' or '9'

Code :
var pattern = /^[569]{1,1}[0-9]{7,7}$/  
var tel_no  = "56895869";  // User Input
pattern.test(tel_no);      // Will return true as Pattern is matching

Example 2. Input STRING

Conditions :
1. The input string should start with the letter 'T' in capital
2. The second letter is a vowel
3. Second letter is small case letter
4. The third letter is any small letter non-digit character
5. The whole string is a 3-letter word.


Code :
var pattern = /^T[aeiou][a-z]$/;

Example 3. Input STRING

Conditions :
1. The string should start with any non-digit character including underscore
2. The string can have only underscore as special character.
3. The string can have maximum 10 characters.

Code : 

var pattern = /^[^0-9_][0-9a-zA-Z_]{0,9}$/;

Example 4. Input STRING

Conditions :
1. The input string must have the word "Band"


Code :
var pattern = /\bBand\b/;

Discussions :: The '\b' modifier is used to find word boundaries. That means string like

"Band, great!!!"
"Test Band..."
"This is my Band. Great na?",
"Nice Band!!!"
"OK!!Band starts now"
"Good Band"

will test true against the pattern. This pattern matches for "Band" followed by a newline character, "Band" word followed by punctuation mark or any such mark followed by the word "Band" etc.

Strings like 

"Great Bands"
"Bands of Britain"

will always return false because "Band" has not appeared as a single word. Check next part of this article here.

Tuesday, November 06, 2012

MYSQL :: Concatenation of columns in multiple rows

Suppose, we have a table as shown below ::

ID Animal_name
1 Lion
2 Tiger
3 Monkey
4 Horse
The "animal_table" table

Suppose, the table has a name "animal_table". Now, I want to have all the values in the "Animal_name" column to be merged into a single string. We can do it in MySQL itself with the help of "GROUP_CONCAT" function as shonw below.

SELECT group_concat( `Animal_name` SEPARATOR ', ' ) FROM `animal_table` 

The output is shown below :
Lion, Tiger, Monkey, Horse

The phrase "SEPARATOR ', '" actually defines the glue string which merges the values together.

If we want the whole table sorted before the concatenation, we would write the query as follows.

SELECT group_concat( DISTINCT `Animal_name` ORDER BY `Animal_name` SEPARATOR ', ' ) FROM `animal_table`

"DISTINCT" has to be used with "ORDER BY" clause.

Monday, November 05, 2012

Output buffering in PHP


I have a very small yet so interesting code sample on buffering in PHP.

Suppose, I have my web-page divided in two segments.. 

1. Main PHP [main.php] for all logic.
2. Template PHP file [template.php], which I include at the bottom of main.php.

Main.php
----------
<?php
include("template.php");
?>

template.php
----------------
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
This is a test template. This test template works well. I want to learn more about PHP templates. This test template is finally working perfectly.
</body>
</html>


Problem :: How to change all occurrences of the word "test template" to "template" without modifying the template file itself?

Solution :: We can manipulate the buffer features that comes with PHP and by doing that we can make required changes to the output PHP script generates before rendering onto browser. 

We need to change the main.php as shown below.

<?php
function show($buffer)
{
  return str_replace("test template","template",$buffer);
}

// Start The Buffer with show() function 
// as a callback ob_start("show"); 
include("template.php");

// Send the Buffer content to Browser
ob_end_flush();
?>

The line "ob_start('show')" line tells PHP server to start buffering the server output and apply the show() function as CallBack on the output. That means, all occurrences of the phrase "test template" are changed to "template" before they are finally sent to browser. And lastly, ob_end_flush() function renders the output to the browser. So, the output of the above script is shown below.

This is a template. This template works well. I want to learn more about PHP templates. This template is finally working perfectly.

Image data handling in PHP


If you are recieving any Image data from any iPhone or other mobile devices, your image data may come in another hex coded format as displayed below. Here I am showing the methods for ::

1. Creating such hex coded image data from an image file in hard disk
2. Retrieving/recovering back the original image file from that hex coded data.

1. To create such hex coded data, use the following code

<?php
// READ the image file content and then 
// strtohex() the data
echo strtohex( file_get_contents( "small.jpg" ) );


function strtohex($dec)

{
$str = '';
for ($i=0; $i < strlen($dec); $i++)
{
$k = "";
 
// Space after every 4 HEX numbers
  if( $i>0 && $i %4 == 0 ) $k = " ";
 
// GET ASCII
  $v = dechex( ord( $dec[$i] ));
  
  // Prefix a '0' if the HEX number is 1 digit long
  if(strlen($v) == 1 ) $v = "0".$v;

  $str .= $k . $v;

}
return $str;
}
?>

The above code had generated the following output with the image I input :

ffd8ffe0 00104a46 49460001 01010060 00600000 ffdb0043 00020101 02010102 02020202 02020203 05030303 03030604 
04030507 06070707 06070708 090b0908 080a0807 070a0d0a 0a0b0c0c 0c0c0709 0e0f0d0c 0e0b0c0c 0cffdb00 43010202 
02030303 06030306 0c080708 0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0c0c0c 
0c0c0c0c 0c0c0c0c 0c0c0c0c 0c0cffc0 00110800 0f001603 01220002 11010311 01ffc400 1f000001 05010101 01010100 
00000000 00000001 02030405 06070809 0a0bffc4 00b51000 02010303 02040305 05040400 00017d01 02030004 11051221 
31410613 51610722 71143281 91a10823 42b1c115 52d1f024 33627282 090a1617 18191a25 26272829 2a343536 3738393a 
43444546 4748494a 53545556 5758595a 63646566 6768696a 73747576 7778797a 83848586 8788898a 92939495 96979899 
9aa2a3a4 a5a6a7a8 a9aab2b3 b4b5b6b7 b8b9bac2 c3c4c5c6 c7c8c9ca d2d3d4d5 d6d7d8d9 dae1e2e3 e4e5e6e7 e8e9eaf1 
f2f3f4f5 f6f7f8f9 faffc400 1f010003 01010101 01010101 01000000 00000001 02030405 06070809 0a0bffc4 00b51100 
02010204 04030407 05040400 01027700 01020311 04052131 06124151 07617113 22328108 144291a1 b1c10923 3352f015 
6272d10a 162434e1 25f11718 191a2627 28292a35 36373839 3a434445 46474849 4a535455 56575859 5a636465 66676869 
6a737475 76777879 7a828384 85868788 898a9293 94959697 98999aa2 a3a4a5a6 a7a8a9aa b2b3b4b5 b6b7b8b9 bac2c3c4 
c5c6c7c8 c9cad2d3 d4d5d6d7 d8d9dae2 e3e4e5e6 e7e8e9ea f2f3f4f5 f6f7f8f9 faffda00 0c030100 02110311 003f00f8 
3bc4dff0 428d2ad7 e0d477da 37c5ed42 ff00e211 fd9d6dbf 6919345b df0725a6 8cba3318 fed16035 14bf9663 7880ca53 
fd084721 440cf16f 253d43c6 3ff06b2f 8abc07f1 b3e2b787 356f881e 20d37c31 e01f15f8 03c31a0f 8a6efc03 34161e35 
ff00849b 50b4b1b9 9ed59aec 47ff0012 e92ec091 23925dec a159a02d c7c9ff00 b70ffc15 b3c7dfb6 07c1af85 7f0e74fd 
43c61e08 f87bf0fb e1ae83e0 1d4fc316 fe2bb9b8 d1bc5171 a5962baa 4d68ab14 22472202 11924286 da3fde36 d5dbf485 
ff00fc1c 85f6dfda 9fe3cfc4 cff8535b 7fe17778 afe1bf89 ff00b37f e12dcff6 2ffc2217 96b73e47 9bf62fdf 7db3ecdb 
77ec8fc9 df9db2e3 0403c3ff 006f8ff8 24e695fb 25fc02f1 27c46f08 7c49d43c 71a2781b e306a9f0 53c4506b 1e174d06 
ea2d66ca dbed1f68 b458af6f 127b3744 986f91e0 914ac7fb a60e4a15 e41fb7c7 edf1e3ef f8281fc7 df1278bf c5fe24f1 
85f6897d e20d5358 f0ef8775 8f115cea f6be11b7 bdb9f3be c569e6e1 238d1161 8ff771c6 18411fca 02800a00 ffd9 

2. Now to get back the original Image file from the above output, check the following code snippet.


<?php

// Take the whole data in a variable
$image_data = "ffd8ffe0 00104a46 49460001 ...."  ; 

// Remove Spaces

$img_data = str_replace(" ","", $image_data);

// Convert From HEX to String

$img_data = hextostr($img_data);

//Create a new file

$fp = fopen("original.jpg" ,"w+");

//Write data to file

fwrite($fp, $img_data);

// Close the file

fclose($fp);

function hextostr($hex)

{
$str = '';
for ($i=0; $i < strlen($hex)-1; $i+=2)
{
$m = hexdec($hex[$i].$hex[$i+1]);
$str .= chr( $m );
}
return $str;
}
?>

The code above is quite self-explanatory. It takes every 2 bytes of image data, converts them to decimal and then a corresponding ASCII character is generated.

Check article on How to Convert image data to base64 encoded in PHP.