Boom Boom McCullum

I have been looking around for the highlights of Brendon McCullum’s hundred against Australia in the 2nd T20 match in the current ongoing series and have finally found it. When I watched the highlights of this match, I was stunned to see his shot selection against the Aussie pace attack. I was amazed by the number scoops he played over the keepers head against the likes of Shaun Tait who almost bowled the “fastest ball ever” in the recent series against Pakistan. The scoops came mostly in the latter part of McCullum’s innings and the two sixes he scored off the scoops after reaching the century were the best picks.

When Dilshan started to play the scoop against some of the best pacemen during the T20 World Cup, the cricketing world admired his ability and gave the scoop a name and that was the “Dil-scoop”. He stands his ground and makes sure that his head is down while playing the scoop to avoid being hit. He is the best in what he does.

The technique McCullum uses is quite different from Dilshan’s. He completely throws himself away from the line of the ball and plays the shot to make sure that he doesn’t get hit. Some may call this “not-Cricket” but lately we have been seeing a lot of innovative shots being played with the invasion of T20 cricket. Can we call this the McScoop?

McCullum was just the second batsman to score a century in a T20 international. While he was just one run short to beating Gayle’s highest score, he also missed out on scoring the fastest century. He had only faced a ball more than Gayle when he reached the century.

Enjoy the highlights of McCullum’s innings

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • FriendFeed
  • Google Bookmarks
  • Technorati
Cricket, Sports

Quick trip to Kandy and back

It has been a long time since I got into the mode of traveling a bit far for the sake of looking around. I made sure I took my camera with me. I’m not really into photography, but my point-and-shoot camera does capture the moments I would like to share with others. It was just a quick round trip to Kandy. Went to Pinnawala on the way, lunch in Kandy, visited few relatives, stayed the night at my dad’s hometown and a quick run back to Colombo sums up the trip.

The main intention of this post is to share the photos I took during the ride. Most of the photos were taken at the Pinnawala Elephant Orphanage. It always amazes me how beautiful this country is. I used to travel a lot those days. But lately I haven’t. There are lot of places that I still have in mind to visit but only if time permits.

I won’t waste much of your time. Enjoy the photos.

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • FriendFeed
  • Google Bookmarks
  • Technorati
General

Protect your website against SQL injection

SQL injection is one of the deadliest techniques attackers use to exploit the weakness in your database code of your website. Regardless of the technology/scripting language you must make sure your code is 100% perfect against SQL injection.

Here I will use PHP and MySQL examples for its wide usage and also I’m much more comfortable with it.

Here is a basic PHP code that most developers will come up with to access the MySQL DB and get the record of a particular username submitted from a form in our website.

<?php
# Get posted username value
$userName = $_POST["usname"];
# MySQL query string to get the record of the user
$queryStr = "SELECT * FROM users WHERE usname = '$userName'");
# Output the string for debugging
echo $queryStr;
# Execute the MySQL query
$result = mysql_query($queryStr) or die(mysql_error());
?>

For example if the username that was submitted is nazly the code will output the following query and execute it.

SELECT * FROM users WHERE usname = 'nazly'

While the query works perfectly and returns the record of that particular user, a attacker can exploit this code by injecting SQL using the submission form.

For example if the attacker submits ‘ OR ‘t’='t instead of the username the query will be formed like this.

SELECT * FROM users WHERE usname = '' OR 't'='t'

When this query is executed, it will return all the records in the database since t=t will be TRUE always. The impact it will have on the website will be depend on the code after executing the query. But the important thing is someone can make the query behave differently than what we actually expected from it.

It can become deadlier than that if someone submits the following instead of the username
a’;DROP TABLE users; SELECT * FROM userinfo WHERE ‘t’ = ‘t
The query for the above value will look like this

SELECT * FROM users WHERE usname = 'a';
DROP TABLE users;
SELECT * FROM userinfo WHERE 't' = 't'

If the above query is executed, it will delete the whole users table. Similarly an attacker can inject any type of SQL code to modify/delete your tables in the database.

It is a huge security flaw in your code but newbies and even some experienced developers don’t understand the depth of problem. So developers should make sure to take precautionary measures against it.

In PHP you can use the mysql_real_escape_string() function for this task. This function will escape any special characters in the string to be used in a SQL statement.

<?php
# Get posted username value by escaping special characters
$userName = mysql_real_escape_string($_POST["usname"]);
# MySQL query string to get the record of the user
$queryStr = "SELECT * FROM users WHERE usname = '$userName'");
# Output the string for debugging
echo $queryStr;
# Execute the MySQL query
$result = mysql_query($queryStr) or die(mysql_error());
?>

If you try to inject SQL to this example, it will have no affect to the Database since the use of this function

