The Joys of Computing

Used to be something else but now basically contains some useful PHP scripts. That's all!

Sending Mail

Posted by crz on February 7, 2010

Sending mail using PHP is very simple. Here I’ll show how we can send the activation mail to a registered using along with the verification key we generated in last post.

<?php
    $emailto= "recipient@example.com";
    $frmname="yourid@yoursite.com";
    $subject	= "Activation-yoursite.com";
    $min_size	= "1";
    $max_size	= "4000";
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
    $headers .="To:".$emailto."<".$emailto.">\r\n";
    $headers .="From:".$frmname."<".$email.">\r\n";
    $headers 	= "From: yourid@yoursite.com";
    $message	= "Registration Successfull!!\n\nThank you for registering with us. \n\nUser name: ". $username . "\nPassword: ". $password ."\n\n Click here for activation.\n www.yoursite.com/activate.php?&verikey=".$pass;
   $ok = @mail($emailto, $subject, $message, $headers);
   $msg	= "Registered Successfully";
   header("location:register_suc.php?msg=$msg");
?>

This will send the recipient with the username and password along with the verification key generated instructing them to click on the link to activate their profile. We will see how to implement the activation page in this post. We also need to understand how to first add the generated key to database. The database techniques can be understood from this post.

Posted in Email, PHP | Tagged: , | Leave a Comment »

Generate Verification Key

Posted by crz on February 7, 2010

While registering with a website we often need to verfy our email id. Given below is the code to develop that functionality. The following will generate the verification key which has 6 characters

function generatePassword()
{
    $length =6;
    $validchars = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    $password ="";
    $counter = 0;

    while($counter &lt; $length)
    {
        $actChar = substr($validchars, rand(0, strlen($validchars)), 1);

        if(!strstr($password, $actchar))
       {
           $password .= $actChar;
           $counter++;
       }
   }

   return $password;
}

rand(0, stlen($validchars)) – generates a random number between 0 and the length of $validchars (inclusive of both ends).

substr($a, $b , len) – get generates a sub string from $a from the first occurrence of $b to length specified by len.

strstr($a, $b) – checks whether $a has $b in it. This is done to create unique characters.

So this is how you generate random string. How you can use it for verification purpose of a user registration is explained in the subsequent posts.

Posted in Email, PHP | Tagged: , , | 1 Comment »

Basic connection string

Posted by crz on February 7, 2010

This is very very novice kind of thing. Every web application requires script like this. Usually we write the following in a file named connection.inc which would later be included in files as needed.

$host = "localhost";
$dbname = "database_name";
$username = "user";
$password = "pass";

function dbConnect()
{
    global $host, $username, $password, $dbname;
    mysql_pconnect($host, $username, $password) or die("Error connecting to database");
    mysql_select_db($dbname) or die("Cannot select the database");
}

mysql_pconnect() makes a persistent connection. When connection it listens for any open connections and uses it if available. Also once the script ends it won’t close the connection. It will remain open for any further connections. It cannot also not closed with mysql_close() function.

Posted in Database, PHP | Tagged: | Leave a Comment »

Moved to a new domain!!!

Posted by crz on January 1, 2010

Hi,

From now on you can check my blog at my new domain here. This site is just kept for historical reasons. Sorry for the inconvenience.

Thanks

Christy John

Posted in Uncategorized | Leave a Comment »

What the Llama taught me? Part – 1

Posted by crz on September 5, 2009

Yesterday I finished reading the Llama book. I need to go through the book again since I didn’t get a thorough understanding of all the contents especially the last chapters. Any how I got a glimpse of what Perl could do and I’m so amazed by most of what it could do, that I ordered 4 books of the Internet, the Llama, Alpace, Vicuna and Camel (The Llama I hold now is a friend’s copy).

Here are some of the new constructs I learned in Perl and some others which are there in other languages but treated differently in Perl. (NB: I have only recently started learning Perl and my experience is litle. So these are what I understood, may be some are not perfectly right. But If some one points out so, I’m willing to correct my entry.)

I believe a newbie can read this and get a bird’s eye view of Perl before getting hold of a Llama.

1) There are no integers. All numerals are treated like floating point by Perl. So 10/3 yields 3.3333… always. However in the case of ‘%’ floats are converted to integers (I’m not sure how Perl makes this possible as there isn’t an integer in Perl, or so I’m said, Some one may give an explanation in comments.).

