Learning Is Fun

Talks on Web Technology and Better Product Development

PHP: Convert number & currency to text in asian i.e. Bangladeshi, Indian format

January28

Hello Guys,

I am from Bangladesh and our currency system is somewhat different. We use lac/lakh, crore etc. So, today I had to convert number to word in a project. When I was searching the web, I did not found anything that meets my requirement 100%. So I wrote one. Although my code does not support more than 999 crore taka / rupee, I think this will suffice most of the projects requirements.

To be frank I used several pieces of beautiful code from internet.

Well. Enough talks. Let me show the code.

CODE:

================================================

{code type=PHP}

error_reporting(E_ALL);
//error_reporting(0);

class Currency
{

function __construct()
{
//do nothing for now
}

// http://www.phpbuilder.com/board/showthread.php?t=10350901
function get_bd_money_format($amount)
{
$output_string = '';
$fraction = '';
$tokens = explode('.', $amount);
$number = $tokens[0];
if(count($tokens) > 1)
{
$fraction = (double)(’0.’ . $tokens[1]);
$fraction = $fraction * 100;
$fraction = round($fraction, 0);
$fraction = ‘.’ . $fraction;
}

$number = $number . ”;
$spl=str_split($number);
$lpcount=count($spl);
$rem=$lpcount-3;
//echo “rem”.$rem.”
“;
//even one
if($lpcount%2==0)
{
for($i=0;$i<=$lpcount-1;$i++)
{

if($i%2!=0 && $i!=0 && $i!=$lpcount-1)
{
$output_string .= ",";
}
$output_string .= $spl[$i];
}
}
//odd one
if($lpcount%2!=0)
{
for($i=0;$i<=$lpcount-1;$i++)
{
if($i%2==0 && $i!=0 && $i!=$lpcount-1)
{
$output_string .= ",";
}
$output_string .= $spl[$i];
}
}
return $output_string . $fraction;
}

// http://efreedom.com/Question/1-3181945/Convert-Money-Text-PHP
function translate_to_words($number)
{
/*****
* A recursive function to turn digits into words
* Numbers must be integers from -999,999,999,999 to 999,999,999,999 inclussive.
*
* (C) 2010 Peter Ajtai
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* See the GNU General Public License: .
*
*/
// zero is a special case, it cause problems even with typecasting if we don’t deal with it here
$max_size = pow(10,18);
if (!$number) return “zero”;
if (is_int($number) && $number < abs($max_size))
{
$prefix = '';
$suffix = '';
switch ($number)
{
// set up some rules for converting digits to words
case $number < 0:
$prefix = "negative";
$suffix = $this->translate_to_words(-1*$number);
$string = $prefix . ” ” . $suffix;
break;
case 1:
$string = “one”;
break;
case 2:
$string = “two”;
break;
case 3:
$string = “three”;
break;
case 4:
$string = “four”;
break;
case 5:
$string = “five”;
break;
case 6:
$string = “six”;
break;
case 7:
$string = “seven”;
break;
case 8:
$string = “eight”;
break;
case 9:
$string = “nine”;
break;
case 10:
$string = “ten”;
break;
case 11:
$string = “eleven”;
break;
case 12:
$string = “twelve”;
break;
case 13:
$string = “thirteen”;
break;
// fourteen handled later
case 15:
$string = “fifteen”;
break;
case $number < 20:
$string = $this->translate_to_words($number%10);
// eighteen only has one “t”
if ($number == 18)
{
$suffix = “een”;
} else
{
$suffix = “teen”;
}
$string .= $suffix;
break;
case 20:
$string = “twenty”;
break;
case 30:
$string = “thirty”;
break;
case 40:
$string = “forty”;
break;
case 50:
$string = “fifty”;
break;
case 60:
$string = “sixty”;
break;
case 70:
$string = “seventy”;
break;
case 80:
$string = “eighty”;
break;
case 90:
$string = “ninety”;
break;
case $number < 100:
$prefix = $this->translate_to_words($number-$number%10);
$suffix = $this->translate_to_words($number%10);
//$string = $prefix . “-” . $suffix;
$string = $prefix . ” ” . $suffix;
break;
// handles all number 100 to 999
case $number < pow(10,3):
// floor return a float not an integer
$prefix = $this->translate_to_words(intval(floor($number/pow(10,2)))) . ” hundred”;
if ($number%pow(10,2)) $suffix = ” and ” . $this->translate_to_words($number%pow(10,2));
$string = $prefix . $suffix;
break;
case $number < pow(10,6):
// floor return a float not an integer
$prefix = $this->translate_to_words(intval(floor($number/pow(10,3)))) . ” thousand”;
if ($number%pow(10,3)) $suffix = $this->translate_to_words($number%pow(10,3));
$string = $prefix . ” ” . $suffix;
break;
}
} else
{
echo “ERROR with – $number
Number must be an integer between -” . number_format($max_size, 0, “.”, “,”) . ” and ” . number_format($max_size, 0, “.”, “,”) . ” exclussive.”;
}
return $string;
}

function get_bd_amount_in_text($amount)
{
$output_string = ”;

$tokens = explode(‘.’, $amount);
$current_amount = $tokens[0];
$fraction = ”;
if(count($tokens) > 1)
{
$fraction = (double)(’0.’ . $tokens[1]);
$fraction = $fraction * 100;
$fraction = round($fraction, 0);
$fraction = (int)$fraction;
$fraction = $this->translate_to_words($fraction) . ‘ paisa’;
$fraction = ‘ Taka & ‘ . $fraction;
}

$crore = 0;
if($current_amount >= pow(10,7))
{
$crore = (int)floor($current_amount / pow(10,7));
$output_string .= $this->translate_to_words($crore) . ‘ crore ‘;
$current_amount = $current_amount – $crore * pow(10,7);
}

$lakh = 0;
if($current_amount >= pow(10,5))
{
$lakh = (int)floor($current_amount / pow(10,5));
$output_string .= $this->translate_to_words($lakh) . ‘ lakh ‘;
$current_amount = $current_amount – $lakh * pow(10,5);
}

$current_amount = (int)$current_amount;
$output_string .= $this->translate_to_words($current_amount);

$output_string = $output_string . $fraction . ‘ only’;
$output_string = ucwords($output_string);
return $output_string;
}

}

$currency_object = new Currency();

for($i=1; $i<10; $i++)
{
$seed = time() / ($i + 1);
srand($seed);
$amount = mt_rand(100, 9999999);
$amount = $amount + $i/10;
echo $currency_object->get_bd_money_format($amount) . ‘ : ‘ . $currency_object->get_bd_amount_in_text($amount) . ‘
‘;

}

?>

{/code}

Sample Output:

================================================

