PHP Optimizations

PHP is my favourite web development language.(Not anymore, its Python now). Nevertheless, here are a few tips I follow to make PHP work faster :

  • When you’re creating PHP files, you’ll start with <?php tags as usual, but DON’T end the file with ?> tags if its not your main index.php file. Its optional and ignoring it is not just safe but recommended. So always leave the <?php tags unclosed in files which you are going to include in your main file. Do close it properly in your main index.php file though.
  • Don’t use functions in FOR loop condition if the function returns the same result always e.g.
for($i=0; $i&lt;length(arr); $i++)

IS VERY VERY SLOW than

for($i=0, $N=length($arr); $i&lt;$N; $i++)

That’s because since the condition is checked on every iteration. The function is called again and again to check the lenght of the same array every time. Instead since you know the array length is the same, why not save it in $N so that it won’t have to calculate it again and again. Though if your array $arr may change in length, you can use that. Continue reading

Advertisements

Defending against SQL Injection Attack in PHP any version

Internet Security is a very sensitive issue and many websites have vulnerabilities which are easily exploitable. One such vulnerability is SQL Injection, in which the attacker can literally execute any kind of query in your database, even gain administrator privileges and if things are even worse, then he may also gain access to your system and execute any command. No wonder how dangerous this vulnerability is, but it has a very easy fix. I’d like to introduce you with a small function escape(), I’ve written for sanitizing data while querying the database, which will disable SQL Injection attacks in PHP, irrespective of the PHP version you use.

function escape($input)
{
if (!get_magic_quotes_gpc()) {
$input = addslashes($input);
}
return $input;

}

By default the Magic GPC Quotes feature of PHP is turned ON. So it will automatically sanitize any data it receives from $_GET and $_POST by placing slashes before any ‘, ” or \ characters. However, as of PHP 5.0+, this feature is deprecated and hence relying on it is highly discouraged. Instead, use the addslashes() function which does the same thing. So the function I wrote will basically identify whether the Magic GPC feature is turned ON, if it is, then it will simply return the query as it is, else it will call the addslashes() method on the query. So simple !
However, there’s a more “secure” version of it. But this one is not suitable for large-scale systems as it requires an extra-connection to the MySQL server.

function escape($input)
{
if (get_magic_quotes_gpc()) {
$input = stripslashes($input);
}
return mysql_real_escape_string($input);

}

You can use the above function as follows :

Find out all the form variables that you receive in your PHP code i.e. all the occurrences of $_GET and $_POST and whenever you use then, use

escape($_POST[‘var’])

instead of just $_POST[‘var’]. Similary for $_GET variables also.

For example, suppose you have stored the mysql query like :

$username=$_GET[‘username’];
$password=$_POST[‘password’];
$query=”SELECT * FROM `users` WHERE `username`=’$username’ AND `password`=’$password'”;

To secure the above code, use this code instead :

$username=escape($_GET[‘username’]);
$password=escape($_POST[‘password’]);
$query=”SELECT * FROM `users` WHERE `username`=’$username’ AND `password`=’$password'”;

or, by writing it in a single line only :

$query=”SELECT * FROM `users` WHERE `username`='”.escape($username).”‘ AND `password`='”.escape($password).”‘”;

This simple thing will completely disable any kind of SQL Injection attacks in your website or web-application, irrespective of the PHP version you use. However, beware of other attacks ! 🙂

Connecting MTS Mblaze USB Modem in Ubuntu

I recently bought myself an MTS Mblaze wireless USB Modem. Connecting it on Linux was difficult because there was practically no tutorial for MTS USB Modem, while many were available for Reliance and Tata Indicom Modems. So here is what I did to finally get it connected (Note : Execute all commands as ROOT )

i) You’d have to install the package USB-ModeSwitch. It is available here : http://packages.debian.org/sid/usb-modeswitch

Note : When you open the above link, you should check out its dependencies and also install the dependency package ” usb-modeswitch-data”.

Just download and double-click on it to install the package.

ii) After you’ve installed usb-modeswitch and usb-modeswitch-data packages, reboot your computer.

iii) Connect the Mblaze Modem and wait for 30 seconds. While you’re waiting, the usb-modeswitch package is doing magic in the background, you can check the status through the following command :

dmesg

iv) I hope you have “wvdial” pre-installed on your system. You can check that by typing “wvdial” and see if the computer recognises it. If it doesn’t then you’d have to install it. Its easy, refer this link.

v) Now edit the file /etc/wvdial.conf (If it doesn’t exists, then create it) as Root and copy paste the following code :

[Dialer cdma]
Stupid Mode = 1
Inherits = Modem0
Password = mts
Username = internet@internet.mtsindia.in
Phone = #777