2) Underscores can be used to add clarity to integer literals.
eg : 12_345_678 is equal to 12345678

3) Principle of “no built-in limits“. eg: You string length can range from 0 to infinity(meaning how much your memory can hold).

4) String repetition operator ‘x’.
eg: "Chris" x 3 is ChrisChrisChris.
Once again here too, if the right operator is a float it is truncated to corresponding integer value.

5) The block curly braces are ALWAYS needed around the conditional code. This is some kind of an inconvenience compared to C rule of no need for the braces if condition is followed by a single line. I believe this is made compulsory to aid readability.

6) The use of an uninitialized variable doesn’t yield a fatal error. Uninitialized variables are pre initialized with a special value ‘undef’, which acts like ‘0′ in numeric context and as empty string in string context. Using the ‘warnings’ pragma will sometimes arise a warning about the use of ‘undef’ values’. There is a defined() function to check whether a variable is defined.

7) There is no need to declare the aray size. It can grow up to whatever size it like. If you declare $fred[999] = 'somevalue' for an array @fred which earlier had only 2 members, the above code would extend the array to 1000 elements with all the elements from $fred[2] to $fred[998] as ‘undef’.
Also you can index the array with a float number(It isn’t an error, but will be truncated) so $fred[2.324] means $fred[2]. You can even use the above said technique of ‘underscores’ to denote an array inex. eg $fred[123_456]
The last array index can be found out by $#fred. Also you can use negative array index to access the array from end. eg $fred[-1] is equal to $fred[$#fred].

8 ) The list literals are  great innovation. The range operator (..) and qw shortcut are great way to ease the coding. [NB: The range operator only counts uphill , there is a reverse function for the opposite.]
The list assignments is an easy way to assign values.

9) The list construct makes it easy to swap two variables easily, that too without a third variable.
eg: ($fred, $barney) = ($barney, $fred) # This swaps the contents of the two variables.
Wow! What an idea!. That’s why I said list is indeed an innovation. There are more techniques like these in lists. When working with lists you will feel that Perl has got artificial intelligence of some sort. It knows to discard values when the two sides of the equal signs aren’t balanced.(Actually as a matter of fact, there are a lot of places where we feel Perl has got AI built in. May be it’s the reason why people complain Perl is hard. Here we are dealing with a beast which has got brains of it’s own. So it’s quite natural to need brains to tame it)

10) push, pop, shift, unshift etc are some array operators which makes life easy while working with arrays.

11) Once again a portion, where Perl shows intelligence. It knows whether you are talking in scalar or list context. So we also need to be intelligent enough to know the context while talking with Perl.
eg : reverse in list context gives the list from the last member whereas n string context reverses the string. You can force a list to scalar context by explicitly using the scalar keyword.

12) Sub routines in Perl is a section where there is a lot of astonishments in store for a newbie. The usual method of calling a subroutine is &<sub routine name>, but it is not always so. If Perl can understand it is a function call somehow then you can use a simple <sub routine name>. This means if the sub routine definition is provided in the code before the call or if there are parameters in the function call(If there are parameters, it ought to be a function, cool logic. isn’t it.?). Now even the skeptics among you can believe my claim ‘Perl is intelligent’.

13) There may or may not be return in a function. If there isn’t a return, the result of the last executed line of code is the return value (Please make sure you understand correctly what is returned since in the earlier days of Perl this can rise a lot of troubles)

14) There are multitude of default variables like $/, $_ etc which maybe confusing at first but once start to get going, these makes life more easy. for eg: $_ default variable makes it possible to write the foreach loop like
foreach (1..10) {
print($_);
}

instead of
foreach $num (1..10) {
print($num);
}

both of the print the numbers from 1 to 10, but the former one may be easier to write. You may decide which one you should use. If you find the second one more readable or say more in tandem with your foreach constructs in other languages go for the second.

15) I have been saying this for a while but even the motto for Perl is ‘There is more than one way to do it’. Do you know we can even write the for instead of the foreach in the above example.

There is more I can say, but I read somewhere the attention span of the average reader diminish by 70% after the first 15 points , so I’m reserving the rest of it for another post.

So here is what to emphasize before the small break.

So Perl is an intelligent beast which is wild(read as powerful) but yet domesticable(suits even the beginner) [Can you find a similarity with camel?]. If you are in any doubt, please try it, and be amazed.

