Learning Is Fun

Talks on Web Technology and Better Product Development

Flickr Gallery in WordPress: Integration with FAlbum plugin

November23

Hello!

Recently I added a gallery in wordpress blog that displays photos from a wordpress plugin FAlbum. This plugin is very nice one and works very smoothly with wordpress. Installing and configuring it with wordpress is somewhat tricky and time consuming. Once you set it up, it will be your great tool.

OK. Now let me share my experience in setting up, configuring and integrating the FAlbum Flickr plugin with wordpress blog.

Integrating a small gallery in wordpress

Before we start, please take a look at what we are going to do. Check the following link.

Click here to see a small gallery with 6 photos at the bottom of the page.

Step One: Download and install the FAlbum plugin

First of all, download the FAlubum plugin from the following link:
http://www.randombyte.net/blog/projects/falbum/

Now unzip the file and make sure that you unzip the file in a folder named as falbum. A common error is unzipping the files in a folder named as FAlbum-0.7.1 and uploading it in the plugins folder of wordpress. Make sure that your files are located as follows:

instllation_directory/wp-content/plugins/falbum/falbum.php
instllation_directory/wp-content/plugins/falbum/FAlbum.class.php
instllation_directory/wp-content/plugins/falbum/wordpress-falbum-plugin.php etc

Step Two: Activate the FAlbum plugin

Log in as admin in your wordpress system and activate FAlbum under the Plugins tab.

Step Three: Configure and setup the FAlbum

Now from the Settings tab, go to FAlbum tab as like Settings –> FAlbum.

Here you will find two steps, complete both of them.

Step Four: Set the options and the (dot)htaccess file

Next, you come to FAlbum Options. Now set there everything as per your preference. Remember one important thing. It is about your (dot)htaccess file. If it is not writable, make it writable. Otherwise, you will get a message that your (dot)htaccess file is not writable and the plugin will request you to copy and past some code. Do either way you like.

Just for your information, I am using the the default settings without change any of them.

Step Five: include and add album code in your theme file

I am showing 6 (six) Flickr photo files at the bottom. So I have add the following code in my footer.php file.

<?php
	require_once(ABSPATH.'/wp-content/plugins/falbum/falbum.php');
	global $falbum;
	echo $falbum->show_recent(6);
?>

In my footer.php file code, I placed in a DIV element. So, it looks somewhat like this:

<div id="footerFlickrPhotos">
    <div id="title">Photos on flickr</div>
    <?php
		require_once(ABSPATH.'/wp-content/plugins/falbum/falbum.php');
		global $falbum;
		echo $falbum->show_recent(6);
    ?>
</div>

Step Six: creating falbum.php file from index.php file

Now we will go to our theme directory. Here you see several files like index.php, header.php, footer.php etc. Now copy the index.php file and paste it as falbum.php. Open the falbum.php file and add FAlbum code and a sample is as follows.

<?php
/*
Template Name: FAlbum
*/
?>
<?php get_header(); ?>
<!-- FAlbum Start -->
<script type="text/javascript" src="<?php bloginfo('url'); ?>/wp-content/plugins/falbum/res/falbum.js"></script>
<script type="text/javascript" src="<?php bloginfo('url'); ?>/wp-content/plugins/falbum/res/overlib.js"></script>
<script type="text/javascript" src="<?php bloginfo('url'); ?>/wp-content/plugins/falbum/res/prototype.js"></script>
<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>
   <div id="content" class="narrowcolumn">
       <?php $falbum->show_photos(); ?>
   </div>
<!-- FAlbum End-->
<?php get_footer(); ?>

Upload this new falbum.php file to your theme directory in the server.

Please remember that there are two different falbum.php files in two different locations. So, pleaes do not confuse with one another.

instllation_directory/wp-content/plugins/falbum/falbum.php
instllation_directory/wp-content/themes/theme_name/falbum.php

We have created the second one from our theme’s index.php file.

Step Seven: Check the output

Go to your website, refresh it twice and click on the thumbnail of any flirkr image.

So, you are done. Huh?

Integrating a complete gallery in wordpress