84,20,202.10 : Eighty Four Lakh Twenty Thousand Two Hundred And Two Taka & Ten Paisa Only
10,90,495.20 : Ten Lakh Ninety Thousand Four Hundred And Ninety Five Taka & Twenty Paisa Only
12,51,706.30 : Twelve Lakh Fifty One Thousand Seven Hundred And Six Taka & Thirty Paisa Only
78,31,550.40 : Seventy Eight Lakh Thirty One Thousand Five Hundred And Fifty Taka & Forty Paisa Only
49,59,035.50 : Forty Nine Lakh Fifty Nine Thousand Thirty Five Taka & Fifty Paisa Only
29,83,538.60 : Twenty Nine Lakh Eighty Three Thousand Five Hundred And Thirty Eight Taka & Sixty Paisa Only
50,70,303.70 : Fifty Lakh Seventy Thousand Three Hundred And Three Taka & Seventy Paisa Only
11,98,440.80 : Eleven Lakh Ninety Eight Thousand Four Hundred And Forty Taka & Eighty Paisa Only
70,08,871.90 : Seventy Lakh Eight Thousand Eight Hundred And Seventy One Taka & Ninety Paisa Only

================================================

That’s it!

Please feel free to use this code anytime anywhere.

If you update/enhance this code, please share with other people.

Thanks for reading.

posted under PHP | 16 Comments »

JavaScript: Div & Element hide & show cross-browser script solution

January17

Hello Guys,

Today I was working in a project where I had to add element hide and show depending on the condition. For example, if the client wants to contact by phone, the phone DIV element or area appears. If not, the phone DIV element hide quickly. I was writing scripts for this. But to my surprise, I noticed that none of them are cross-browser supporting. When one scripting working in few browsers, the same script is not working in other browsers. So, I struggled to come up with the cross-browser solution and at last, I succeeded. You can use this code in your form whenever you need to show and hide elements dynamically in JavaScript. This script is a kind of Contact Us form.

So, what am I gonna do? I am going to share my small script so that you can save your time I you find my this article by Google search or any other search.

OK!
No more introduction. Let us start.

Download:

I suggest you first download the script and take a look.
http://www.tanzilo.com/demo/code/hide_show/hide_show.zip

Features:

  1. It is a totally CSS-based and table-less scripting
  2. I have used phpMailer version 2.3 and it works for PHP 5 and/or 6 version
  3. JavaScript used as you already know

CSS Code:

{code type=CSS}

{/code}

HTML Code:

{code type=HTML}

Name:
Email:
Best method to contact you:
Phone No:
Will this server host a vBulletin site?

Forum Link:
Current size of database:
Average concurrent users:
Do you currently have a dedicated server?

Current Provider:
Current Server Specs:

Are there any specs you must have with your new server
or additional notes you would like us to consider?

Time frame to purchase
Do you have a budget we need to consider?
Anti Spam Question: How much is: 5+5+3=?

 

{/code}

JavaScript Code:

{code type=JavaScript}

function displayContactMethod()
{
var id = ‘phone’;
var contatMethod = document.contact_form.contact_method.value;

if(contatMethod == “Phone”)
{
displayDiv(‘phoneNoDiv’)
}
else
{
hideDiv(‘phoneNoDiv’);
document.contact_form.phone.value = ”;
}
}

function initialHiddenDivs()
{
var divID_1 = ‘phoneNoDiv’;
var divID_2 = ‘formRowForum’;
var divID_3 = ‘formRowDatabase’;
var divID_4 = ‘formRowUsers’;
var divID_5 = ‘formRowProvider’;
var divID_6 = ‘formRowCurrentSpecs’;

hideDiv(divID_1);
hideDiv(divID_2);
hideDiv(divID_3);
hideDiv(divID_4);
hideDiv(divID_5);
hideDiv(divID_6);
}
function hideDiv(id)
{
if (document.getElementById) { // DOM3 = IE5, NS6
document.getElementById(id).style.display = ‘none’;
}
else {
if (document.layers) { // Netscape 4
document.id.display = ‘none’;
}
else { // IE 4
document.all.id.style.display = ‘none’;
}
}
}

function displayDiv(id)
{
if (document.getElementById) { // DOM3 = IE5, NS6
document.getElementById(id).style.display = ‘block’;
}
else {
if (document.layers) { // Netscape 4
document.id.display = ‘block’;
}
else { // IE 4
document.all.id.style.display = ‘block’;
}
}
}

function controlServerHostOptions()
{
var host_vb = document.contact_form.host_vb.value;

if(host_vb == “Yes”)
{
displayDiv(‘formRowForum’);
displayDiv(‘formRowDatabase’);
displayDiv(‘formRowUsers’);
}
else
{
hideDiv(‘formRowForum’);
hideDiv(‘formRowDatabase’);
hideDiv(‘formRowUsers’);
document.contact_form.forum_link.value = ”;
document.contact_form.size.value = ”;
document.contact_form.users.value = ”;
}
}

function controlCurrentHostOptions()
{
var server = document.contact_form.server.value;

if(server == “Yes”)
{
displayDiv(‘formRowProvider’);
displayDiv(‘formRowCurrentSpecs’);
}
else
{
hideDiv(‘formRowProvider’);
hideDiv(‘formRowCurrentSpecs’);
document.contact_form.current_provider.value = ”;
document.contact_form.current_specs.value = ”;
}
}

{/code}

PHP Code:

{code type=PHP}