add to del.icio.us : Add to Blinkslist : add to furl : Digg it : Stumble It! : add to simpy : seed the vine : : : TailRank : post to facebook

Posted in Perl | Tagged: , , | 20 Comments »

Why I love Perl already?

Posted by crz on September 2, 2009

Since I have only started learning Perl I’m not yet qualified to talk about the programming aspects of the languages.I also don’t have much experience with lot of other languages so wouldn’t try even comparing them. Here I’m only trying to state a few traits of the general Perl community and programmers, which I already started loving.

1) Perl people are passionate.
Have you ever talked to a Perl programmer? The chances are that you will start programming in Perl too. Actually I too was brought in like that by a friend. Perl Programmers love Perl more than anything in the world and will do anything to popularize it. If you are in doubt check the community.

2) The gurus are there to help you
The irc channel contains knowledgeable guys and they are always ready to help a newbie. Whenever I had doubt I visited the #perl channel in freenode and my doubts were cleared within minutes. Yesterday I saw a senior member in irc stating “:) Ha I didn’t kill a newbie”, after explaining a seemingly easy doubt for a newbie and the newbie reporting to check into the matter further. The emotion embedded in the statement was how much the Perl community want new people to come in. I don’t know if this is normal with all the programing language channels, but in #perl you are sure to be in company of prominent and great guys. It is possible that the author of the book that you following explaining your doubts.

3) Great documentation
Good documentation is available online, for download and most of the time pre installed in linux.
Documentation is rather exhaustive and you get to learn every aspect of the language from this alone. However there are also lot of printed material to assist. The Llama, Camel and Alpaca are the premium source of education in the field of Perl. The documenation got a new and nice face lift recently and is rather god looking and easily navigable.

4) Highly expressive and less restrictive language
The language is really expressive and less restrictive. There are more than one way to do things, and actually it is the motto of the language. At first a newbie may find it hard to remember all of these different techniques and also some of the language constructs may seem confusing and unnecessary. But a few days in Perl and you will start enjoying all of these and it begins to seem second language to you. For a sample of what I was saying look into the last post. For another example you will get confused (I got) that a subroutine can be called with and without a ‘&’ and you doubt why? But a couple of pages more into the Llama would tell you the reasons. And once you know the reasons, you will appreciate it, and sometimes you even wonder how in the world Larry even visualized this feature. Another thing I found in my small experience so far are two new constructs, unless and until. I haven’t seen any of these in any of the languages I have used so far.You may argue by saying it is same is made possible by adding a ‘!’ in front of ‘if’ and ‘while’. Yeah, it is true, but it is great to have those and it makes you more expressive and I’m sure Perl have more of them in stock for me.

5) Nice and humble people.
There are more but I’m stopping with this one. This is by far the most important thing I have noticed. Perl people are humble. They love their language and are passionate about them but would never belittle another languages. Most of them are well versed in many languages. Actually all of them would tell you to learn other languages too and use one which suits you. I think the confidence is from the fact that once you start coding in Perl you are unlikely to move into others. Perl is pretty addictive.

add to del.icio.us : Add to Blinkslist : add to furl : Digg it : Stumble It! : add to simpy : seed the vine : : : TailRank : post to facebook

Posted in Perl | Tagged: | 7 Comments »

Explantion on the use of chop() and chomp() functions.

Posted by crz on August 31, 2009

In an effort to learn Perl I was going through the Llama book. When I came to the second chapter there was an exercise where we need to enter two numbers and the program will return their product. I did the program and it worked well except for a small glitch. Here is my code and the output.

#!/usr/bin/perl
print "Enter the first number : ";
$num1 = <STDIN>;
print "Enter the second number : " ;
$num2 = <STDIN>;
$prd = $num1 * $num2;
print "The product of $num1 and $num2 is $prd\n";

The code worked well and outputted 20 if we enter 4 and 5 but it printed output like this.

Enter the first number : 4
Enter the second number : 5
The product of 4
and 5
is
20

Now it was annoying. Having only started programming in Perl and my previous experience in C or Java or even PHP never made me expect something like this. I expected it to print the whole sentence in one single line. What could be wrong. Then I recalled Llama telling about <STDIN> adding a ‘\n’ to the input and the need for using chomp() to get rid of this.

So I modified code and added two more lines

chomp($num1);
chomp($num2);