If you are a developing a Wordpress plugin for your website, you must make sure to protect the site against SQL injection as well. Since Wordpress has its own class for database manipulation you should use the methods available in Wordpress.

The escape() function in the WPDB class is much similar to using the standard mysql_real_escape_string() function.

<?php
function myWpPluginFunc($usName){
    global $wpdb;
    $u = $wpdb->escape($usName);
    $wpdb->query("SELECT * FROM users WHERE usname = '$u'");
}
?>

But there is a better option available in Wordpress. Rather than escaping individual values you can format the SQL statement and then use the prepare() function in the WPDB class to escape the special characters. The syntax is similar to using sprintf(). Using the prepare() function, the developer is sure that all values are escaped. So less chance for errors.

<?php
function myWpPluginFunc($usName){
    global $wpdb;
    $qstr = $wpdb->prepare("SELECT * FROM users WHERE usname = %s", $usName);
    $wpdb->query($qstr);
}
?>

For more check out Data Validation in Wordpress.

I wish MySQL functions in PHP had a similar function like WordPress’s prepare()

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • FriendFeed
  • Google Bookmarks
  • Technorati
MySQL, PHP, Technology, Wordpress

Looking for a Nissan March K11?

4355995128_53d71116a3

I have been using a Nissan March K11 for little over a year now. It has been serving me quite well and its in very good condition at the moment. I always preferred a hatchback as it is very convenient when it comes to driving around in traffic and specially parking around Colombo. Due to an urgent need I’m planning to sell it.

I bought this car under Ijarah Islamic Leasing facility, I would prefer to transfer it to someone who is looking for a Nissan March K11 under the same Leasing Scheme rather than actually sell it. Preferably the person whom I will be transferring the lease should be a Muslim since this particular Leasing Scheme doesn’t involve Riba (charging of interest on loans).

Update: I double checked with my Leasing Company. The person whom I will be transferring the lease to can be a non-Muslim but will be continuing the lease under Ijarah Islamic Leasing facility. Hope this helps since I got few calls asking whether this is possible. Sorry for the confusion due to lack of communication.

So if you are interested call me or send me a text message to my mobile. You also can email me requesting further details. When you contact me, I will disclose the amount I need in hand + the installment rate you need to pay to continue with the lease.

My Contact Details
Mobile Number : 077-7487480
Email Address : nazly.ahmed@gmail.com

Here are some basic details of the car.

Make and Model :
Nissan March K11 (1000 CC)

Year of Manufacture :
2000 (Cup Holder Model)

Vehicle Number Series :
HY-XXXX

Transmission :
Automatic

Mileage :
54000 KMs

Average Fuel Consumption :
8-9 KMs/ltr within Colombo
11-12 KMs/ltr Outstations

Features :
14″ Alloys, New Tires, A/C, Power Steering, Power Shutters, Retractable Mirrors, Central Locking, ABS, Dual Air Bag, CD Player, 3-Way Rear Speakers, Remote Key, Rear Wiper

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • FriendFeed
  • Google Bookmarks
  • Technorati
Cars

PHPMailer for the rescue

When we start building a dynamic website or a Web Application using PHP, sending out Emails to the users is always on top of the To-Dos list. In most cases it will require sending the email in a specific template to maintain the branding of the website/application. In this situation the developer has to send out the emails in HTML Format.

When you use PHP’s built-in mail() function with the basic parameters, the email is sent out in plain-text.

<?php
mail("user@mydomain.com", "This is the Subject", "Hello World");
?>

To send out HTML Emails using the built-in mail() function, you will require to add another parameter where you can specify the headers of the email. Here I will add some additional headers to send out a proper a Email with a from address as well. The additional headers should be separated with a CRLF (\r\n).

<?php
#Specify a From Address
$addHeaders = "From: webmaster@ourwebsite.com" . "\r\n";
 
# Set the content-type to send out the email in HTML format
$addHeaders .= "MIME-Version: 1.0" . "\r\n";
$addHeaders .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
 
# Mail Body consists HTML tags
$mailBody = "<h1>Hello World</h1>
                 <strong>Example: </strong>How to send a HTML Email";
 
mail("user@mydomain.com", "This is the Subject", $mailBody, $addHeaders);
?>

In most of the cases there will be a requirement to embed images into HTML since the particular Email template will consists logos, photos etc.

There are actually two ways to do this.

  1. You can specify absolute paths to the images on your site.
  2. You can attach images into the message and link it with a special URI.

For the first method I will use the built-in mail() function itself.

<?php
#Specify a From Address
$addHeaders = "From: webmaster@ourwebsite.com" . "\r\n";
 
# Set the content-type to send out the email in HTML
$addHeaders .= "MIME-Version: 1.0" . "\r\n";
$addHeaders .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
 