if($_POST)
{

$name = trim($_POST['name']);
$email = trim($_POST['email']);
$contact_method = trim($_POST['contact_method']);
$phone = trim($_POST['phone']);
$host_vb = trim($_POST['host_vb']);
$forum_link = trim($_POST['forum_link']);
$size = trim($_POST['size']);
$users = trim($_POST['users']);
$server = trim($_POST['server']);
$current_provider = trim($_POST['current_provider']);
$current_specs = trim($_POST['current_specs']);
$specs = trim($_POST['specs']);
$time = trim($_POST['time']);
$budget = trim($_POST['budget']);
$total = trim($_POST['total']);

$_SESSION['name'] = $name;
$_SESSION['email'] = $email;
$_SESSION['contact_method'] = $contact_method;
$_SESSION['phone'] = $phone;
$_SESSION['host_vb'] = $host_vb;
$_SESSION['forum_link'] = $forum_link;
$_SESSION['size'] = $size;
$_SESSION['users'] = $users;
$_SESSION['server'] = $server;
$_SESSION['current_provider'] = $current_provider;
$_SESSION['current_specs'] = $current_specs;
$_SESSION['specs'] = $specs;
$_SESSION['time'] = $time;
$_SESSION['budget'] = $budget;

if($total != 13)
{
echo '

Anti Spam Question is wrong!
Please sum up and type the current result of: 5+5+3=?

‘;
}
else
{

$emailBody = ”;
if(!empty($name))
{
$emailBody .= ‘Name : ‘ . $name . chr(10);
}
if(!empty($email))
{
$emailBody .= ‘Email : ‘ . $email . chr(10);
}
if(!empty($contact_method))
{
$emailBody .= ‘Best method to contact you : ‘ . $contact_method . chr(10);
}
if(!empty($phone))
{
$emailBody .= ‘Phone : ‘ . $phone . chr(10);
}
if(!empty($host_vb))
{
$emailBody .= ‘Will this server host a vBulletin site? : ‘ . $host_vb . chr(10);
}
if(!empty($forum_link))
{
$emailBody .= ‘Forum Link : ‘ . $forum_link . chr(10);
}
if(!empty($size))
{
$emailBody .= ‘Current size of database : ‘ . $size . chr(10);
}
if(!empty($users))
{
$emailBody .= ‘Average concurrent users : ‘ . $users . chr(10);
}
if(!empty($server))
{
$emailBody .= ‘Do you currently have a dedicated server? : ‘ . $server . chr(10);
}
if(!empty($current_provider))
{
$emailBody .= ‘Current Provider : ‘ . $current_provider . chr(10);
}
if(!empty($current_specs))
{
$emailBody .= ‘Current Server Specs : ‘ . $current_specs . chr(10);
}
if(!empty($specs))
{
$emailBody .= ‘Are there any specs you must have with your
new server or additional notes you would
like us to consider? : ‘ . $specs . chr(10);
}
if(!empty($time))
{
$emailBody .= ‘Time frame to purchase : ‘ . $time . chr(10);
}
if(!empty($budget))
{
$emailBody .= ‘Do you have a budget we need to consider? : ‘ . $budget . chr(10);
}

include_once(‘php5Mailer/class.phpmailer.php’);

$mail = new PHPMailer();

$body = $emailBody;
$body = eregi_replace(“[\]“,”,$body);
$subject = eregi_replace(“[\]“,”,$subject);

$mail->From = $email;
$mail->FromName = $name;

$mail->Subject = “New Email from $name ($email)”;

// optional, comment out and test
$mail->AltBody = “To view the message, please use an HTML compatible email viewer!”;

$mail->Body = nl2br($body);

$mail->AddAddress(“todd@urljet.com”, “Todd”);
$mail->IsHTML(true);

if(!$mail->Send())
{
echo ‘

Failed to send mail

‘;
}
else
{
echo ‘

Mail sent

‘;
$_SESSION['name'] = ”;
$_SESSION['email'] = ”;
$_SESSION['contact_method'] = ”;
$_SESSION['phone'] = ”;
$_SESSION['host_vb'] = ”;
$_SESSION['forum_link'] = ”;
$_SESSION['size'] = ”;
$_SESSION['users'] = ”;
$_SESSION['server'] = ”;
$_SESSION['current_provider'] = ”;
$_SESSION['current_specs'] = ”;
$_SESSION['specs'] = ”;
$_SESSION['time'] = ”;
$_SESSION['budget'] = ”;
}

}

}

?>
{/code}

Once again I would like to remind you that you first download this small script from the above download link and take a look at the whole script.

That is all for now, Dude!

Thank you for reading.

posted under JavaScript, PHP | 5 Comments »

WordPress: adding a custom option box and developing file upload plugin

January15

Hello Buddy,

One of my clients wanted to show thumbnail photo beside the post text as below. So, I had to make a plugin so that the admin can post the thumbnail when he is writing the post or can edit when editing the post. Take a look at the thumbnail’s position below.

Thus, recently I solved a plugin problem in one of my wordpress works although it was small. You know you may sometimes need to add a custom field in your wordpress posting/writing/editing area. To check what I am saying, take a look at the following image:

Adding such a box is extremely easy using the wordpress’s builtin add_meta function. But does file upload works i.e. if you upload the file, will it work? The answer is straight – “NO”. But why? The reason is also simple. If you want to upload a file, your form should have “enctype=”multipart/form-data” in the form opening such as

{code type=HTML}

{/code}

But the problem is – if you open the source code of text editor tool as following,

you will see that it does not have “enctype=”multipart/form-data” unfortunately. It looks exactly like this in my wordpress 2.7 version if I open the wp-admin/edit-form-advanced.php file at line # 520.

{code type=HTML}

{/code}

Not funny? Huh?

So, to cope up with this situation, I had to add “enctype=”multipart/form-data” in the form although I do not like changing the core files. Why do not I like to change the core files? The answer simple. Because whenever there is an update, the client have to update the file everytime. The client may not like it or may even forget it. Anyway, after change, it looks like this:

{code type=HTML}

{/code}

OK. Lemme show you step by step what to do if you want to add a file upload plugin.

Step One: Change the “wp-admin/edit-form-advanced.php” file

Open this file from the mentioned location and change the following line in the file:

{code type=HTML}

{/code}

to this line:

{code type=HTML}

{/code}

Step Two: Write you plugin

Here goes mine:

{code type=PHP}

/*
Plugin Name: Bag Thumbnail
Plugin URI: http://www.tanzilo.com/
Description: This plugin helps you to set thumbnail image of your bags.
Author: Tanzil Al Gazmir
Version: 1.0
Author URI: http://www.tanzilo.com/
*/