This made it correct. But still I found it odd and thought this feature of <STDIN> a nuisance. So I went into some knowledge hunting. I asked in #perl channel at freenode. So far I was wary and wasn’t talking and was merely listening. I was afraid even while asking this of getting some serious ‘RTFM’. But the folk in there responded nicely. Thanks for <claes_>. He gave the apt reply. Here is what I learned from him.

There is a special variable in Perl named $/ which is initialzed to be ‘\n’. This variable is termed the input record separator. This variable is used to separate the various lines from your inut. Since $/ contains ‘\n’ it assumes your input has been ended once you key in the return key.(Note: Though the ‘\n’ is not a part of the intended input, since you entered it it will also be included as a part of your input). That’s why we get the newline when printing it back. When we use chomp() it removes these ‘\n’. If we explicitly assign say, ‘f’ to $/ then <STDIN> enters whatever up to the first ‘f’ it sees. Also the functionality of chomp() changes. It will now remove the last ‘f’ from your input (Once again though ‘f’ wasn’t in your intended input, since you entered it it would be there, Please don’t do so. Leave ‘$/’ to the ‘/n’, or be ready to bear the dire after effects). So $/ variable helps in entering user input from standard input.

Another option is to use in the above example is the chop() method [I earlier called it a better option, but I taking that away as per the info by 'Andrew']. When chomp() removes whatever declared in the $/ variable, chop() removes the last character from the input.

So in the below snippet
$str = "Christy;
chop($str);
print $str;

the output is ‘Christ’;

I think I was successful in explaining the issue and let this save another newbie someday.

[Revision: Thursday 3 Sep, 2009, There was some confusion in the explanation of input record separator. Thank to Chas Owen. I corrected it.}

add to del.icio.us : Add to Blinkslist : add to furl : Digg itStumble It! : add to simpy : seed the vine : : : TailRank : post to facebook

Posted in Perl | Tagged: , | 12 Comments »

Stepping into the world of Perl.

Posted by crz on August 31, 2009

Alan Haggai Alavi a friend of mine and another Perl hacker introduced me to Perl a few days back. He has been doing steady Perl coding for a while and has submitted some modules in CPAN and is a known name among some elitist coders in the Perl community. I am happy to have him as my friend.

Much to the anger of the die hard Perl hackers, I was also an ignorant fellow who confused Perl to be synonymous wih cgi. But Haggai and some reading on the matter got rid of the misinformation. Haggai showed me some samples of a CMS he was developing in Perl. It is using catalyst as the frame work. He showed me how to do a Unit Test, though most of it was Latin to me, since I haven’t yet done Test driven development (I know for a programmer with more than 2 years of experience it is a shame, What to do, all the work I have done so far didn’t demand one. I’m pretty beginner.). However this got me excited and I started looked into Perl.

There are so much myths regarding Perl and I’m yet to gain experience to believe or dispel one. From what I heard from people who actually code Perl is that Perl is robust, powerful and a less restrictive language. So I’m going to learn it.

One more thing I love about Perl is the passion among Perl coders. They will Eat, Drink and Sleep Perl and will do anything and everything for the language. I haven’t seen such a kind of emotion in no other language community. Also the Perl coders are humble. They don’t belittle other languages. They even tell people to learn more languages to experience the difference and gain wisdom. This is some kind of emotion which isn’t seen elsewhere. For an experience, ask a python programmer what he feels about Perl. I think this cool behavior of Perl programmers must have been inherited from Larry Wall (I don’t know him personally. But I read he is a very religious guy. So it implies he is humble).

Haggai also introduced me to Ohloh and Stack Overflow. Since I haven’t developed any open source software and isn’t yet a genius my rating there is very poor. But I believe I can improve in the coming days.

I also decided to join the Iron man competition.Maybe I’m vain, but I have a dream. One day I too will a known name in the open source community. Like Matt S Trout, Shlomi Fish, Randal Schwartz, brian d foy, Larry Wall (Oh, God! I’m really vain)  one day Perl community will know me too.

Posted in Perl | 3 Comments »

What is actually unicode and how Java implements it?

Posted by crz on August 9, 2009

In an attempt to move into the field of enterprise application development I started refreshing my Java recently. I was going through a well known book when I stumbled upon the implementation of  Strings in Java. I have high esteem for the developers at Sun, but I really could not digest the fact that Sun engineers thought 2 bytes would be enough for characters. It was kind of  Y2kish. Now that the UTF has grown above the usual number 16 bits can represent I was eager to find how Sun tackled this problem. The book touched the matter vaguely but since that didn’t completely clear my doubts I decided to investigate. And these are my findings.

