Tagged with " Example"
Dec 31, 2008 - PHP    11 Comments

PHP: Serialization & Unserialization explanation, code & example

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

And here is the related class:

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.

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.

Dec 23, 2008 - PHP    14 Comments

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

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:

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.

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.

Dec 19, 2008 - PHP, Wordpress    45 Comments

WordPress: get page id and content with example & code

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.

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.

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

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.

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.

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.

Nov 28, 2008 - PHP, Wordpress    3 Comments

WordPress: Creating a Static Front/Home Page without Plugin

Hello WordPress Developer!

When I was new to wordpress blog devevelopment, I got few projects where the clients wanted a static homepage and a Blog link in the menu. In some other projects, the clients wanted to make the homepage to be semi dynamic; that means in the homepage we will show some wordpress data like three latest posts and other things will be static.

You know when we install WordPress the homepage is by default going to show the latest 10 blog entries. But now the homepage will be static, semi dynamic or anything. We will create a page and link it to default WordPress homepage.

OK. Take a look below of what I mean.

I tried it several ways. But I was not satisfied the available solutions. But luckily I figured out a stable solution. My solution does not need any plugin and it is simple too.

Step One: Create your custom homepage

First of all create your homepage as static, dynamic or whatever you want name it as home.php and remember that when visitors come to your site, they will see this file running as front page or website homepage. Upload it in the theme directory.

Step Two: Create your blog homepage templae

Create your blog homepage template and name it blog.php or anything. For clarity and relevance, let us name it blog.php and upload it in the theme directory.

Here is the code:

Step Three: Create your blog homepage

Now create your blog homepage index and name it as index.php and then upload it in the theme folder.

Here is a sample of blog index.php file code:

Step Four: Create a page as Blog from admin panel

Now log in to the admin panel and create a page named as Blog. See the image below what I mean:

Do not save or publish this page right now. Follow the Step Five below before you save or publish this page.

Step Five: Set the blog page template

Now go to the Advanced Options section at the bottom. Under Page Template, select Blog template for this page.

Take a look of what I mean:

Now publish your page!

Now you may ask how this Blog template is coming? It is coming because of Step Two and of the first 5 (five) lines as below:

Step Six: Check your site

Now go to your site and check everything! We are done!

I must say a big thanks to my American friend Joshua Knowles for his contribution to find out this smooth technique. Although Joshua is not a regular developer, he is a brilliant guy indeed!

Thank you for reading.

Nov 14, 2008 - MySQL, PHP    2 Comments

SQL Injection Prevention & Protection in PHP & MySQL with Example

What is SQL Injection?

SQL Injection is the process when someone executes one or more SQL statements in your database without your knowledge to harm the data in your database. In this technique, someone exploits a security vulnerability in database application layer. This happens often when you ask for input(s) from the user and they add extra SQL statement(s) with the valid input. We can illustrate this situation with two cases (1) user inputs are incorrectly filtered or (2) user submitted data is not strongly typed and one ore more of the inputs is executed unexpectedly.

This is possible because the user can submit any input and you may have no or weak user submitted input filtering coding, you can execute one more statements in your database at a time.
For example,
Case 1:

Executing one statement at a time is OK.

Case 2:

Executing more than one statement at a time is also OK.

Now an intruder can combine Case 1 and Case 2, run all the queries at a time and then delete the users table and harmfully update the customers table.

As a result, a successful SQL Injection occurs and harms the database information.

Reasons behind SQL Injection

In the following situations, SQL Injection happens.

  • Incorrectly filtered escape characters
  • Incorrect type handling
  • Vulnerabilities inside the database server
  • Conditional Errors

Case 1: Incorrectly filtered escape characters

You have a module that asks for user’s email address to send a temporary password to her email address when she forgets her password. So, the usual SQL query will be like this in this case:

But an intruder can extent this statement if they set the value for the $email variable in this way and delete the user table:

[email protected]’; DROP TABLE users; SELECT * FROM customers WHERE name LIKE ‘%

As a result, the final statement is something like:

So, you see the intruder is deleting the users table easily. And as a result, you lose your users table and your system crashes since no user will be able to log in from now on. If you do not have a database backup, you loose everything.

Case 2: Incorrect type handling

Sometimes you definitely know the type of data. For example, the age of a customer is a numeric value, gender of a user as male or female, total amount of bill as double value.