[Modem0]
Init1 = ATZ
SetVolume = 0
Modem = /dev/ttyUSB0
Baud = 115200
FlowControl = Hardware (CRTSCTS)
Dial Command = ATDT

Note that ttyUSB0 may be different for your system. However, first try with the above code, if it doesn’t works and says some error like “ttyUSB0 doesn’t exists” or something similar to it, then find out the actual one by going through the output of following command :

dmesg | grep -e “modem” -e “tty”

vi) That’s it, you’re done. Now start browsing with the following command :

wvdial cdma

As soon as you start seeing some IP addresses, you’re online! DO NOT close the terminal in which you executed the command, otherwise you will get disconnected.

And from next time, you don’t have to it all over again. Simply connect your modem, wait for 30 seconds and type the last command. To disconnect, goto the terminal, and press Ctrl + C.

Hope it worked for you, if any problems occured, you can leave a reply !

Basics of IRC : Internet Relay Chat

IRC or Internet Relay Chat is a widely used chat protocol over the Internet. From a birds-eye view, its just like any other chat application you use like Yahoo or Gtalk. It lets you talk to other people using text messages over the Internet. So then what’s so different about it?

Lets have a more closer look. IRC is a “protocol” like HTTP,FTP and not an “application” like Yahoo or Gtalk. Speaking in a technical way, IRC is a well-defined Application Layer Chat Protocol (RFC 1459) that uses port 6667 over TCP connection while chat messengers like Yahoo are applications that uses their own proprietary protocols. There are many advantages and some disadvantages of using IRC. Advantages being its an open-protocol means anyone can design his own IRC client. Its very simple, there are just list of rules which you have to follow to talk. Disadvantage is that it doesn’t support features like Video or Audio chat and other real-time multimedia applications. It can, at most, share text and files.

Also IRC is not meant for individual chat (although it is supported). Its developed for groups discussing development of open-source softwares, contribute to research-based discussions and take part in online debates, or just spend time fooling around and see other people talk! IRC have “nodes” or “channels” similar to “chat rooms”. As soon as you join a channel, you start receiving real-time conversations going on. You can just hop in then and say what you have to say to all the members in that channel. Be aware though, the @admin can kick you out anytime if he doesn’t like what you’re saying!

So as I said, its basically for chat related to open-source, discussions and debates, between people with great minds and less time, between old-fashioned geeks who hates twitter and facebook and between people who take inspiration from secretly hearing others talk. To be frank, I myself never used it before the Google Summer of Code 2010 which widely advertise the use of IRC with mentors. Since I’m participating in it, I had to talk to my mentor and for that I needed to learn IRC. It was very difficult to find a nice tutorial especially which deals with making a linux-based IRC client work behind the combo of a proxy and NAT firewall in my college, which blocks the port 6667 with extra-pleasure 😦 .

After some googling I found a solution to my problem. Since I needed to chat mostly in the freenode server, the web-based IRC chat client offered by freenode.net was perfect. Check it out here : http://webchat.freenode.net . You can pick any name and login to any channel. However, if that name is registered, you have to change it within 2 minutes or you will be automatically renamed to some random number. So lets start my actual tutorial on using IRC :

Continue reading

Agate CMS

Agate CMS is my Free and Open Source Software which I have hosted up on sourceforge.net. Its a Content Management System, which means it lets you create your fully functional website in just a few clicks ! All you need to do is work out a template for your website and all the coding part, including user-registration/login, user-management, website content, forms, etc will be taken care by the CMS.

First, I want to tell you a little about why I started this project. I actually never thought of coding a CMS of my own from scratch. What I actually wanted to do is to change the core-architecture of the Pragyan CMS v2, which is developed by the members of the “Delta Force” (the Central Webteam of NIT Trichy), of which I’m a part of. Pragyan CMS has been contributed to by dozens of students from my college and so when I started going through that huge number of PHP files each having some 4 to 5 hundred lines of codes, I didnt felt like actually trying to understand those thousands of lines of codes which were written by a dozen webteam members, the result of which is a code with no fixed convention for “pretty printing”, with many bugs&unnecessary codes, and absence of any single person who knows every single line of the CMS. This is what I call a “loose” software, and it needs to be filled up with lots of patches to remove all the bugs. This is what which encouraged me to write a CMS myself, with strict organization of files and structured code. This took some time but it wasn’t that hard.Finally, when I was halfway through I started implementing new ideas for the core architecture which were very different than what was there in Pragyan CMS. Till that point, Agate CMS was very similar to Pragyan CMS, but after that point, its my own ideas which I implemented which I thought were better than Pragyan’s. Finally I ended up writing a working CMS with an entirely different architecture and new features. I won’t go to the technical details now.

Continue reading