Before we dive into the Java implementation of the standard, we should understand what UTF is. At least some of us might have seen it somewhere. May be those of us who have the creepy behavior of going through the source of an HTML page might have seen the following,
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />.
And we may have a vague idea on what it does. Don’t worry let’s understand what it really is.

Unicode is an internationally accepted standard to define character sets and corresponding encoding. And the above piece of code is informing the browser that the document should be interpreted using the utf-8 character set.  So what exactly is UTF or Uniform Transformation Format?

In order to completely know about Unicode, we have to traverse a few decades back when people thought the earth was the center of  the universe and it was indeed flat. Oh sorry, we have to traverse a few decades back when the majority of the software was written by English speaking people. It was only quite natural they thought the only set of characters ever to be  encountered in the realm of programming would be from English alphabets, numerical digits and a couple of other prominent characters. So it was logical to use 28 or 256 bits to represent the set of characters. It was enough for the normally used characters back then and also space were left for the inclusion of characters in the future. The problem started when different people started encoding different characters in the free space. What evolved was chaos. Also when the internet happened, all the people around the globe  started using technology and started tweaking programs to their likes and in their own native languages. It became impossible to fit all the characters into the tiny space of 256 bits. Soon the encoding system known as ASCII ran out of space and a need for a better encoding system evolved. To make a long story short, thus evolved UTF. More on this can be read from here and here.

In UTF characters are represented by code points. It is usually a hex number preceded by U+. For example U+2122 means TM, the trademark symbol. The prominent UTF encodings are UTF-8, UTF-16 and the latest one being UTF-32. These three are methods to represent the UTF character set using 8 bit, 16 bit and 32 bit respectively. To get a more detailed and exclusive idea on Unicode please read Joel Spolsky’s post.

In Java from beginning characters were represented by 16 bits and for some time it was enough to represent all the characters. But since the characters included into UTF overgrew the 16 bit realm, Java was faced with a dilemma, either to change the char representation into 32 bit or use some other methods.. It is not of much issue since most of the characters outside the 16 bit representation is rarely used. But since Java is a language which believes a in portability very much and the engineers in Sun are much more intelligent than the average developers like us, they found a way to circumvent this issue. Java is now equipped to represent all the characters in the 32 bit realm also. So how does Java tackle the supplementary characters out side the 16 bits? What Sun employed to get out of this mess was UTF-16 encoding. So what is UTF-16?

To quote Wikipedia UTF- 18 is a variable length character encoding for Unicode, capable of encoding the entire Unicode repertoire. The encoding maps character to a sequence of 16 bit words. Characters are known as code points and 16 bit words are known as code units. The basic characters from the Basic Multilingual Plane’ can be represented using the 16 bits. For characters outside this we need to use a pair of 16 bit words called as the surrogate pair. Thus all the characters that can be encoded by 232 or U+0000 through U+10FFFF , except for U+D800–U+DFFF (These are not assigned any characters) can be specified using UTF-16. Why are these numbers not assigned any characters? It is an intelligent choice made by the Unicode community to design the UTF-16 encoding scheme.

The characters outside the BMP (those from U+10000 through U+10FFFF) are represented using a pair of 16 bit words as I said before. These pair is known as surrogate pair. Now 1000016 is subtracted from the original code point to make it a 20 bit number. Now it is divided to two 10 bit numbers each of which is loaded into a surrogate with the higher order bits in the first. the two surrogates will be in the range 0xD800–0xDBFF and 0xDC00-0xDFFF. Thus since we have left out those region unassigned we can be sure it isn’t a character but need processing before the original code point is found out.  You can read the UTF-16 specification from Sun here.

add to del.icio.us : Add to Blinkslist : add to furl : Digg it : Stumble It! : add to simpy : seed the vine : : : TailRank : post to facebook

Posted in Java | Tagged: , , , , , , | Leave a Comment »

Links to other good tutorials in internet

Posted by crz on July 21, 2009

I believe in the idea of recycling and reuse. It is much more efficient to reuse someone else’s effort than reinventing the wheel. So I’m taking the opportunity in this post to point you to some of the best tutorials and fixes for various issues we may have while using a computer. It’s better this way than just plagiarizing their efforts.

1. Installing Mplayer with GUI and browser plugin.

Posted in Linux, Useful links | Tagged: , , | Leave a Comment »