Now what if someone submits the $ageValue value as 20; DROP TABLE users

The resulting sql is:

You know for sure that the value of will be always an integer. If you do not check if the value is really an integer, the intruder can add one or more statements with the value of $ageValue variable and harm your database.

Case 3: Vulnerabilities inside the database server

Although some people think that they can avoid SQL Injection just by using mysql_real_escape_string() function in PHP, they are wrong unfortunately. Built-in functions supplied with language package to work on database is sometimes vulnerable to database and thus are not successful to avoid the attack all the times.

Case 4: Conditional Responses

Using SQL Injection the user can easily bypass the sign in or log in process in your system. Let us give an example:

Now you know satisfying only one condition is enough to enter the system. The condition OR 1=1 is always true. Thus, the intruder can fool the log in system.

SQL Injection Prevention and/or Protection

These are the techniques for preventing SQL Injection:

  1. Use Parameterized Query
  2. Use Stored Procedure whenever applicable
  3. Apply Regular expression to discard invalid inputs
  4. Write and use Quote blocking  function
  5. Hide detailed error messages from the user
  6. Create a database user with less privileged role
  7. Set the limitation for maximum value in your HTML form

1. Use Parameterized Query

Rather than directly supplying the values in the SQL statement, let us supply the values in parameterized way as follows:

“i” stands for integer type
“d” stands for double type
“s” stands for string type
“b” stands for a blob and will be send in packets

2. Use Stored Procedure whenever applicable

Using stored procedures can help your to reduce the attack risk too.

3. Apply Regular expression to discard invalid inputs

Regular expression is very powerful process to find out the validity of the inputs. We can check whether the input is given in proper format. For example, here we validate data for a valid numeric value for customer age and reject any chance for SQL Injection.

You can also user the built in PHP is_array(), is_bool(), is_double(), is_float(), is_int(), is_integer(), is_integer() etc functions to check if the user provided information is in proper format.

4. Write and use Quote blocking  function

If you are using PHP, mysql_real_escape_string function for each and every user given inputs. For example,

This is a very powerful built-in PHP function and will stop SQL Injection in most of the cases. I have used it for long time and found it performing great. You can try to inject SQL after you use the mysql_real_escape_string function and test if you can succeed any way. This powerful function rejects the possibility of many clever techniques used by the intruders.

5. Hide detailed error messages from the user

First of all avoid using the built-in MySQL mysql_error() function. The clever intruder can guess many things from the error message and sometimes the error message may show the connection parameters. Using mysql_error() function is good at development stage. But avoid or clean it when you run it in the real server for users or visitors.

The second thing is stop error reporting in PHP. This is simple and one line code.

The third thing is better you give a customized error message. See an example:

As a result, the user will not know what the error is and how it is. He will also not get any accidentally disclosed crucial information such as database name, table name, username etc.

6. Create a database user with less privileged role

In most cases, you will notice that the visitors do not need to delete or update any information. Think of a music selling site. The user can request for data (which is SELECT query) and make their orders (which are INSERT query). Even sometimes the SELECT operation is just OK in many sites.

So, create different users with different privileges. For admin grant all the permissions. But for a general visitor, grant only limited permission. For example, I am creating, two connection string for two users.

And now we can user the $visitorDbLink link for regulating information connecting with the visitors and will use the $visitorDbLink link only for the administrator.

7. Set the limitation for maximum value in your HTML form

We can set that the username cannot be more than 10 chars. Try to use the “maxlength” property for HTML form. An example is like this:

As a result, possibility of attack by intruder somewhat goes down since he cannot input enough harmful SQL statement input. But it is not very helpful though and the user can bypass this creating his own form and submitting the custom form.

8. Using a PHP Framework

If you are using a PHP framework like CodeIgniter or CakePHP, the framework will protect you at maximum level from SQL injection. Complain of SQL Injection after using a PHP framework is rare and I did not hear even one still now.

This kind of frameworks are Open Source, very matured and strong nowadays and they do each and everything possible such as from input filtering to URL rewrite. Learning them is easy although it take some time. You can get books and other online materials about this PHP frameworks.

If you are an advanced PHP coder or developer, my suggestion is you better code using a PHP framework you like.

These are all I know about SQL Injection.

Thanks for reading.