function init_bag_review_thumb_widget()
{

global $wpdb;

$result = mysql_list_tables(DB_NAME);
$current_table = array();
while($row = mysql_fetch_row($result))
{
$current_tables[] = $row[0];
}
$myNewDatabaseTable = $wpdb->prefix . ‘bag_thumb’;
if(!in_array($myNewDatabaseTable, $current_tables))
{

mysql_query(”
CREATE TABLE IF NOT EXISTS `” . $myNewDatabaseTable . “` (
`id` int(11) NOT NULL auto_increment,
`post_id` int(11) NOT NULL,
`image_name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
);
“);
}

/*
// Now I am going to delete all unnecessary thumb images by scanning the
// whole directory
*/
$sqlQuery = “SELECT image_name FROM ” .$wpdb->prefix . “bag_thumb; “;
$fileArray = $wpdb->get_col($sqlQuery);
$fileArray[] = ‘no_thumb.jpg’;

if ($handle = opendir(‘../bag_thumb/’))
{

// This is the correct way to loop over the directory.
while (false !== ($file = readdir($handle)))
{
if(is_file(‘../bag_thumb/’ . $file))
{
if(!in_array($file, $fileArray))
{
unlink(‘../bag_thumb/’ . $file);
}
}
}

closedir($handle);
}

}

// This function tells WP to add a new “meta box”
function add_bag_photo_box()
{

add_meta_box(

‘bag_photo’, // id of the

we’ll add
‘Add Bag Thumbnail Photo’, //title
‘add_bag_photo’, // callback function that will echo the box content
‘post’, // where to add the box: on “post”, “page”, or “link” page
‘normal’,
‘high’

);
}

// This function echoes the content of our meta box
function add_bag_photo()
{
echo


‘;
}

function bag_thumbnail_plugin_save_postdata()
{
$fileArray = array();
global $wpdb;

$file = $_FILES['bag_thumbnail_photo'];
$fileName = $_FILES['bag_thumbnail_photo']['name'];
$basename = ”;

if(!empty($fileName))
{
if(isAllowedExtension($_FILES['bag_thumbnail_photo']['name']))
{

$postID = $_POST['post_ID'];

# Do uploading here
$basename = basename( $_FILES['bag_thumbnail_photo']['name']);
$basename = str_replace(‘ ‘, ‘_’, $basename);
$basename = str_replace(‘-’, ‘_’, $basename);
$basename = strtolower($basename);
$basename = $_POST['post_ID'] . ‘_’ . $basename;
$target_path = ‘../bag_thumb/’;
$target_path = $target_path . $basename;

$sqlQuery = “DELETE FROM ” . $wpdb->prefix . “bag_thumb WHERE post_id=$postID;”;
$wpdb->query($sqlQuery);

move_uploaded_file($_FILES['bag_thumbnail_photo']['tmp_name'], $target_path);

// adding record in the database
$sqlQuery = “INSERT INTO ” .
$wpdb->prefix . “bag_thumb(post_id, image_name)
VALUES($postID, ‘$basename’)”;
$wpdb->query($sqlQuery);
}

}

}

function isAllowedExtension($fileName)
{
$allowedExtensions = array(“png”, “gif”, “jpg”, ‘jpeg’);
return in_array(end(explode(“.”, $fileName)), $allowedExtensions);
}

// This starts whenever the plugin is loaded
add_action(“plugins_loaded”, “init_bag_review_thumb_widget”);

// Hook things in, late enough so that add_meta_box() is defined
if (is_admin())
{
/* Use the admin_menu action to define the custom boxes */
add_action(‘admin_menu’, ‘add_bag_photo_box’);
}

/* Use the save_post action to do something with the data entered */
add_action(‘save_post’, ‘bag_thumbnail_plugin_save_postdata’);

?>
{/code}

Please notice that I dynamically delete any unnecessary file using the PHP’s unlink() function.

Step Three: get your image name from the database

I have placed the following code in my functions.php file.

{code type=PHP}

if(!function_exists('getBagThumbName'))
{
function getBagThumbName($postID)
{
global $wpdb;
$sqlQuery = 'SELECT image_name FROM ' . $wpdb->prefix . ‘bag_thumb WHERE post_id=’ . $postID . ‘;’;
$fileName = $wpdb->get_var($sqlQuery);
$fileName = trim($fileName);
$fileURL = get_option(‘siteurl’) . ‘/bag_thumb/’ . $fileName;
if(!empty($fileName))
{
return $fileURL;
}
else
{
return (get_option(‘siteurl’) . ‘/bag_thumb/no_thumb.jpg’);
}
}
}

?>
{/code}

Step Four: Link with the index.php or single.php or wherever you want

See how I placed the thumbnail image source in the code of index.php and single.php file.

{code type=PHP}

posted under PHP, Wordpress | 31 Comments »

WordPress: display posts by category ID. Solution with code & example.

January6

Hello Guy!

Often in many blogging sites, you will see two or three columns of the most important categories. Recently I had to do this for a blog. It was a little bit cumbersome and time consuming. So, I would like to share the solution so that you can kill the time waste trying yourself in case you do not know how to do it. In this solution, I show 5 posts at maximum from my chosen three categories.

OK.
Let us start and let me show how to do it.

Step One: See the sample what would be the output

In the above image, you will notice that the first category has enough posts, so it can fetch 5 (five) posts for us. But in second column and third column, there are only three posts because those categories do not have more than three posts. And what I want to say at this point is – although we will try to get 5 posts from each category, we will not get enough in case that category has less than 5 (five) posts and this is done automatically.

Step Two: Adding custom function

{code type=PHP}

if(!function_exists('postListByCategory'))
{
function categoryNameByCategoryID($categoryID = 0)
{
global $wpdb;
$sqlQuery = 'SELECT name FROM ' . $wpdb->prefix . “terms WHERE term_id=$categoryID”;
return $wpdb->get_var($sqlQuery);
}
}

if(!function_exists(‘postListByCategory’))
{
function postListByCategoryID($categoryID = 0)
{
$outputString = ”;
query_posts(‘orderby=name&order=asc&cat=’ . $categoryID . ‘&showposts=5′);
$outputString .= ‘

    ‘ . chr(10);
    while (have_posts()) : the_post();
    $permaLink = get_permalink();
    $permaLink = trim($permaLink);
    if(!empty($permaLink))
    {
    $outputString .= ‘
  • ‘ . chr(10);
    $outputString .= ‘‘ . get_the_title($post->ID) . ‘
    ‘ . chr(10);
    $outputString .= ‘‘ . get_the_time(‘D M jS Y’) .’‘ . chr(10);
    $outputString .= ‘
  • ‘ . chr(10);
    }
    endwhile;
    $outputString .= ‘

‘ . chr(10);
return $outputString;
}
}

?>
{/code}

Now open the functions.php file inside your theme directory and insert these two functions. If there is none, create a functions.php file. And at this point, please remember that all the functions and coding in this file are automatically added during the code execution.

Note that the function names are self descriptive.

Step Three: Embed code in your file(s)

Now open your footer.php file or any other file and add this code. In 99% cases, you may need to customize this small piece of code. The first three lines are category IDs.

{code type=PHP}

$firstColumnCategoryID = 1;
$secondColumnCategoryID = 30;
$thirdColumnCategoryID = 31;

?>

 

 

 

{/code}

Step Four: Link your CSS code

{code type=CSS}
#bottomThreeColumns
{
width:940px; min-height:100px; margin:0 auto; clear:both;
}
#bottomThreeColumns UL
{
margin:0px 0px 30px 0px; padding:0px;
}
#bottomThreeColumns LI
{
list-style:none; border-bottom:#EEEEEE solid 1px; margin:7px 0px 0px 4px;
}
#bottomThreeColumns LI A
{
text-decoration:none; color:#000000;
}
#bottomThreeColumns LI A:hover
{
text-decoration:underline;
}
#bottomThreeColumns SMALL
{
font-style:italic; line-height:25px; padding:0px 0px 0px 4px;
}
#bottomColumn
{
float:left; width:300px; margin:20px 20px 0px 0px;
}
#bottomColumnThird
{
float:left; width:300px; margin:20px 0px 0px 0px;
}
#bottomColumnTop
{
width:300px; height:26px; background:#5FB8EB; color:#FFFFFF;
line-height:25px; font-weight:bold;
}
{/code}

I have put the above CSS code in my style.css file. In 99% cases, you may need to customize according to your requirements.

Step Five: Test everything by opening the link

Now test you code and we are done!

Thank you for reading.

posted under PHP, Wordpress | 12 Comments »

PHP: Serialization & Unserialization explanation, code & example

December31

Hello Folks!

When I was new to PHP 5 Object Oriented Programming (OOP), the serialization and un-serialization issues were not clear to me and I used to get confused with them often. Nowadays I can play with them easily and I will try to share my knowledge with you so that you can kill your confusion on these topics.

OK. Let us start!

What is Serialization?

This process makes a storable representation of a value that is useful for storing or passing PHP values around without losing their type and structure.

Remember the “__sleep” function in case of Serialization

Before starting your serialization process, PHP will execute the __sleep function automatically. This is a magic function or method.

What is Unserialization?

This process takes a single serialized variable and converts it back into a PHP value.

Remember the “__wakeup” function in case of Unserialization

Before starting your unserialization process, PHP will execute the __wakeup function automatically. This is a magic function or method.

What can you Serialize and Unserialize?

Many things as such

  1. Variables (Integer, Float, Real, String etc.)
  2. Arrays
  3. Objects etc.

What cannot you Serialize and Unserialize?

Only one type

  1. Resource-type

A simple example of Serialization and Unserialization

{code type=PHP}

require_once "class.serialize.php";
$myObject = new SerializationTest();
$myObject->counter = 999;
$myObject->myName = ‘Random Visitor’;
$myObject->myAge = 59;

$myString = ‘I am a simple line.’;
$myArray = array();
$myArray[0] = ‘One’;
$myArray[1] = ‘Two’;
$myArray[2] = ‘Three’;

echo $myString . ‘
‘;
var_dump($myArray);
echo ‘
‘;
echo ‘$myObject->counter: ‘ . $myObject->counter . ‘
‘;
echo ‘$myObject->myName: ‘ . $myObject->myName . ‘
‘;
echo ‘$myObject->myAge: ‘ . $myObject->myAge . ‘
‘;
var_dump($myObject);

$mySerializedString = serialize($myString);
$mySerializedArray = serialize($myArray);
$mySerializedObject = serialize($myObject);

$myString = ‘I have changed!’;
$myArray[0] = ‘New 1′;
$myArray[1] = ‘New 2′;
$myArray[2] = ‘New 3′;

echo ‘

‘;
echo $myString . ‘
‘;
var_dump($myArray);
echo ‘
‘;

$myUnserializedString = unserialize($mySerializedString);
$myUnserializedArray = unserialize($mySerializedArray);
$myUnserializedObject = unserialize($mySerializedObject);

echo ‘

‘;
echo $myUnserializedString . ‘
‘;
var_dump($myUnserializedArray);
echo ‘
‘;
echo ‘$myUnserializedObject->counter: ‘ . $myUnserializedObject->counter . ‘
‘;
echo ‘$myUnserializedObject->myName: ‘ . $myUnserializedObject->myName . ‘
‘;
echo ‘$myUnserializedObject->myAge: ‘ . $myUnserializedObject->myAge . ‘
‘;
var_dump($myUnserializedObject);

?>
{/code}

And here is the related class:

{code type=PHP}

class SerializationTest
{
public $counter;
public $myName;
public $myAge;
function __construct()
{
$this->counter = 100;
$this->myName = ‘Tanzilo Insido’;
$this->myAge = 28;
}

function __sleep()
{
echo “

__sleep()

“;
$this->counter = $this->counter + 1;
echo ‘Serialization Process Started!’ . ‘
‘;
echo ‘$this->counter: ‘ . $this->counter . ‘
‘;
return array(myString);
}

function __wakeup()
{
echo “

__wakeup()

“;
$this->counter = $this->counter – 1;
echo ‘UnSerialization Process Started!’ . ‘
‘;
echo ‘$this->counter: ‘ . $this->counter . ‘
‘;
}

}

?>
{/code}

Explanation of the example

If you notice the A to Z of the above code, you will find that we have a $myString variable, $myArray array and $myObject object. First of all, we have set values to them and then printed them all. They all perform as expected. Then we change all the values. Next when we serialize and unserialize the values, our original dara structure returns! And that is what we wanted.

Here is the result of the above code:

An interesting thing to note:
I would like to draw your attention to the fact that using __sleep() method, you can change the values of your declared and initialized variables. But you cannot change them by using __wakeup() function. For example, see the following code:

Now we serialize 3 (three)  times and unserialize 2 (two) times.

{code type=PHP}

require_once "class.serialize.php";
$myObject = new SerializationTest();

echo '

Start Value:

‘;
echo ‘$this->counter: ‘ . $myObject->counter . ‘
‘;
echo ‘$this->myString: ‘ . $myObject->myString;

$serializeData_1 = serialize($myObject);
$serializeData_2 = serialize($myObject);
$serializeData_3 = serialize($myObject);

$unSerializeData_1 = unserialize($serializeData_1);
$unSerializeData_2 = unserialize($serializeData_2);

?>
{/code}

And here is the result if we serialize 3 (three)  times and unserialize 2 (two) times.

Although we initialized $this->counter variable in the __construct() function, it is not used or has no effect in __wakeup() function. But it works properly in __sleep() or serialize() process. But what is the reason? The explanation is simple. The __wakeup() is part of the process when your data is retrieved from memory. Another thing is – did you notice the array return in the __sleep() function? Without returning this, the process often does not work. So, please remember to keep in your code.

You can download these small pieces of code files from here:
http://www.tanzilo.com/demo/code/serialize/serialize.zip

Thank you for reading.

posted under PHP | 11 Comments »

PHP & MySQL: Creating a website in your local language smoothly

December29

Hello Developer,

You know English is the international language and accepted as international communication. So, most of the websites have been developed in English. But in many other times, a developer needs to work with local languages where they are developing a website in PHP. If you develop in local language, you need to know a small trick and that will show your content properly in all browsers smoothly.

So, what is the technique?

Well. Let me explain step by step.

Step One: An observation
I will show you the source code of two Bengali newspaper. In this newspaper: http://www.prothom-alo.com, the fonts and text comes properly in all browsers. But in this newspaper: http://www.ittefaq.com, it can show text and fonts properly only in Internet Explorer.

Now the matter is we must make sure our content will be displayed properly in any browser. Right?

OK. So what is the difference between the two websites I just gave example?

If you take a look at the source code of the first website’s content, you will find it is like this:&#2488;&#2691;&#2474;&#2494;&#2470;&#2453;

This is another website that had been developed as smooth site in the same technique: http://www.bdnews24.com/bangla. If you check its code, you will see that it uses same type of code for its text.

So, what are these &#2474;&#2494;&#2470;&#2453;&#2496;&#2527; things? It is very interesting that these are universal representation of local language in HTML entities. For every character of any local language, there is a unique and fixed symbol defined such as &#2474; in HTML entities. When you bring this kind of text in your browser source code, the site content looks smooth without any break and fonts displays properly.

Now if you open the source code of http://www.ittefaq.com, you will see something like AvR beg RvZxq msm` wbe©vP‡b jovB n‡e †RvU-gnv‡Rv‡Ui g‡a¨. The matter is they are also showing Bengali news content, but in a different way that is not useful in cross-broswer platform. This is often totally recognized by only Internet Explorer and often partially recognized by other browsers.

Step Two: Storing your local language content in the database
You see I have some content in my local language (Bangla) in the database.

Step Three: Converting your local language text in Universal code
Well. This is extremely easy.

{code type=PHP}

class UnicodeHandler
{
var $dbLink;
var $sqlQuery;
var $dbResult;
var $dbRow;
var $salary;
var $bonus;

/* Use this constructor in case your PHP version is 4. */
/*
function UnicodeHandler()
{
$this->dbLink = ”;
$this->sqlQuery = ”;
$this->dbResult = ”;
$this->dbRow = ”;
$this->mySalary = 0;
$this->myBonus = 0;

$this->dbLink = mysql_connect(‘localhost’, ‘root’, ”);
mysql_query(“SET character_set_results=utf8″, $this->dbLink);
mb_language(‘uni’);
mb_internal_encoding(‘UTF-8′);

mysql_select_db(‘test’, $this->dbLink);
mysql_query(“set names ‘utf8′”,$this->dbLink);
}
*/

/* Use this constructor in case your PHP version is 5 or 5+. */
/* I assume you are using PHP 5 or 5+. */
function __construct()
{
$this->dbLink = ”;
$this->sqlQuery = ”;
$this->dbResult = ”;
$this->dbRow = ”;
$this->mySalary = 0;
$this->myBonus = 0;

$this->dbLink = mysql_connect(‘localhost’, ‘root’, ”);
mysql_query(“SET character_set_results=utf8″, $this->dbLink);
mb_language(‘uni’);
mb_internal_encoding(‘UTF-8′);

mysql_select_db(‘test’, $this->dbLink);
mysql_query(“set names ‘utf8′”,$this->dbLink);
}

function displayLocalContent()
{
mysql_query(“SET character_set_results=utf8″, $this->dbLink);
$this->sqlQuery = “SELECT * FROM unitext “;
$this->dbResult = mysql_query($this->sqlQuery, $this->dbLink);
while($this->dbRow = mysql_fetch_object($this->dbResult))
{
echo ‘News: ‘ . $this->convertToLocalHtml($this->dbRow->news) . ‘
‘;
}

}

function convertToLocalHtml($localHtmlEquivalent)
{

$localHtmlEquivalent = mb_convert_encoding($localHtmlEquivalent,”HTML-ENTITIES”,”UTF-8″);
return $localHtmlEquivalent;
}
}

?>
{/code}

The displayLocalContent() function is going to display the news and convertToLocalHtml() function converts my utf-8 content to HTML entities.

And here in index.php I am executing my displayLocalContent() function.

{code type=PHP}




include_once 'class.unicode.php';
$unicodeObject = new UnicodeHandler();
$unicodeObject->displayLocalContent();

?>


{/code}

As a result, the output is now as ঢাকা, ডিসে etc.

Step Four: You need to check my other posting for SELECT, INSERT & UPDATE your local language.
Here goes my other article so that you can perform all required operations for storing and displaying information in browser smoothly:
http://www.tanzilo.com/2008/10/13/php-mysql-unicode-solution-to-chinese-russian-or-any-language/

An alternative way
I have an alternative way in my mind and that is when you store the data in the database, you can first convert them to universal code such as &#2453;&#2496;&#2527;and then directly show your text.

This article will cover any language such as Afrikaans, Albanian, Amharic, Arabic, Armenian, Assamese, Aymara, Azeri, Belarusian, Bengali, Bislama, Bosnian, Bulgarian, Burmese, Catalan, Chinese, Mandarin,Croatian, Czech, Danish, Dari, Dhivehi, Dutch, Dzongkha, English, Esperanto, Estonian, Fijian, Filipino, Finnish, French, Frisian,  Gagauz, Georgian, German, Greek, Guaraní, Gujarati, Haitian Creole, Hebrew, Hindi, Hiri Motu, Hungarian, Icelandic, Indonesian, Italian, Japanese, Kannada, Kashmiri, Kazakh, Khmer, Korean, Kurdish, Kyrgyz, Lao, Latvian, Lithuanian, Luxembourgish, Macedonian, Malagasy, Malay, Malayalam, Maltese, Māori, Marathi, Mayan, Moldovan, Mongolian, Montenegrin,Náhuatl, Ndebele, Nepali, New Zealand Sign Language, Northern Sotho, Norwegian, Oriya, Papiamento, Pashto, Persian, Polish, Portuguese, Punjabi, Quechua, Romanian, Rhaeto-Romansh, Russian, Sanskrit, Serbian, Shona, Sindhi, Sinhala, Slovak, Slovene, Somali, Sotho, Spanish, Swahili, Swati, Swedish, Tagalog, Tajik, Tamil, Telugu, Tetum, Thai, Tok Pisin, Tsonga, Tswana, Turkish, Turkmen, Ukrainian, Urdu, Uzbek, Venda, Vietnamese, Welsh, Xhosa, Yiddish, Zulu etc.

You can also download this small piece of code from here:
http://www.tanzilo.com/demo/code/convert_to_unicode/convert_to_unicode.zip

Thank you for reading.

PHP & MySQL: Unicode number add, subtract etc for any language

December23

Hello Coders!

Recently a visitor from my country asked me how he can add Unicode numbers stored in MySQL database.  I was thinking that it is really a good question. Because you may store any number in any local language to your database and later you may try to add or delete them.

For example, in Bangla language an employee’s salary can be ২৪১৮৬ (which is 24186 in English) bucks and the coder may want to store it in a table under salary field. Another field can be bonus and it can be ২০০ (2000 in English). Now the coder may want to add them up anytime required. You know adding 24186 and 2000 is easy. But what the coder may do in case the values are stored in a local language?

The visitor asked me how he can use the MySQL sum() function in case the data are stored in Unicode format. Well. I do not think MySQL’s unicode will support the sum() function or even if there is one I do not know frankly speaking. So, I thought and developed an alternative solution.

Here is the alternative solution steps:

  1. I get the unicode numbers from the database
  2. Convert them to English number
  3. Sum them up or anything like substract, multiply or divide etc
  4. Convert the result to Unicode once again

Thus, it looks simple procedure. Right?

Before we start I would like to suggest you download the codes from the bottom link of the page and take a look. Because some code may not look as the original one for browser’s case sensitiveness. So, it is better to look at the original code from the download link below.

So,  I wrote a small class to handle the whole procedure and here goes the coding of my class:

{code type=PHP}

class UnicodeHandler
{
var $dbLink;
var $sqlQuery;
var $dbResult;
var $dbRow;
var $salary;
var $bonus;

/* Use this constructor in case your PHP version is 4. */
/*
function UnicodeHandler()
{
$this->dbLink = ”;
$this->sqlQuery = ”;
$this->dbResult = ”;
$this->dbRow = ”;
$this->mySalary = 0;
$this->myBonus = 0;

$this->dbLink = mysql_connect(‘localhost’, ‘root’, ”);
mysql_query(“SET character_set_results=utf8″, $this->dbLink);
mb_language(‘uni’);
mb_internal_encoding(‘UTF-8′);

mysql_select_db(‘test’, $this->dbLink);
mysql_query(“set names ‘utf8′”,$this->dbLink);
}
*/

/* Use this constructor in case your PHP version is 5 or 5+. */
/* I assume you are using PHP 5 or 5+. */
function __construct()
{
$this->dbLink = ”;
$this->sqlQuery = ”;
$this->dbResult = ”;
$this->dbRow = ”;
$this->mySalary = 0;
$this->myBonus = 0;

$this->dbLink = mysql_connect(‘localhost’, ‘root’, ”);
mysql_query(“SET character_set_results=utf8″, $this->dbLink);
mb_language(‘uni’);
mb_internal_encoding(‘UTF-8′);

mysql_select_db(‘test’, $this->dbLink);
mysql_query(“set names ‘utf8′”,$this->dbLink);
}

function displayTotalPayment()
{
mysql_query(“SET character_set_results=utf8″, $this->dbLink);
$this->sqlQuery = “SELECT * FROM bangla_number “;
$this->dbResult = mysql_query($this->sqlQuery, $this->dbLink);
$this->total = 0;
while($this->dbRow = mysql_fetch_object($this->dbResult))
{
echo ‘Employee ID # ‘ . $this->dbRow->id . ‘
‘;
echo ‘Salary: ‘ . $this->dbRow->salary . ‘
‘;
echo ‘Bonus: ‘ . $this->dbRow->bonus . ‘
‘;
$totalPayment = $this->convertToEnglishNumber($this->dbRow->salary) +
$this->convertToEnglishNumber($this->dbRow->bonus);
echo ‘Total Payment: ‘ . $this->convertToBanglaNumber($totalPayment) . ‘
‘;
echo ‘

‘;
}

}

function convertToEnglishNumber($unicodeNumber)
{

$englishNumber = mb_convert_encoding($unicodeNumber,”HTML-ENTITIES”,”UTF-8″);
$englishNumber = str_replace(‘০’, ’0′, $englishNumber);
$englishNumber = str_replace(‘১’, ’1′, $englishNumber);
$englishNumber = str_replace(‘২’, ’2′, $englishNumber);
$englishNumber = str_replace(‘৩’, ’3′, $englishNumber);
$englishNumber = str_replace(‘৪’, ’4′, $englishNumber);
$englishNumber = str_replace(‘৫’, ’5′, $englishNumber);
$englishNumber = str_replace(‘৬’, ’6′, $englishNumber);
$englishNumber = str_replace(‘৭’, ’7′, $englishNumber);
$englishNumber = str_replace(‘৮’, ’8′, $englishNumber);
$englishNumber = str_replace(‘৯’, ’9′, $englishNumber);
return $englishNumber;
}

function convertToBanglaNumber($englishNumber)
{
$englishNumber = (string) $englishNumber;
$banglaNumber = ”;
$indexLimit = strlen($englishNumber);
for($i=0; $i<$indexLimit; $i++)
{
switch($englishNumber[$i])
{
case "0":
$banglaNumber .= '০';
break;
case "1":
$banglaNumber .= '১';
break;
case "2":
$banglaNumber .= '২';
break;
case "3":
$banglaNumber .= '৩';
break;
case "4":
$banglaNumber .= '৪';
break;
case "5":
$banglaNumber .= '৫';
break;
case "6":
$banglaNumber .= '৬';
break;
case "7":
$banglaNumber .= '৭';
break;
case "8":
$banglaNumber .= '৮';
break;
case "9":
$banglaNumber .= '৯';
break;
default:
$banglaNumber .= $englishNumber[$i];
break;
}
}
return $banglaNumber;
}

}

?>
{/code}

If you are not using Bengali language, you need to configure the equivalent number values in convertToEnglishNumber and convertToBanglaNumber functions.

And here goes the page where I am executing the displayTotalPayment() function.

{code type=PHP}




include_once 'class.unicode.php';
$salaryObject = new UnicodeHandler();
$salaryObject->displayTotalPayment();

?>


{/code}

Now the final result looks like this:

Oh! One important thing. If you are coding for European number format, you need to do some modification to handle the comma (,) factor in the number in case required.

Thus, if you use this small tricky method, you can add, subtract,  multiply or divide any local numbers such as Russian, Chinese, Arabic, Spanish, German, Polish, Turkey, Hindi etc.

You can also download this small piece of code from here:
http://www.tanzilo.com/demo/code/unicode_number_add/unicode_number_add.zip

Thank you for reading.

posted under PHP | 14 Comments »

WordPress: get page id and content with example & code

December19

Hey Guys!

Often I see people coming to my site searching with the terms wordpress get page id, wordpress get page content or something similar. I think wordpress developers face situations when they need to get page or post information in customized way. It happened to me too and I would like to share it with others since often people are coming to search this information.

Well. It is very easy and we can solve it quickly.
OK. Now let me show you how to get these information.

Remember one thing that is important for wordpress data fetching of this kind. Your posts and pages information is saved in a single database table and that is wp_posts. The wp_ is the prefix of you database and may differ. But most of the times the database table name is wp_posts and other times it is YourCustomPrefix_posts. We are going to fetch data from this table.

WordPress – print page id:

There is a built-in wordpress function using which you can print the post or page id. When you call this, this directly prints this inforation in your page without the need to use the built-in PHP echo or print function. Remember to keep it in the while loop.

{code type=PHP}


{/code}

WordPress – get page id:

There is a global variable post which contains the related information of the currest post or page. The name of the variable is: $post and it is actually an object. You can access information just as you access variables from an object. Remember to keep it in the while loop.

{code type=PHP}

global $post;
echo $post->ID;
?>


{/code}

You can print all the information in the $post object to see all the variables and their values that is contains.

{code type=PHP}

global $post;
var_dump($post);
?>


{/code}

WordPress – get page content:

Now you know you can get the page or post content from $post->post_content variable. But if you echo or print them, they may look somewhat without formatting. So, you need to use PHP built-in nl2br() function to look the content as it is.

{code type=PHP}

global $post;
echo nl2br($post->post_content);
?>


{/code}

WordPress – get any information of your page or post:

You know you can print all information to check all the available variables and their values through using PHP’s built-in var_dump() function. Suppose you need to get the post title, post type and posting time. We can get them easily in this way.

{code type=PHP}

global $post;
echo $post->post_title;
echo $post->post_type;
echo $post->post_date;
?>


{/code}

Please notice that post_title, post_type and post_date are all several database fields from wp_posts table of our wordpress database.

Very easy. Right? And that is all for getting the page or post information.

Thank you for reading.

posted under PHP, Wordpress | 45 Comments »

WordPress: Custom URL rewrite and reading URL values

December17

Hello!

Recently I was working for a Irish guy who has opened a wordpress blog few months ago. I did the theme for him. Recently he requested me for modifying and/or upgrading the project. One of the project requirements was URL rewriting. For example, there can a URL as follows:
http://www.sitename.com/index.php?group_name=My-Input-Value-Goes-Here

But after rewrite, the URL should look like:
http://www.sitename.com/My-Input-Value-Goes-Here

Well. You see I am passing the variable value in index.php file. But I needed to read the custom URL passed value through another PHP file and that is group.php. My group.php file was inside the theme folder. I am passing the group_name value in index.php file but reading from group.php file. It sounds a bit interesting. Huh?

OK. After browsing several blogs, I came up to writing a custom plugin. Thanks to Google.com and all those people sharing information.

My plugin made me a way so that I could pass a variable value in index.php file but read it from group.php file. This plugin code is available almost everywhere. Here goes my plugin:

{code type=PHP}

/*
Plugin Name: WP Custom URL
Plugin URI: http://www.tanzilo.com/#
Description: A plugin to allow parameters to be passed in the URL and recognized by WordPress
Author: Tanzilo
Version: 1.0
Author URI: http://www.tanzilo.com/
*/

function flush_rewrite_rules()
{
global $wp_rewrite;
$wp_rewrite->flush_rules();
}

function add_rewrite_rules( $wp_rewrite )
{
$new_rules = array(
‘(.+)’ => ‘index.php?group_name=’ .
$wp_rewrite->preg_index(1) );

$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

function add_query_vars( $qvars )
{
$qvars[] = ‘group_name’;
return $qvars;
}

function template_redirect_file()
{
global $wp_query;
if ( $wp_query->get(‘group_name’) )
{
if (file_exists( TEMPLATEPATH . ‘/group.php’ ))
{
include( TEMPLATEPATH . ‘/group.php’ );
exit;
}
}
}

add_action(‘init’, ‘flush_rewrite_rules’);
add_action(‘generate_rewrite_rules’, ‘add_rewrite_rules’);
add_filter(‘query_vars’, ‘add_query_vars’);
add_action(‘template_redirect’, ‘template_redirect_file’);

?>
{/code}

So, what happens now when I activate this plugin? It does a simple work and that is: when it gets a link as below:
http://www.sitename.com/index.php?group_name=My-Input-Value-Goes-Here

It sends the group_name variable value to group.php file which is in the theme folder. In group.php file, I can catch the variable value and use it anyway I want.

Do you want to see my group.php file too? OK. Here it goes:

{code type=PHP}

$group_name = $_GET['group_name'];
$group_name = str_replace('-', ' ', $group_name);

?>

If you enjoyed this post, make sure you
(dot)htaccess file for solving the rest of the part.

I was searching for a helpful blog link and after searching many blogs, I found a similar blog article and here it is:

http://www.webmasterworld.com/forum92/6079.htm

In this blog, I found a similar solution and wrote my own based on this code.

{code type=HTML}
# Enable mod_rewrite, start rewrite engine
Options +FollowSymLinks
RewriteEngine on
#
# Internally rewrite search engine friendly static URL to dynamic filepath and query
RewriteRule ^product/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ /index.php?product=$1&color=$2&size=$3&texture=$4&maker=$5 [L]
#
# Externally redirect client requests for old dynamic URLs to equivalent new static URLs
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\?product=([^&]+)&color=([^&]+)&size=([^&]+)&texture=([^&]+)&maker=([^\ ]+)\ HTTP/
RewriteRule ^index\.php$ http://example.com/product/%1/%2/%3/%4/%5? [R=301,L]
{/code}

Finally my (dot)htaccess file looked like this:

{code type=HTML}
# BEGIN WordPress

RewriteEngine On
RewriteBase /

RewriteRule ^pages/([^/]+)/?$ /index.php?group_name=$1 [L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\?group_name=([^&]+)\ HTTP/
RewriteRule ^index\.php$ http://mobile.ie/pages/%1? [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress
{/code}

But I was not 100% perfect but close to the solution. The reason is my URL started looking like this:
http://www.sitename.com/pages/My-Input-Value-Goes-Here

Well. You see I was almost close to the solution. As the buyer wanted like this:
http://www.sitename.com/My-Input-Value-Goes-Here

But I came up with a solution to:
http://www.sitename.com/pages/My-Input-Value-Goes-Here

I believe you can work on it and come to a solution without the extra “pages/” part in the URL. If you find such a solution, please share with me and others who will face similar problem.

Dude! That is all for now.

Thank you for reading.

posted under PHP, Wordpress | 11 Comments »

WordPress: Upload many PHP files quickly by Zip & Unzip

December15

Hello!

It is actually not only for a wordpress developer but also for all those developers who face situation where they must upload many files to the server. Recently in a wordpress project, I had to upload wordpress 2.7 version files in the server. In the wordpress 2.7 package, you will find around 600 files! Uploading them is not very interesting when your internet connection do not guarantee you smooth upload.

Uploading the 600 files brought me pain because they were going to the server very slowly and each time some files were corrupted and for any reason reuploading the corrupted files were not working. It was really time consuming, boring and painful. Then I started to look for an alternative solution. Then, I naturally came to the idea that how about I zip (compress) the folders containing most of the files and upload them. Thus I have to upload few zip files although bigger in size. Writing a piece of PHP code to unzip the zipped file is easy too.

So, I decided to zip the main three folders and uploaded them. You know they contain most of the files.

OK. Let me tell you the process in step by step way so that you can follow easily:

  1. First I zipped my three folders (wp-admin, wp-content & wp-includes) that contains most of the files.
  2. Changed the ‘public_html‘ folder permission to 777. Remember you will do it for the folder where you are going to upload.
  3. Uploaded the three zipped folders.
  4. Run my PHP script that you will see below.
  5. Checked if everything is OK and found them OK.
  6. Changed the file permission of the ‘public_html‘ folder back to 750. If you uploaded to any other folder, you need to change the permission 777 to any combination you think good for your purpose.
  7. Deleted the zip files since they are no longer required.

Here goes my PHP code to unzip them and it is very simple!

{code type=PHP}

$zipFileNames = array();
$zipFileNames[] = 'wp-admin.zip';
$zipFileNames[] = 'wp-content.zip';
$zipFileNames[] = 'wp-includes.zip';
// and all other zip files

$indexLimit = count($zipFileNames);
for($i=0; $i<$indexLimit; $i++)
{
$fileLink = $_SERVER['DOCUMENT_ROOT'] . '/' . $zipFileNames[$i];
if(is_file($fileLink))
{
if(exec("unzip $fileLink"))
{
echo 'Successful! ' . $fileLink . ' is properly unzipped!' . '
‘;
}
else
{
echo ‘Failed! exec() failed to execute as expected!’ . ‘
‘ .
‘Please check if the directory permission is 777 where you are trying upload.’;
}
}
else
{
echo ‘Error: ‘ . $fileLink . ‘ is not a (zip) file!’ . ‘
‘;
}
}

?>
{/code}

By the way, you can improve the code to more sophisticated one as per your requirement. For example, the exec() function has several options that you can use for more flexibility or anyway anything else you want.

Oh! There is one other way to unzip a uploaded zipped file although I did not use this piece of code. But remember that if you use this code you need to set your destination file permission to ’777′ first and then change as mentioned before after you unzipped. Fortunately this coding is very simple too and an example is as follows:

{code type=PHP}

$zip = new ZipArchive;

if($zip->open($_SERVER['DOCUMENT_ROOT'] . ‘/hello.zip’) === true)
{
$zip->extractto($_SERVER['DOCUMENT_ROOT'] . ‘/hellotest/’);
$zip->close();
echo ‘Files successfully unzipped!’;
}
else
{
die(‘Failed to open zip file’);
}

?>
{/code}

I tested both the processes mentioned above in Linux system and not sure how it works in Windows Server. I guess the second process should work in Windows server for uploading and unzipping bulk file quickly.

This is all for the trick of the game and for killing the pain of uploading several hundred of files.

Well. You can download my little sweet code here too:
http://www.tanzilo.com/demo/code/unzip/unzipping.zip

Thank you for reading.

posted under PHP, Wordpress | 2 Comments »
« Older Entries