Well. You may want to keep a single page as your album home and in that page you may want to keep some Flirkr photos in thumbnail so that it looks gallery homepage. Fine!

Now let us see how we can do this.

Step One: Read the above part “Integrating a small gallery in wordpress”

Check the above part thoroughly since you will need the knowledge from the above part titled as Integrating a small gallery in wordpress. Since many things are common, I have avoid the repeated description.

Step Two: create a file and link it to wordpress

First of all, create a file and link it with wordpress. You can follow my another article to do this. The another article is here:

http://www.tanzilo.com/2008/11/02/wordpress-how-to-add-and-link-static-or-custom-pages/

Step Three: add the album code to your page

You can add photos in several ways. For example, if you want to add latest or recent 8 photos, add the following code.

<?php echo $falbum->show_recent(8); ?>

If you want to show 8 random Flickr photos, add code like this:

<?php echo $falbum->show_random(8); ?>

You will find more details on how to customize your page in the following link:
http://www.randombyte.net/wiki/falbum/functions_and_variables

Step Four: Customize CSS coding for custom look

Remember that each thumbnail photo will be placed in a list element. So, if this is the PHP code where we place the album:

<?php
	require_once(ABSPATH.'/wp-content/plugins/falbum/falbum.php');
	global $falbum;
	echo $falbum->show_recent(6);
?>

Here is the CSS to make them looking like a thumbnail gallery:

#footerFlickrPhotos
{
	width:323px; margin:23px 0px 0px 48px; float:left;
}
#footerFlickrPhotos UL
{
	margin:0px; padding:0px;
}
#footerFlickrPhotos LI
{
	list-style:none; float:left; margin:0px; padding:0px;
	background:none;
}
#footerFlickrPhotos IMG
{
	width:75px; height:75px; border:#FFFFFF 2px solid;
	float:left; margin:5px 15px 10px 0px;
}

Next, the bigger photo and all other things like next, previous buttons and tags etc will be displayed in a DIV element named as content.

#content
{
	width:580px;
}
#content A
{
	color:#0B4B93; text-decoration:none;
}
#content A:hover
{
	text-decoration:underline;
}

Step Five: Check your site

Now you are done! Go to your site, refresh the site twice and check you album.

So, we are done!

These following two links will be helpful and you can visit them for more information:
http://www.randombyte.net/wiki/falbum/functions_and_variables
http://www.randombyte.net/wiki/falbum/incorporating_falbum_into_your_own_theme

Thank you for reading.

posted under PHP, Wordpress | 6 Comments »

SQL Injection Prevention & Protection in PHP & MySQL with Example

November14

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.

<?php
	$sqlStatement = "SELECT * FROM customers where username='james';";
?>

Case 2:

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

<?php
	$sqlStatement = "DROP TABLE users; UPDATE customers SET age=0; DELETE FROM customers where id>0;";
?>

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:

<?php
	$sqlStatement = "SELECT * FROM users WHERE username = '" + $username + "' AND email = '" + $email + "' ";
?>

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

user@hostname.com’; DROP TABLE users; SELECT * FROM customers WHERE name LIKE ‘%

As a result, the final statement is something like:

<?php
	$sqlStatement = "SELECT * FROM users WHERE username = 'james' AND email = 'user@hostname.com'; DROP TABLE users; SELECT * FROM customers WHERE name 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.

<?php
	$sqlStatement = "SELECT * FROM customers WHERE age = " + $ageValue + ";";
?>

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

The resulting sql is:

<?php
	$sqlStatement = "SELECT * FROM customers WHERE age = 20; DROP TABLE users;";
?>

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:

<?php
	$sqlStatement = "SELECT * FROM users WHERE username = 'james' AND password = 'secret' OR 1=1;";
?>

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:

<?php
	$db_connection = new mysqli("localhost", "user", "pass", "db");
	$statement = $db_connection->prepare("SELECT * FROM customers WHERE id = ?");
	$statement->bind_param("i", $id);
	$statement->execute();
?>

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