# Mail Body consists Images with an absolute URI
$mailBody = "<h1>Hello World</h1>
                 <strong>Example: </strong>How to send a HTML Email with images
                 <img src=\"http://www.mydomain.com/images/photo.jpg\" />";
 
mail("user@mydomain.com", "This is the Subject", $mailBody, $addHeaders);
?>

But this method has few drawbacks. Most of the Email clients do not allow displaying images from absolute URLS coz someone can track the people who will be opening this Email. Its a privacy issue, and you can enable to display images from absolute URLS in your Email client. But you can’t expect every user who will be checking this email to have this option enabled. So the best option is to use the second method.

Using the built-in mail() function to attach images and link it with a special URI can be a painful process in my opinion. It is possible but maintaining that code can be a real pain if the Email templates have to be modified over and over again.

PHPMailer is a life saver when it comes to sending Emails using PHP. Though the built-in mail() function fulfills most of our requirements, special cases like SMTP authentication, attaching files, embedding images can be done effectively and easily with PHPMailer without doing any modification to the Server settings.

You need to download the PHPMailer library files from here first.
The following code explains how you can send Emails with inline images. I added the code for SMTP authentication as well.

<?php
require_once('class.phpmailer.php');
 
require_once("class.smtp.php"); 
 
$mail = new PHPMailer();
 
# Follwing code segment uses a SMTP server to send email
# Comment this segment if you don't wish to use a SMTP server
# Use a SMTP Server
$mail->IsSMTP();
# SMTP Server address                  
$mail->Host = "smtp.mydomain.com"; 
# SMTP Port
$mail->Port = 25;
# Enable debug for SMTP (Only for testing purposes)
# 1 = errors and messages
# 2 = messages only
$mail->SMTPDebug = 1;              
 
# From address and Name                                            
$mail->SetFrom("user@mydomain.com", "User Display Name");
 
# Message Subject
$mail->Subject  = "Message Subject"; 
 
# Enable HTML Email
$mail->IsHTML(true); 
 
# Embed Images into the Email Body
# Attach file logo.jpg and give it an identifier name 'logo'
$mail->AddEmbeddedImage('logo.jpg', 'logo', 'logo.jpg'); 
# Attach file photo.jpg and and give it an identifier name 'photo'
$mail->AddEmbeddedImage('photo.jpg', 'photo', 'photo.jpg'); 
 
# Use the identifier in the special URI format to link with the attached image
$mail->Body = "<h1>Hello World</h1>
                <img src=\"cid:logo\" />
                   <img src=\"cid:photo\" />";
 
# alternate text if the Email client doesn't support HTML
$mail->AltBody="This is text only alternative body.";
 
# Add recipients of the email
$mail->AddAddress("you@yoursite.com");
$mail->AddAddress("you@anothersite.com");
 
# Send out the email 
if(!$mail->Send()){  
    #if Email failed to send
    echo "Email not sent";
    #Debug purposes only
    echo $mail->ErrorInfo;
}
else {
    # If Email was successfully sent out
    echo "Email sent";
}
?>
Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • FriendFeed
  • Google Bookmarks
  • Technorati
PHP, Technology, Web

Revamping lkgeeks.org

lkgeeks.org has been up there for a quite a while now but the traffic to the site seems to be declining at a considerable rate. In a nutshell lkgeeks.org is a Blog/Twitter aggregator that will give a quick glance at the posts/Tweets from our Lankan geeks. It was initially a requirement of mine that turned into a website that everybody could keep a track of. But it has come to a point where even I don’t visit the site often which actually makes the site having zero traffic on a given day. Though it gives you the information you need, there is no interactivity in the site. Also it sucks at usability and I have to admit that I used the technology in an appropriate manner.

I think its high time to move on. I’m planning it to make it a portal for the Sri Lankan geeks. The aggregator will remain but just be a part of the site. I won’t spoil things up but you will know when it happens. When I launched lkgeeks.org, my initial plan was to keep it limited to FOSS Blogs. But with the revamp it may change. So all the geeks who represent Sri Lanka will get equal opportunity to get listed and share their Blog posts and Tweets. Also there would be some sort of filtering that will take place. Non-technical posts/Tweets have to be filtered while @ Replies will be taken off from the Twitter feed. I haven’t really figured out this process yet but I’m just trying to plan things out and you will also know what you can expect. Its a mixed thought and I welcome your feedback on this.

Since Twitter has introduced the Lists feature, I have created a List for lkgeeks.org and once the site is revamped, the Twitter aggregator will be based on this list. I made a tweet about this sometime back. If you are not listed, send me Direct Message on Twitter to get listed.

