Learning Is Fun

Talks on Web Technology and Better Product Development

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

<?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 . '<br />';
	var_dump($myArray);
	echo '<br />';
	echo '$myObject->counter: ' . $myObject->counter . '<br />';
	echo '$myObject->myName: ' . $myObject->myName . '<br />';
	echo '$myObject->myAge: ' . $myObject->myAge . '<br />';
	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 '<br /><br />';
	echo $myString . '<br />';
	var_dump($myArray);
	echo '<br />';
	$myUnserializedString = unserialize($mySerializedString);
	$myUnserializedArray = unserialize($mySerializedArray);
	$myUnserializedObject = unserialize($mySerializedObject);
	echo '<br /><br />';
	echo $myUnserializedString . '<br />';
	var_dump($myUnserializedArray);
	echo '<br />';
	echo '$myUnserializedObject->counter: ' . $myUnserializedObject->counter . '<br />';
	echo '$myUnserializedObject->myName: ' . $myUnserializedObject->myName . '<br />';
	echo '$myUnserializedObject->myAge: ' . $myUnserializedObject->myAge . '<br />';
	var_dump($myUnserializedObject);
?>

And here is the related class:

<?php
	class SerializationTest
	{
		public $counter;
		public $myName;
		public $myAge;
		function __construct()
		{
			$this->counter = 100;
			$this->myName  = 'Tanzilo Insido';
			$this->myAge   = 28;
		}
		function __sleep()
		{
			echo "<h3>__sleep()</h3>";
			$this->counter = $this->counter + 1;
			echo 'Serialization Process Started!' . '<br />';
			echo '$this->counter: ' . $this->counter .  '<br />';
			return array(myString);
		}
		function __wakeup()
		{
			echo "<h3>__wakeup()</h3>";
			$this->counter = $this->counter - 1;
			echo 'UnSerialization Process Started!' . '<br />';
			echo '$this->counter: ' . $this->counter .  '<br />';
		}
	}
?>

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.

<?php
	require_once "class.serialize.php";
	$myObject = new SerializationTest();
	echo '<h3>Start Value:</h3>';
	echo '$this->counter: ' . $myObject->counter . '<br />';
	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);
?>

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 | 4 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.

<?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) . '<br />';
			}
		}
		function convertToLocalHtml($localHtmlEquivalent)
		{
			$localHtmlEquivalent = mb_convert_encoding($localHtmlEquivalent,"HTML-ENTITIES","UTF-8");
			return $localHtmlEquivalent;
		}
	}
?>

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.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Displaying Your Local Language</title>
</head>
<body>
<?php
	include_once 'class.unicode.php';
	$unicodeObject = new UnicodeHandler();
	$unicodeObject->displayLocalContent();
?>
</body>
</html>

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:

<?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 . '<br />';
				echo 'Salary: ' . $this->dbRow->salary . '<br />';
				echo 'Bonus: ' . $this->dbRow->bonus . '<br />';
				$totalPayment = $this->convertToEnglishNumber($this->dbRow->salary) +
				$this->convertToEnglishNumber($this->dbRow->bonus);
				echo 'Total Payment: ' . $this->convertToBanglaNumber($totalPayment) . '<br />';
				echo '<br /><br />';
			}
		}
		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;
		}
	}
?>

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.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Unicode Number Adding</title>
</head>
<body>
<?php
	include_once 'class.unicode.php';
	$salaryObject = new UnicodeHandler();
	$salaryObject->displayTotalPayment();
?>
</body>
</html>

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 | 7 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.

<?php if (have_posts()) : ?>
	<?php while (have_posts()) : the_post(); ?>
		<?php the_ID(); ?>
	<?php endwhile; ?>
<?php endif; ?>

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.

<?php if (have_posts()) : ?>
	<?php while (have_posts()) : the_post(); ?>
        <?php
		global $post;
		echo $post->ID;
        ?>
	<?php endwhile; ?>
<?php endif; ?>

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

<?php if (have_posts()) : ?>
	<?php while (have_posts()) : the_post(); ?>
        <?php
		global $post;
		var_dump($post);
        ?>
	<?php endwhile; ?>
<?php endif; ?>

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.

<?php if (have_posts()) : ?>
	<?php while (have_posts()) : the_post(); ?>
        <?php
		global $post;
		echo nl2br($post->post_content);
        ?>
	<?php endwhile; ?>
<?php endif; ?>

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.