<?php
	$sqlStatement = "
		CREATE PROCEDURE HUGEORDER
		(
			id INT ,
			quantity INT,
			price DECIMAL(6,2)
		)
		BEGIN
			DECLARE discount_percent DECIMAL(6,2);
			DECLARE discounted_price DECIMAL(6,2);
			SET discount_percent  =  10;
			SET discounted_price = price – discount_percent/100*price;
			IF quantity > 500 THEN
				SET discounted_price = discounted_price - 0.25 * quantity;
			END  IF;
			UPDATE fashion_products
			SET product_price = discounted_price WHERE product_id = id;
			Select * from fashion_products;
		END;
	";
?>

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.

<?php
	if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email))
	{
		echo 'INVALID Email Address!';
		return;
	}
?>

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,

<?php
	$username = mysql_real_escape_string($username, $ dbLink);
?>

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.

<?php
	// Turn off all error reporting
	error_reporting(0);
?>

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

<?php
	if(!mysql_query($statement))
	{
		echo 'We are sorry BUT The server is not responding. Please try again later.';
	}
?>

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.

<?php
	$visitorDbLink = mysql_connect('host', 'general_user', 'general_user_pass');
	$visitorDbLink = mysql_connect('host', 'admin_user', 'admin_pass');
?>

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:

	<input name="username" type="text" id="username" maxlength="10" />

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.

posted under MySQL, PHP | 2 Comments »

PHP: pass all POST and GET variables in array in function parameter

November9

Hello!

My subject of this post is about the total number of parameters we send as input from a form or any other way and optimizing the parameter passing. If we have many forms and many input fields in each form, it is often painful to set or order value of GET, POST or other variables one by one.

Passing all POST variables as function parameter in one array

Let us see the following HTML form that has ten fields.

<form action="feedback.php" method="post" enctype="multipart/form-data" name="feedbackForm" id="feedbackForm">
	<label for="name">Name</label>
	<input type="text" name="name" id="name" />
	<br />
	<label for="address">Address</label>
	<input type="text" name="address" id="address" />
	<br />
	<label for="phone">Phone</label>
	<input type="text" name="phone" id="phone" />
	<br />
	<label for="fax">Fax</label>
	<input type="text" name="fax" id="fax" />
	<br />
	<label for="email">Email</label>
	<input type="text" name="email" id="email" />
	<br />
	<label for="website">Website</label>
	<input type="text" name="website" id="website" />
	<br />
	<label for="message">Message</label>
	<textarea name="message" id="message" cols="45" rows="5"></textarea>
	<br />
	<input type="submit" name="submit" id="submit" value="Submit" />
</form>

Now if we want to call a function passing all the input fields, it will look like this:

<?php
	saveFeedback($_POST['name'], $_POST['address'], $_POST['phone'], $_POST['fax'], $_POST['email'], $_POST['website'], $_POST['message']);
?>

But does it look good or anything comfortable? I know most coder will be bored doing this. When I was a newcomer to PHP programming, I used to do this kind of programming. But there is no reason to do coding like this as we have extremely simple solution.

Fortunately we can pass a whole array as function parameter value. This is how:

Function calling:

<?php
	saveFeedback($_POST);
?>

Or the Object Oriented Programming style:

<?php
	$myObject = new MyClassName();
	$myObject->saveFeedback($_POST);
?>

Easy and comfortable. Huh?

Getting the values inside the function definition:

<?php
	function saveFeedback($inputArray)
	{
		$myName    = $inputArray['name'];
		$myAddress = $inputArray['address'];
		$myPhone   = $inputArray['phone'];
		$myFax     = $inputArray['fax'];
		$myEmail   = $inputArray['email'];
		$myWebsite = $inputArray['website'];
		$myMessage = $inputArray['message'];
		// Rest of the coding for this function
	}
?>

Simple. Right?

You can also print all the input values inside your function you want for debugging or any other purpose as like this:

<?php
	function saveFeedback($inputArray)
	{
		var_dump($inputArray);
	}
?>

Passing all GET variables as function parameter in one array

Suppose that here is your link:

http://www.example.com/products.php?type=cap&max_price=1000&min_price=100&material=leather

You can pass all the GET variables to a function such as ‘filterKeys’ in this case simply this way:

<?php
	filterKeys($_GET);
?>

Or the Object Oriented Programming style:

