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.

Convert image data to base64 encoded in PHP


Here I want to show, how to convert simple image to base64 encoded data which can be used directly with the HTML <img> tag.

Step 1 : Create/Get an image which you need to convert into base64-encoded data.
Step 2 : Write the following PHP code to effect the conversion.

<?php
echo $str =  base64_encode(file_get_contents("test.jpg"));
?>

Step 3 : Base64 encoded data will be echoed on the page. We can use this base64 encoded code in HTML img tag directly as shown below.

<img
src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAALCAAQAGkBAREA/8QAGwAAAgIDAQAA
AAAAAAAAAAAABgcFCAIDBAr/xAAqEAABBQEAAgICAQIHAAAAAAAEAQIDBQYHCBQREgATFhUhJDJi
gZGi0f/aAAgBAQAAPwDxFeL+NzPQu54fJa+sS4z1sTZMsK2Qo8NpTR6g8uFqlVc4x8SftihVfWna
75RUX5aqtdcPYcS5re8v6ddL48aXx/s8M2mNo9DdaXWWYOoQq0QAiqhD1IosTY5WzM+FDSYn3CAP
kodiOEte7WeD9iX2PGm4jm8K8Zmfi5dJGuvgj/cJK2vm0zmss9I/RqqteU1VAc1zUT7A/X4Y5ZMX
hPI6Ot7BaB+P1j1svM9ksMhQ5ik0m5DMr86wH2mujnpyLGWaACaOONSbEcouVTGrIY9WJ8Va8s+V
4/n1rz2wyOZPwTtzjgb6259Znk2ZuUsHSPHlGQqwctk4WdYnvY49fa9ppqKOI1sYYxumW8f+D47m
M3V+b23VdT0vN1+0sJP5PZZSuyees5pH1UVRBVrBLdmFhpNNYQnkjMSccNleTAhMz048by3gVxqO
xdIGL02l4bygWhPDpVhfVWmjPvi2jVlIUaiQHD1EhcRI81i2OstPSWOVjBSImskyMyHDO28x3Ou5
Xzyy5VreXOrLCyz/APJLPX0+ozlocNXzlLY20qGA2tc/2C3QwjQjIEz/ACEundPVN/d5rxTxnUc5
xq14STGukAzQ02/quh6pplRNqK4X9VjDnzZ7MIiQA0tpCRTkmDKkaKoxTEUaYcG8Zuf5+nuq6+pn
XNvUeSud5825lNsw3m44uJJHhSBh2MYUTrGGWEr2oIPehST4EO/X/b8K7PxV5lD5O4ivqqFbXjmn
sNd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BoZ0E
DBhpI3RziQHk35CZ3q1ViMXkoNibQ4eS6nj1vRLplvr9KReJXTzus44GywheiQNMIOkVgX7YjRZH
+m6J0Dadf7r/AMP/APfz/9k=" alt="Test Image"/>

Check out the output as shown below.







Problem :: How to create an Image from this base64? This is very simple.

<?php
// Image Data
$image_data = 
"/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAALCAAQAGkBAREA/8QAGwAAAgIDAQAA
AAAAAAAAAAAABgcFCAIDBAr/xAAqEAABBQEAAgICAQIHAAAAAAAEAQIDBQYHCBQREgATFhUhJDJi
gZGi0f/aAAgBAQAAPwDxFeL+NzPQu54fJa+sS4z1sTZMsK2Qo8NpTR6g8uFqlVc4x8SftihVfWna
75RUX5aqtdcPYcS5re8v6ddL48aXx/s8M2mNo9DdaXWWYOoQq0QAiqhD1IosTY5WzM+FDSYn3CAP
kodiOEte7WeD9iX2PGm4jm8K8Zmfi5dJGuvgj/cJK2vm0zmss9I/RqqteU1VAc1zUT7A/X4Y5ZMX
hPI6Ot7BaB+P1j1svM9ksMhQ5ik0m5DMr86wH2mujnpyLGWaACaOONSbEcouVTGrIY9WJ8Va8s+V
4/n1rz2wyOZPwTtzjgb6259Znk2ZuUsHSPHlGQqwctk4WdYnvY49fa9ppqKOI1sYYxumW8f+D47m
M3V+b23VdT0vN1+0sJP5PZZSuyees5pH1UVRBVrBLdmFhpNNYQnkjMSccNleTAhMz048by3gVxqO
xdIGL02l4bygWhPDpVhfVWmjPvi2jVlIUaiQHD1EhcRI81i2OstPSWOVjBSImskyMyHDO28x3Ou5
Xzyy5VreXOrLCyz/APJLPX0+ozlocNXzlLY20qGA2tc/2C3QwjQjIEz/ACEundPVN/d5rxTxnUc5
xq14STGukAzQ02/quh6pplRNqK4X9VjDnzZ7MIiQA0tpCRTkmDKkaKoxTEUaY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ELFCtxAZrRQIZyQz7GntWwWiRl
ClxPf7fpxC/gDiu+cqucyFgeyUWyWnyOlttRzvZYIupF11ARaHsNnqP1WCRioCWUr7VbBpJBoZ0E
DBhpI3RziQHk35CZ3q1ViMXkoNibQ4eS6nj1vRLplvr9KReJXTzus44GywheiQNMIOkVgX7YjRZH
+m6J0Dadf7r/AMP/APfz/9k=";

// Create Image File
$fp = fopen("new.jpg", "w+");

//Write the new Data
fwrite($fp, base64_decode($img_data));

// Close the file
fclose($fp);

?>