<?php if (have_posts()) : ?>
	<?php while (have_posts()) : the_post(); ?>
        <?php
		global $post;
		echo $post->post_title;
		echo $post->post_type;
		echo $post->post_date;
        ?>
	<?php endwhile; ?>
<?php endif; ?>

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 | 31 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:

<?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');
?>

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:

	<?php get_header(); ?>
	<?php
		$group_name = $_GET['group_name'];
		$group_name = str_replace('-', ' ', $group_name);
	?>
	<div id="container">
    	<div id="contentLeft">
        	<div id="pageContent">
            	<div id="postTitle"><?php echo $group_name; ?></div>
                <div id="postContent"><?php the_time('F j, Y') ?><br />
                    <ul id="pageGroupLinks">
                        <?php echo getGroupPageLinks($group_name); ?>
                    </ul>
				</div>
                <div id="rssSubscribe">If you enjoyed this post, make sure you
                <a href="<?php bloginfo('rss2_url'); ?>">subscribe to our RSS feed!</a>
                </div>
            </div>
        </div>
	<?php get_sidebar(); ?>
    </div>
	<?php get_footer(); ?>

This was half the way winning the battle.

But why? Because the following lines should solve my problem.

	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;
	}

But for any unknown reason it was not working.

So, I had to take help of apache (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.

# 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&amp;color=$2&amp;size=$3&amp;texture=$4&amp;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=([^&amp;]+)&amp;color=([^&amp;]+)&amp;size=([^&amp;]+)&amp;texture=([^&amp;]+)&amp;maker=([^\ ]+)\ HTTP/
RewriteRule ^index\.php$ http://example.com/product/%1/%2/%3/%4/%5? [R=301,L]

Finally my (dot)htaccess file looked like this:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^pages/([^/]+)/?$ /index.php?group_name=$1 [L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\?group_name=([^&amp;]+)\ HTTP/
RewriteRule ^index\.php$ http://mobile.ie/pages/%1? [R=301,L] 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

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 | 6 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!

<?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!' . '<br />';
			}
			else

			{
				echo 'Failed! exec() failed to execute as expected!' . '<br />' .
				'Please check if the directory permission is 777 where you are trying upload.';
			}
		}
		else

		{
			echo 'Error: ' . $fileLink . ' is not a (zip) file!' . '<br />';
		}
	}
?>

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:

<?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');
	} 
?>

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 | 1 Comment »

Flash swf and Lightbox overlapping problem solution

December13

Recently I was working in an American project where my client wanted to convert this static site to dynamic. Everything was fine except the gallery. The existing gallery was done using Lightbox effect and there was a flash audio file. The audio file was avoiding the Lightbox effect and coming overlapping any effect. And this is where the problem started.

OK. See below for an idea how it looked:

Not funny or interesting. Ugly, Huh? So, my client requested to fix it.

But what is the reason for this problem? Hm? Actually this was happening because Flash file is always above any other elements in your page. It comes at the topmost priority position in your page and that is why it can ignore the Lightbox effect. Our job is to make sure taht the Flash swf file stands behind the door when a Lighbox effect is in action. Clear?

In few blogs, I found possible solutions and they did not work. One possible solution that I thought would work was using z-index property in CSS. One coder advised to keep the embedding code in a lower z-index (such as 0) and keeping the container gallery in higher z-index (such as 1). Although he said, it worked for her, but did not work for me. But you can give a try if you want. May be this trick can work for you depending you code.

So, how did you fix it so that it looks like as follows?

So, what is the trick?  If you make sure that you added the following lines bold red in your HTML code, the problem is solved.

<?php
$client_testimonial = “/testimonials/audio_file.mp3″;
?>
<object type=”application/x-shockwave-flash” width=”200″ height=”15″
data=”/testimonials/xspf_player_slim.swf?song_url=<?php echo $client_testimonial; ?>&song_title=Air-trekkers Testimonial&player_title=Click to hear testimonial!”>
<param name=”wmode” value=”opaque”>
<param name=”movie”
value=”/testimonials/xspf_player_slim.swf?song_url=<?php echo $client_testimonial; ?>&song_title=Air-trekkers Testimonial&player_title=Click to hear testimonial!” />
<embed wmode=”opaque” src=”/testimonials/xspf_player_slim.swf?song_url=<?php echo $client_testimonial; ?>&song_title=Air-trekkers Testimonial&player_title=Click to hear testimonial!” quality=”high” pluginspage=”http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash” type=”application/x-shockwave-flash” width=”200″ height=”15″></embed>
</object>

That is all and…

Thank you for reading.

posted under AJAX, PHP, Wordpress | 15 Comments »