<?php
	$myObject = new MyClassName();
	$myObject->filterKeys($_GET);
?>

And here is how you get them:

<?php
	function filterKeys($inputArray)
	{
		$productType      = $inputArray['type'];
		$productMaxPrice  = $inputArray['max_price'];
		$productMinPrice  = $inputArray['min_price'];
		$productMaterial  = $inputArray['material'];
	}
?>

This is just like the way used for the POST method.

You can print the input values inside your function anytime you want for debugging or any other purpose like this:

<?php
	function filterKeys($inputArray)
	{
		var_dump($inputArray);
	}
?>

Although REQUEST method will work similarly, I suggest you not using this for avoiding any future confusion and also for the sake of keeping your coding more readable for other developers.

Special Case: File

Actually when you send a file, it contains several data and $_FILES is an array itself. So, the following values come directly to your script without any extra attention:

<?php
	$_FILES['fileName']['name']
	$_FILES['fileName']['type']
	$_FILES['fileName']['size']
	$_FILES['fileName']['tmp_name']
	$_FILES['fileName']['error']
?>

So, you can use them directly in your script.

Taking another Special Case in Consideration: Setting default input values

Sometimes you may need to set a default value to one or more parameters. For example:

<?php
	function saveClientInformation($age=25, gender='Male')
	{
	}
?>

You can define array and scalar inputs altogether as like this:

<?php
	function saveClientInformation($postInputArray, $getInputArray, $age=25, gender='Male')
	{
	}
?>

Next you can pass array and scalar inputs altogether as like this:

<?php
	function saveClientInformation($_POST, $_GET, 35, 'Male');
?>

So, why should you code like this? Because this will increase efficiency, save some time and make your code clean looking.

Thanks for reading.

posted under PHP | 1 Comment »

WordPress: How to add and link static or custom pages

November2

When I was new to wordpress theme development, I faced a common problem that many others might have faced. That is adding or linking or integrating a static or custom page in your wordpress site. It is very possible that you may prefer to keep one of your page or file linked as the following:

http://www.yoursitename.com/products.php

Sometimes this kind of requirement arrive that you have no other option but to do it.

But you know this kind of link will not directly appear in your wordpress blog or site because of the unique linking structure of wordpress. Most probably you will get a 404 error i.e. file not found error. So, if you want to link directly, you need to follow a simple trick. This trick is simple, small and intereting.

If you want to add and link your custom or static pages, follow these steps and you will get smooth result:

Step One: Changing the header of the php file

In this article, we will add a php file products.php in our wordpress blog. So, please create your products.php file.  Now open you products.php file and add the following two lines at the top of the file and save your file.

<?php
	define('WP_USE_THEMES', false);
	require('./wp-blog-header.php');
?>

Remember, these lines will be the topmost lines in your products.php file. OK? See below how I added.

<?php
	define('WP_USE_THEMES', false);
	require('./wp-blog-header.php');
?>
<!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>Our Products</title>
</head>
<!-- Other lines of coding -->

Why are we adding these two lines? Because we are telling wordpress that this file will not use wordpress themes and we are going to link it in a different way. So, wordpress do not force to link in its usual way.

Step Two: Saving in the public_html or root folder

Now upload it in the wordpress installation directory so that it looks like:

http://www.yoursitename.com/products.php

Done? Great!

Step Three: Linking the products.php file in a usual way

Now in the code of any wordpress file where you want to link your products.php file, keep the html linking as usual or what we say relative linking. For example, in the contact us page, I am creating such a link in the body section:

<a href="http://www.tanzilo.com/wp-admin/products.php">Our Products</a>

And yes! We are done!
Test now if it works for you.

Thus, you can add any number of pages in your wordperss site. I do not know exactly when you may need to link this way. I had to do it time to time depending on the client’s project requirement.

Thus, you can also protect your pages from permalink (dot)htaccess in wordpress.

Thanks for reading.

posted under Blog, PHP, Wordpress | 3 Comments »

WordPress: get page content by page id. Static pages to Dynamic

November1

Hello!