Setting up Reliance/TataIndicom Wireless Internet in Ubuntu

It is very easy to setup a wireless internet connection using your Reliance or Tata Indicom DataCard on your Ubuntu running PC. I’ve myself faced a lot of problems and finally here I am with a well-researched solution. I’ll try to simplify it as much as I can but it is not an easy job. Its going to be a little scary, but don’t lose hope and try finishing steps 1 to 6. Now start following the steps :

Step 1 : (Optional) I’ll strongly recommend you to upgrade your Ubuntu to latest Ubuntu 9.10. If you have not done it yet, I assure you that this will make your life much easier.

Step 2: Download the package ‘wvdial’. If you have an internet connection (may be DSL on ubuntu),  execute the following command :

sudo apt-get install wvdial

However, if you can’t connect your Ubuntu PC to internet for some reason then you’d have to install wvdial manually. This may take some of your time, patience and skill. Refer this article.

After you’ve downloaded and installed wvdial, tighten your seat-belts because its going to be a hell of a ride now!

Step 3 (Don’t Panic!): Now, plug in your Reliance or Tata Indicom data card into one of your USB slots.

TARGET : Determine the name of the port you connected it to. Seems easy, doesn’t it? You’ll see …

There are 3 ways to do that – (a),(b) and (c). Start with (a) and go to the next one only if the previous one fails.

Continue reading

Dr. Wave of Google

Summary in my own terms : Google Wave is an online collaboration media. Actually, its like a conference chat application, the only difference is that “chats” are now called “waves” and can also have videos,docs,pics,gadgets, etc.. and of course, google wave has the most interactive web-based platform I’ve ever seen.  You can have real time multimedia conferencing using wave, where others will see/hear exactly the same thing as you. Well to be frank, I don’t find something very new in google wave, because other applications do exists for the same purpose (though not web-based, and some are not even free like Cisco’s). Anyways, wave is still under development and I only hope more features are added to it with time.

By the way, I have 8 invites of Wave, anyone wants ??? 🙂

Overriding Inline Font Using CSS

Recently I discovered something very cool in CSS while working on the new template of my college website. My college website uses the Pragyan CMS v2, which was written from scratch by the members of Delta Force ( or the Central Webteam of NITT ). Our college is one among those few institutions in the world which uses a home developed CMS for its website, all others use the free CMS like Mambo, Joomla, Drupal, etc. Now that is something which makes you proud of being in Delta, but not to forget every good things comes with some sacrifices. In this case, the Pragyan CMS uses a WYSIWYG editor that enables anyone anywhere in the world to change the content of each and every page of my website if he has the necessary permissions. The main problem which I faced because of this was while designing the template of the faculty pages. Every faculty of my college has been given permissions to edit the content of his webpage in the college website. Ofcourse this sounds reasonable, but the problem is that not all faculty members has a good sense of professional looking website designing. So they end up using odd colours, underlining, changing the text height and weight and font in order to make it more attractive. This is surely not acceptable in a professional website as all the pages needs to be uniform in styling as well as in content. So I pondered upon how to tackle this problem and wow! I got the solution.

What faculty members, or infact any user with permissions who uses the WYSIWYG editor for modifying the contents of the website, controls is the source code of that particular page while I control the main CSS stylesheet. So all I needed to ensure that even if they put tags like <font> and inline styling attributes like style=””, they shouldn’t work! And yes there is a way to do it. All you need to do is to make sure that your CSS settings override the inline stylings. This can be done by putting the !important tag next to the CSS attribute which you want to be permanent.

In cases like defining CSS for font and span tags where you dont want any specific pre-defined attribute to be used always, all you can do is to use the inherit option in place of the value of the attribute. This will make sure that whenever these tags are used inline in the HTML code, there styling is overridden by whatever styling there parent has. So even if you put a <font> tag inside the <h1> tag, then no matter what you specify in the font tag, the styling will always be done according to the CSS of the h1 tag. Ofcourse since you are also overridding the inline styling you also need to put the !important tag. Hence overall the code becomes :

font, span

{

	font-family : inherit !important;

	color       : inherit !important;

	text-weigth : inherit !important;

	font-size   : inherit !important;

	text-decortation : inherit !important;

	

}


and to make sure that your CSS styles for h1,h2,h3,a,p,etc cannot be changed by inline styling, just use !important. For e.g.

h1

{

	font-family : calibri, arial, verdana !important;

	color       : #000000 !important;

	text-weigth : normal !important;

	font-size   : 1em !important;

	text-decortation : none !important;

}


Now this will make sure that all the beautiful inline stylings done by faculty and staff members with no sense of webdesigning gets overriden. This is surely going to make some of them bang their heads as they wont be able to know why there tags aren’t working ! 🙂