Also I will be adding a News/Events section. This way everyone can track events around Sri Lanka. Its something I can’t do alone so any voluntary help is much appreciated.

The good thing is that I have a lot of ideas but executing them doesn’t really happen most of the time mainly due to lack of time I get to work on these ideas. You will see changes happening soon. Would love to hear your thoughts as well.

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • FriendFeed
  • Google Bookmarks
  • Technorati
Blog, Social Media, Technology

I keep coming back and this time for real..

At the beginning of this year I made a promise that my blog posts will flow and I will update regularly. But unfortunately for several reasons I haven’t posted anything in my blog since January. Juggling my life between work and family is one of the main reasons. My wife gave birth to a baby boy in January. Since then I have been fascinated by watching him grow. Each day has been a new experience and facing new challenges was exciting. I would have loved to keep posting stuff on my blog but my addiction to Twitter was the easy way out since I could do a blog post in 140 characters and in quick time. Yet there were stuff I want to share on my blog but since my blogging engine is something I wrote from scratch in PHP in 2005 it lacked all the new features a blog should have. So actually I was kinda stuck with the basic requirements to keep my blogging hopes alive.

Couple of months back I made the decision to switch to Wordpress. Since then I have been stealing time and migrating my blog to Wordpress. It was not easy but since Wordpress has a tons of features to import it was just like a walk in the park. But that was just for posts. Importing comments was bit tough but I was able to write few custom PHP scripts and MySQL queries to make the transition smooth. Then I had to categorize and tag posts which I did manually. URLs have changed. But I made sure that I do 301 redirects to all the previous URLs to make sure that I don’t lose my search engine rankings and traffic that has been flowing in. All in all it was fun. I took my own time, and finally its up.

Now I make another promise. My blog posts will continue. Its your support that has kept this blog alive.

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • FriendFeed
  • Google Bookmarks
  • Technorati
Blog, Technology

Extremely Useful PHP Tools

Just came across the 50 Extremely Useful PHP Tools posted at Smashing Magazine which immediately caught my attention. It lists all the great tools around PHP which makes it more easier and fun to code.

I have started to write an article series on PHP which will be featured in an online magazine which is scheduled to be launched soon. I will post more details about it soon.

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • FriendFeed
  • Google Bookmarks
  • Technorati
PHP, Technology

Welcome 2009

"Before the sun sets in this year, before the memories fade, before the networks get jammed, I didn't wish, because my wishes come with the new sun and new day.I Wish u and ur family Happy Sparkling New Year 2009"

The New Year has dawn and had a tough time going through all the text messages and trying to reply to them. But I didn't manage to reply to them all but picked the message above to publish here which was bit different from the standard way of wishing. So a Happy New Year to you all. Let the dawning year bring you Peace and Prosperity.

I just can't imagine how the last year flew away leaving a lot of good memories, a year that brought lot of new things into my life. I started 2008 by getting married, which was a 180° turn in my life. My life style changed a lot after that but I managed to keep my geekhood alive. If you didn't see my blog being updated much, now you know why. But I still managed to post in between my busy work schedule. The last few months was more a restructuring period of my life both work and personal, so that's the reason why my last post it dated back to September. This year I vow that I will do my level best to keep the blog alive with loads of information in time to come.

The tough decision came somewhere in the middle of last year when I had to quit my previous workplace and take up a new challenge. It was a tough decision but I took it. I was at Cenango for almost four years and I do miss all the colleagues I used to work with and the great moments at Cenango. Thanks to all the guys who supported me throughout specially during the tough times and made me what I'm now.

Switching from a two wheel ride to a four wheel drive was the best thing that could happen to me at the end of the year for me. I don't want to erase my past memories I had with my hoodless ride as I used to call it, specially the days I used to get wet like nothing by the time I get home. :D[BigGrin] It served me well for more than three years and still serving for short rides since I have no plans of selling it.

So all and all it has been a great last year and ready to face the challenges that are awaiting this year. I wish you all the very best in what ever you do.

Thanks to all!!!

Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • FriendFeed
  • Google Bookmarks
  • Technorati
General

CHMOD recursively

Time to time I come across this problem when I have to move large portions of directories and files from one location to another. Mostly after extracting from tar archives. The directory/file permissions are often messed up depending on the source I copied them or based on the way I copied/archived them. So I used to use this technique to CHMOD directories and files recursively. Today when I was using this I thought of blogging it for my own future reference. If there is a better way feel free to comment.

CHMOD directories only

find . -type d -exec chmod 755 {} \;

CHMOD files only

find . -type f -exec chmod 644 {} \;
Share and Enjoy:
  • Twitter
  • Facebook
  • Digg
  • del.icio.us
  • FriendFeed
  • Google Bookmarks
  • Technorati
GNU/Linux, Technology