Recently I am working in a wordpress project where I am converting a total static site to wordpress site. What I do is: (1) from the static pages, I am taking the static text and creating a new wordpress page for each static page. (2) fetching the page content/text by page id and (3) showing them wherever I want.

I have written a function and now I can fetch the content of any page or one more pages just by the page id.

<?php
	if(!function_exists('getPageContent'))
	{
		function getPageContent($pageId)
		{
			if(!is_numeric($pageId))
			{
				return;
			}
			global $wpdb;
			$sql_query = 'SELECT DISTINCT * FROM ' . $wpdb->posts .
			' WHERE ' . $wpdb->posts . '.ID=' . $pageId;
			$posts = $wpdb->get_results($sql_query);
			if(!empty($posts))
			{
				foreach($posts as $post)
				{
					return nl2br($post->post_content);
				}
			}
		}
	}
?>

I am using this function to fetch several page data and show them in one page. In the static site, there are several section with different designs. The client want edit each section using wordpress. So, if there are three different sections, I am creating three individual pages for this single page. Next, I am just fetching the content of the three pages by calling my method three times with different parameters and showing the output in one page.

For exampe,

<div id="income_tax">
	<?php echo getPageContent(6); ?>
</div>
<div id="tax_advise">
	<?php echo getPageContent(7); ?>
</div>
<div id="yearly_return">
	<?php echo getPageContent(8); ?>
</div>

Thus, I am just shifting all text and/or content of the static site to wordpress so that the client can edit the site himself. I think this is a simple way or technique if you want to convert your static page to dynamic wordpress site.

You can also customize this one as per your need. For example, you may only need to fetch the page title.

<?php
	if(!function_exists('getPageTitle'))
	{
		function getPageTitle($pageId)
		{
			if(!is_numeric($pageId))
			{
				return;
			}
			global $wpdb;
			$sql_query = 'SELECT DISTINCT * FROM ' . $wpdb->posts .
			' WHERE ' . $wpdb->posts . '.ID=' . $pageId;
			$posts = $wpdb->get_results($sql_query);
			if(!empty($posts))
			{
				foreach($posts as $post)
				{
					return nl2br($post->post_title);
				}
			}
		}
	}
?>

You can not only get the page content, but also the post content if you set the value of the “$pageId” equals any post id. You know you can see the page or post id from the admin panel.

By the way,
I have put my functions in the functions.php file so that I can access it from anywhere. I suggest you following the same way i.e. writing all your custom functions in the functions.php file.

Thank you for reading.

posted under Blog, PHP, Wordpress | 26 Comments »

PHP – MySQL: Unicode solution to Chinese, Russian or any language

October13

Hey Guys,

I am a Freelance Web Developer and my main tools are PHP & MySQL. Few days ago, I got a Chinese project where I had to develop a Real Estate site in Chinese language. You know we often build websites in English and Databases are in English too. So, the default configuration in MySQL works fine everytime.

But when it comes a language other than English, many people do not know what to do. Well. When I started the project, I did not even know that the default MySQL settings will not work for the Chinese language. So, I started searching for a stable solution where my program will support any language for adding, updating and searching data from the MySQL database.

And Yeah.
I found it!

OK.

Let us see the solution now.
It is very very simple.

Step One: SET THE CHARSET TO UTF-8 IN THE HEAD SECTION

First of all, the browser needs to know that you are going to display or use Unicode in this page. So, go to your <HEAD></HEAD> section and set the charset to utf-8. So, the browser will be able to show the Unicode text without any error and smoothly. You can also copy and paste the line below:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Step Two: CREATING THE DATABASE

When you create your (a) Database and (b) any Table in the database, set the Collation of both of them to utf8_unicode_ci and you know it is very easy if you are using phpMyAdmin.

Step Three: DATABASE INITIALIZATION

When you initialize the database connection, please add the “extra lines”

<?php
	define('HOSTNAME', 'localhost');
	define('USERNAME', 'database_user_name');
	define('PASSWORD', 'database_password');
	define('DATABASE', 'database_name');
	$dbLink = mysql_connect(HOSTNAME, USERNAME, PASSWORD);
	mysql_query("SET character_set_results=utf8", $dbLink);
	mb_language('uni');
	mb_internal_encoding('UTF-8');
	mysql_select_db(DATABASE, $dbLink);
	mysql_query("set names 'utf8'",$dbLink);
?>

But why are you adding the extra lines? Because you are letting the database know what kind of input you are going to work with soon.

Step Four: INSERTING INPUTS/DATA IN THE DATABASE

<?php
	mysql_query("SET character_set_client=utf8", $dbLink);
	mysql_query("SET character_set_connection=utf8", $dbLink);
	$sql_query = "INSERT INTO
	TABLE_NAME(field_name_one, field_name_two)
	VALUES('field_value_one', 'field_value_two')";
	mysql_query($sql_query, $dbLink);
?>

Why are you adding the first two lines for? Because the database should know what kind of data is going to be stored.

Step Five: UPDATING INPUTS/DATA IN THE DATABASE

<?php
	mysql_query("SET character_set_client=utf8", $dbLink);
	mysql_query("SET character_set_connection=utf8", $dbLink);
	$sql_query = "UPDATE TABLE_NAME
	SET field_name_one='field_value_one', field_name_two='field_value_two'
	WHERE id='$id'; ";
	mysql_query($sql_query, $dbLink);
?>

So, you are adding the extra two lines before you run your query string as you are playing with Unicode.

Step Six: SEARCHING DATA FROM THE DATABASE

<?php
	mysql_query("SET character_set_results=utf8", $dbLink);
	$sql_query = "SELECT * FROM TABLE_NAME WHERE id='$id'; ";
	$dbResult = mysql_query( $sql_query, $dbLink);
?>

Adding the one extra line every time you search your Unicode data is enough.

OKKK.
You are done. This should work smoothly for handling your data in any language does not matter it is Bangla (my mother tongue), Hindi, Chinese, French, German, Spanish, Russian, Arabian (Arabic), Urdu, or any other language.

And do not forget to leave a comment if you have any. Because I need to update the post in case required.

Thanks for reading and please check if it works for you.

posted under MySQL, PHP | 88 Comments »

Destroy or Delete all session variables in PHP

May2

Sometimes I have seen that coders forges to delete all session variables when the user logs out or sign out. This can be dangerous since this is a security hole. From my own experience I have seen that the session variables may appear even after the sign out. I myself have seen this. This may happen because several people write codes in several ways. But what is important we must delete all session variables when the user signs out.

So, how can we delete all session variables and stop the session variables appear accidentally even after sign out?

Well. We can do it using only 3 lines of code and this is very easy too!

Add these following 3 lines of codes in your sign out code and all your session variables are destroyed!

<?php

$_SESSION = array();
session_destroy();
session_unset();

?>

But if you want to delete the session itself too, you need to add a few lines. So the final code will look like this.

<?php

$_SESSION = array();

if (isset($_COOKIE[session_name()]))
{
setcookie(session_name(), ”, time() – 60000, ‘/’);
}

session_destroy();
session_unset();

?>

Thus, we can destroy our session variables and keep the user secured one way.
OK.
That is all for now.

posted under PHP | 5 Comments »

PHP script to print all the GET & POST variables

March29

Variables are one of the core powers of programming. As PHP programmers, we oftern may find that a $_GET or $_POST variable is not performing properly or the way we expected. This may occur for several reasons such as we made a mistake in the variable name. Sometimes this kind of problem take so much time that lots of time is wasted to correct a single variable!

So, you can use the scripts I have written below and use in your code whenever you suspect that there may be a problem with the variables. These scripts helps you by showing the details of each and every $_GET and $_POST variables in the script.

This is very easy and actually 3 (three) lines of code required.

Below is the code to print all $_GET variables:

<?php

print(‘<pre>’);
print_r($_GET);
print(‘</pre>’);

?>

Click here to see the demo here.

To print all the $_POST variables, we need to change only one line:

<?php

print(‘<pre>’);
print_r($_POST);
print(‘</pre>’);

?>

OK.
You can do it in another way too. It is simple also.

<?php

var_dump($_GET);

?>

Or,

<?php

var_dump($_POST);

?>

So, print your $_GET and $_POST variables whenever you think required.

posted under PHP | 7 Comments »