miercuri, 21 noiembrie 2007

User Authentication With Image Verification

User Authentication With Image Verification

In some cases you may want your loging form to be able to prevent automatic login by a robot ( script ). To achieve this we can create a login form which displays an image showing random numbers. The login form will have an extra input field to enter the values shown.
Take a look at the login form. The numbers shown there will change everytime you refresh the page. Go ahead and try refreshing that page you will see the numbers always change.
Before working on the login form we must take care of the script that create the verification image first. Here is the code :
Example : image-verification/randomImage.phpSource : image-verification/randomImage.phps
// generate 5 digit random number$rand = rand(10000, 99999);
// create the hash for the random number and put it in the session$_SESSION['image_random_value'] = md5($rand);
// create the image$image = imagecreate(60, 30);
// use white as the background image$bgColor = imagecolorallocate ($image, 255, 255, 255);
// the text color is black$textColor = imagecolorallocate ($image, 0, 0, 0);
// write the random numberimagestring ($image, 5, 5, 8, $rand, $textColor); // send several headers to make sure the image is not cached // taken directly from the PHP Manual// Date in the past header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
// always modified header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// HTTP/1.1 header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false);
// HTTP/1.0 header("Pragma: no-cache");
// send the content type header so the image is displayed properlyheader('Content-type: image/jpeg');
// send the image to the browserimagejpeg($image);
// destroy the image to free up the memoryimagedestroy($image);?>
To create a five digit random number we use rand() function and specify that the random number must be between 10000 and 99999. We put the hash value of this random number in the session. This hash value will be used by the login script to check if the entered number is correct.
Next we create a small image, 60 x 30 pixels, using imagecreate(). We set the background color to white ( RGB = 255, 255, 255 ) using imagecolorallocate() function. Note that the first call to imagecolorallocate() will always set the background color for the image. Then we set the text color as black ( RGB = 0, 0, 0 ). Feel free to change the color text to your liking.
To print the random number to the image we use the function imagestring(). In the script above we call this function like this : imagestring ($image, 5, 5, 8, $rand, $textColor);
The first argument passed to this function is the image handler ( $image ). The second one ( 5 ) is the font. You can choose from one to five where one is the smallest font. The third and fourth parameter is the horizontal and vertical coordinate where we will print the image. The top left corner is defined as 0, 0. The last one is the text color which is black as mentioned earlier.
After we got the image ready we can now send it to the browser. But before doing that we must set several headers to make sure that the image is not cached. If the image is cached then the login form will show the same image even if you refresh it. That will cause a problem since the random number is always different.
Finally after everything is set we send the image to the browser using imagejpeg() and to free the memory we use imagedestroy().

The Login Form
The login form is pretty much the same but only have extra field to enter the displayed number.
Example : image-verification/login.phpSource : image-verification/login.phps
Basic Login

User Id
Enter Number

To check if the login information is correct we first check if the entered number is the same one as displayed in the image. To do this we check the hash of the entered number and see if it match the one saved in the session. If the number don't match we just set an error message.
If the number do match we continue checking the given user id and password just like the previous example. If the userid and password combination is correct we set $_SESSION['image_is_logged_in'] to true and move on to the main page
Example : image-verification/login.phpSource : image-verification/login.phps
$errorMessage = '';if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) { // first check if the number submitted is correct $number = $_POST['txtNumber']; if (md5($number) == $_SESSION['image_random_value']) { include 'library/config.php'; include 'library/opendb.php'; $userId = $_POST['txtUserId']; $password = $_POST['txtPassword']; // check if the user id and password combination exist $sql = "SELECT user_id FROM tbl_auth_user WHERE user_id = '$userId' AND user_password = PASSWORD('$password')"; $result = mysql_query($sql) or die('Query failed. ' . mysql_error()); if (mysql_num_rows($result) == 1) { // the user id and password match, // set the session $_SESSION['image_is_logged_in'] = true;
// remove the random value from session $_SESSION['image_random_value'] = ''; // after login we move to the main page header('Location: main.php'); exit; } else { $errorMessage = 'Sorry, wrong user id / password'; } include 'library/closedb.php'; } else { $errorMessage = 'Sorry, wrong number. Please try again'; } }?>
We don't need to discuss about main.php and logout.php since they are the same as previous example except the session name is now called $_SESSION['image_is_logged_in']. So instead of working on those two files let's move on to a more interesting stuff...

Improving The Verification Image
We can improve the verification image in at least two ways. They are :
Using alphanumeric characters as the verification code instead of numbers
Using backgound images
For the first improvement the only thing we need to change is the way we generate the code. Take a look at the code below
Example : image-verification/randomImage2.phpSource : image-verification/randomImage2.phps
// generate the verication code $rand = substr(str_shuffle($alphanum), 0, 5);
// ... no changes after this point?>
We start by defining the characters that we want to use in the verification code. For this example we use upper case alphabet plus numbers. The code is generated using the combination of str_shuffle() and substr() function. Using str_shuffle() we jumble all the characters in $aplhanum and then using substr() we take just the first five characters. The result will look something like "D79ZG". Just run the example and see it for yourself.
The second improvement is by using background images. Maybe you already know this but there are software/scripts that can extract the characters displayed as images. And if the verification image only use plain background color identifying the characters wil be quite easy.
For this reason we will make the verification code displayed on a background image. In this tutorial we will only use four different background images. You can add as many background images as you want in your own code. Here are the background images :
background image #1 :
background image #2 :
background image #3 :
background image #4 :
Note : When you want to create a background image make sure the code will still be readable on them. For instance it's quite hard ( at least for me ) to recognize the code when the code is displayed on image #1 and image #4. Go take a look if you don't believe me.
Here is the code for this second improvement
Example : image-verification/randomImage3.phpSource : image-verification/randomImage3.phps
// generate the verication code $rand = substr(str_shuffle($alphanum), 0, 5);
// choose one of four background images$bgNum = rand(1, 4);$image = imagecreatefromjpeg("background$bgNum.jpg");
$textColor = imagecolorallocate ($image, 0, 0, 0);
// write the code on the background imageimagestring ($image, 5, 5, 8, $rand, $textColor);
// ... no changes after this point?>
After making the verification code we randomly pick one background image. Then we create an image object from the chosen background using imagecreatefromjpeg() and draw the code on the background. The rest of the code is the same as randomImage1.php and randomImage2.php so no need to explain it here.
Okay that is it. The three method of user authentication. Just pick one that fit your application.

E-mail validation

E-mail validation This free JavaScript will validate an email address entered into a form. The examples below will work in any type of file. This script will work in any browser on any platform, even in IE 2.0 on a Macintosh! This script is in use on literally thousands of web sites using our Perl scripts. The check_email function will validate an email address entered by a user in real time and return a false or negative value if the email address is not in a valid format. Copy and paste this function into your document, then follow the instructions below.
Note the 4 in the above regular expression. This used to be 3 before the new domain suffixes were released (.info, .name). However, now that 4 characters are allowed in the suffix, a user could enter name@server.conm and the error would not be detected. Next, you need your form validation script.
Next, in your form, you should have a field that asks a user to enter their e-mail address. You must also include the the onsubmit event handler, which will point to your validation script. The validation script will utilize the check_email function. The beauty of the check_email function is that it can be used over and over again. Below is a simple example of a simple form that asks for two email addresses. Note that the keyword this is passed to the check_form function. It tells the function which form to check.




Copy and paste all three sections of code above into a document (in any order) and you will have working example. Keep reading if you are going to have the JavaScript printed by a cgi script.
CGI scripts will need to escape (preceed with a backslash) any metacharacters contained in the JavaScript so that the CGI script does not think those characters are Perl Syntax. And there are many metacharacters in this JavaScript snippet. Below is the JavaScript you should use if you are going to have the JavaScript printed by a CGI script. Make sense? #!/usr/bin/perl
print qq~Content-Type: text/html\n\n~;
print qq~

Please excuse the small font, we needed to squeeze the code in so that it did not wrap. The only difference between this example and the one above, is that all metacharacters have been escaped with a backslash \. Metacharacters include the following : $ @ \ .

Check Boxes and Radio Buttons

This article describes how to automate Check Boxes, i.e. their production, interrogation, setting and clearing, and describes how to access the values of Radio Buttons.
Check Boxes
A checkbox element has two values: CHECKED=TRUE or CHECKED=FALSE.
The following short script will create 10 like named checkboxes (i.e. box0 through to box9):

It also create four buttons each of which invokes an appropriate function using the onClick event.
The following JavaScript defines the functions used by the onClick events:

The reverse() function cycles through the checkboxes setting the value of each checkbox to the opposite of its original value.
Radio Buttons
The following example shows how to find the value of radio buttons:

Question 0? Yes

Question 1? Yes

Question 2? Yes

Question 3? Yes

Question 4? Yes

Question 5? Yes

Question 6? Yes

Question 7? Yes

Question 8? Yes

Question 9? Yes


Which looks like this:
Question 0? Yes No Question 1? Yes No Question 2? Yes No Question 3? Yes No Question 4? Yes No Question 5? Yes No Question 6? Yes No Question 7? Yes No Question 8? Yes No Question 9? Yes No
yes: no:
Multiple Choice Quiz
Radio Buttons are supposed to work in groups, very much like the old push buttons on transistor radios, where if you pressed a button for one radio station, the original pressed in button popped out. The idea being, there would always only be one button pushed in at any one time.
The way they are grouped together in JavaScript is by identically naming them. Therefore in the above JavaScript code, question 0 has two buttons both named q0. Liked named Radio Buttons are then grouped together in an array of elements.
To determine whether a particular button is pressed the syntax required is: test = document.formName.radioGroupName[indexNumber].checked;
Where radioGroupName is the name used by the group of associated Radio Buttons, and indexNumber, is the array index, i.e. the position within the array.
The value returned to text is true, if the Radio Button is checked, and false if not.
The previous example, checks the values of the each of the 10 groups of Radio Buttons, and then displays the result in the text boxes. It doesn't actually make use of the Radio Buttons value field.
In the following example a simple check is made, comparing the answer chosen against the value of the Radio Button:

Black = WhiteTrue
or False ?
2 + 2 = 4True
or False ?
5 - 3 = 1True
or False ?
7 * 7 = 49True
or False ?
36 / 6 = 5True
or False ?
99 - 33 = 66True
or False ?
33 + 99 = 66True
or False ?
5 + 4 + 3 = 12True
or False ?
6 + 5 + 4 = 13True
or False ?
81 / 9 = 9True
or False ?


Which looks like this:
Black = White
True or False ?
2 + 2 = 4
True or False ?
5 - 3 = 1
True or False ?
7 * 7 = 49
True or False ?
36 / 6 = 5
True or False ?
99 - 33 = 66
True or False ?
33 + 99 = 66
True or False ?
5 + 4 + 3 = 12
True or False ?
6 + 5 + 4 = 13
True or False ?
81 / 9 = 9
True or False ?
Correct: Wrong: Blank:
In this example each of the Radio Buttons has a value associated with it using VALUE, the correct answers have a value of true and the incorrect answers have a value of false.
Note, that these values are text string values, i.e. enclosed within quotes, they are not boolean values, i.e. proper true of false.
When the answers are evaluated, the value property is used to obtain the Radio Buttons value.
In this example, the initial state of the Radio Buttons is not set, i.e. neither of the buttons are checked. As its possible for them to remain unchecked, a simple test is performed to exclude them from the calculation, i.e.: if (yesChoice == noChoice)
This checks that if both of the Radio Buttons within the group are of the same state, i.e. both checked or both unchecked, then ignore them. As its impossible for them both to be checked at any one time, then it is safe to make the assumption, that if this check is true then they are both unchecked.
If this test is untrue, i.e. one or the other of the Radio Buttons is checked, the value of the Radio Buttons are compared with the checked status.
Note, the checked statuses are first converted using the toString() method, this is because their original object type is boolean. Comparing a boolean with a text string will never return the expected answer.
Unlike Check Boxes, it isn't easy to unset a Radio Button once it has been set. Using: document.formName.radioName[indexNumber].checked = false;
does not work. The only way to unset a Radio Button is to reset the form: document.formName.reset();
Unfortunately this has the effect of resetting everything on the form.
One possible work around, is to remember the settings of the form, reset it using the reset() method, and then repair the damage - difficult, but not impossible.

sâmbătă, 10 noiembrie 2007


Un bancher evreu isi insoara baiatul. - Simon, fiule, maine zburam la Tel Aviv pentru nunta ta. Imi dau brusc seama ca nu ti-am spus multe lucruri despre viata. De maine vei fi impreuna cu sotia ta, trebuie sa stii unele lucruri. Uite, spre exemplu, cunosti degetele de la mana ? - Sigur, tata, degetul mare, aratator, mijlociu, etc - Nu, fiule, stai sa-ti explic : exista degetul calatoriei, al directiei, al placerii, al casatoriei si al distinctiei. - Ah, nu stiam asta, tata. - Degetul calatoriei este degetul mare, care iti permite sa faci autostopul ; degetul directiei – indexul -, il intinzi casa indici un anumit lucru ; degetul casatoriei – inelarul -, pe care pui verigheta, iar degetul distinctiei – cel mic – pe care-l ridici cand bei cafea. - Am inteles, tata, dar ai uitat degetul placerii. - Ah, Simon, l-am lasat pe cel mai bun la sfarsit… degetul placerii este degetul mijlociu, cel mai lung si mai frumos… pentru placere, fiule… il umezesti cu limba… si numeri bancnotele. Cei care s-au gandit la altceva, in genunchi si sa recite 4 Ave Maria :)

Scrisoare catre generatia noastra

Nascuti la inceputul anilor 60- 70-80, vedem acum in anul 2006 cum casa parintilor nostri este de 50 de ori mai scumpa decat atunci cand aucumparat-o si realizam ca noi o sa platim pentru casele noastre in jur de 50 de ani. Nu avem amintiri despre primii pasi pe luna, nici despre razboaiesangeroase, dar avem cultura generala, pentru ca asta insemna ceva o data.Suntem ultima generatie care a jucat "Ascunselea", "Castel", "Ratele si vanatorii", "Tara, tara! vrem ostasi", "Prinsea", "Sticluta cu otrava", "Pac Pac", "Hotii si vardistii", ultimii care au strigat "Un doi trei la perete stai", ultimii care au folosit telefoanele cu fise, dar primii care am facut petreceri video (inchiriam un video si stateam sa ne uitam la filme 2 zile inchisi in casa) primii care am vazut desene animate color, primii care am renuntat la casete audio si le-am inlocuit cu cd-uri.Noi am purtat jeansi elastici, pantaloni evazati, geci de blugi de la turci, iar cine avea firme gen Lee sau Puma era deja lider de gasca.Noi nu am dat examene de Capacitate, nu am dat teste grile la admitere. Noi am fost ultimii "Soimi ai Patriei" si ultimii "Pioneri".La gradinita am invatat poezii in romaneste, nu in engleza... Si am cantat MULTI ANI TRAIASCA nu HAPPY BIRTHDAY la aniversari.
Am sorbit din ochi Sclava Isaura, Beverly Hills , Melrose Place , Twin Peaks, Dallas .. si cine zice ca nu s-a uitat ori minte ori nu avea inca televizor.Reclamele de pe posturile straine ne innebuneau, si abia asteptam sa vina si la noi> inghetata Magnum, sau pustile alea absolut superbe cu apa.Intre timp, ne consolam cu Tango cu vanilie si ciocolata si clasicele bidoane umplute cu apa de la robinet, care turnate in cap ne provocau pneumonii.
Si uite un motiv bun sa nu mergem la scoala.
Noi am ascultat si Metallica, si Ace of Base, si DJ Bobo, si Michael Jackson, si Backstreet Boys, si Take That, si inca nu auzisem de manele, singurele melodii de joc fiind horele la chefuri, la care nimeni nu stia pasii, dar toti dansam! Dar spre deosebire de copiii din ziua de azi, am auzit atatde Abba, si de Queen, cat si de noile nume gen 50 Cent si Britney Spears.
Am citit "Licurici", "Pif", Ciresarii, si am baut Cico si Zmeurata si ni s-a parut ceva extraordinar cand au aparut primele sucuri "de la TEC" fara sa nefie teama ca "au prea multe E-uri", iar la scoala beam toata clasa dintr-o sticla de suc fara teama de virusi.Noi am baut prima Coca-Cola la sticla si am descoperit internetul.Noi nu ne dadeam bip-uri, ne fluieram sa iesim afara, noi nu aveam dolby surround system, taceam toti ca sa auzim actiunea filmului, nu aveamNintendo sau Playstation ci jocuri tetris de care ne plictiseam la o luna dupa ce le cumparam si le uitam pe dulap, pline de praf. Abia asteptam la chefuri sa jucam "Fantanita", sau "Flori, fete sau baieti", sau "Adevar sau provocare", sau orice ne dadea un pretext sa "pupam pe gura" pe cine "iubeam".
Noi suntem cei care inca au mai "cerut prietenia", care inca roseam la cuvantul "sex", care dadeam cu banul care sa intre in farmacie sa cumpereprezervative, pe care apoi sa le umplem cu apa si sa le aruncam in capul colegilor, care am completat mii de oracole, sperand ca persoana iubita va citi acolo unde scrie "De cine iti place?" ca ne place de el/ea.Este uimitor ca inca mai suntem in viata, pentru ca noi am mers cu bicicleta fara casca, genunchiere si cotiere, nu am avut scaune speciale in masini, nu am aruncat la gunoi bomboanele care ne cadeau din greseala pe jos, nu am avut pastile cu capac special sa nu fie desfacute de copii, nu ne-am spalat pemaini dupa ce ne-am jucat cu toti cainii si toate pisicile din cartier, nu am tinut cont de cate lipide si glucide mancam, parintii nostri nu au "child proof the house", ne-au trimis sa cumparam bere si vin de la alimentara, si cate un pachet de tigari de la tutungerie.
Noi am auzit cum s-a tras la Revolutie, noi am fost martorii a treischimbari de bancnote si monede, noi am ras la bancuri cu Bula, noi am fost primii care au auzit-o pe Andreea Esca la Pro TV, noi suntem cei care mai tinem minte emisiunea "Feriti-va de magarus".
Suntem o generatie de invingatori, de visatori, de "first-timers"...
Daca citesti si ai cazut macar un pic pe ganduri, esti de-al nostru!


Folosirea eronata a prezervativului poate duce la rani usoare


- Mai Ioane, de ce te-ai insurat? - Pentru ca nu-mi placea mancarea gatita de mine. - Si acum cum e? - Acum imi place!

Pe o banca, in parc, doi indragostiti se imbratiseaza. La un moment dat,langa ei se asaza un domn, care o fixeaza cu privirea pe femeie. In cele din urma, partenerul ei nu mai suporta si izbucneste: - N-am mai pomenit atata obraznicie ! - Regret, nu vreau sa va deranjez, dar trebuie sa-i cer nevestei cheia de la casa!

Doua vecine se intalnesc dimineata. - Ce-i cu tine, draga, esti bolnava? - Nu, de ce intrebi? -Am vazut azi dimineata doctorul iesind din apartamentul tau - Si ce? De la tine au iesit trei soldati. Te-am intrebat daca a izbucnit razboiul?

La inmormantarea unui cardiolog. Sicriul in forma de inima este asezat intr-o groapa in forma de inima, pe care sunt puse coroane in forma de inima, pe o muzica divina.
Un om incepe sa rada. - De ce razi, esti nesimtit? Cum poti sa razi lainmormantarea unui asemenea om? - Rad, omule. Ma gandesc la inmormantarea mea, ca sunt ginecolog.


In anii '30 Bucurestiul avea cate putin din toate lucrurile bune specifice fiecarui mare oras din Europa. De ce sa nu fie asa si acum? Cred ca ar trebui sa incepem prin abonamente ca cel de mai sus :)

Bancuri englezesti

An English family was shopping when the young son picked up a Scotland football shirt and said to his sister,
- I've decided to be a Scotland supporter. I want this shirt for my birthday. His sister was outraged, whacked him upside the head, and screamed,
- Talk to your mother!" The little lad took the blue football shirt to his mom.
- Mum, I've decided to be a Scotland supporter. I want this shirt for my birthday. His mother was outraged, whacked him upside the head, and shouted,
- Talk to your father!" So he did.
- Dad, I've decided to be a Scotland supporter. I want this shirt for my birthday. His father is outraged and whacked his son upside the head, bellowing,
- No son of mine will ever be seen in that!. An hour later, as they were driving home, his father said sternly,
- Son, I hope you've learned your lesson today.The boy replied,
- Yes, father, I have.
- Good. What did you learn? The son replied,
- I've only been a Scotland supporter for an hour and I already hate you English bastards

In 2019, Rory John Gates asked his father, Bill Gates III,
- Daddy, I'm 20 years old and I've never had sex. What can I do? Bill replied,
- Simple, son. Take the biggest car from our garage, wear your best suit, give her a big bouquet of exotic flowers, take her to the most expensive restaurant in town, buy her the best Champagne, rent a horse-drawn carriage for a trip around the lake, and end up at the presidential suite of the most expensive hotel in town. She'll be all yours. Rory was shocked.
- But, Dad? What about flirting, romantic walks, gazing into each other's eyes, and reading poetry in the moonlight? Bill scoffed,
- Son, all that stuff was invented by the Open Source community so that they could have sex for free!"

Greierele si furnica

Primavara. Furnica sapa, pune seminte, face straturi. Apare sigreierele. - Ce faci, greierasule? - Merg la un tenis cu baietii. - Mai, mai! Sa nu vii la iarna sa-mi ceri mancare, ca nu stiu ce-ti fac! - Da, da, bine....

Vara. Furnica aduna, secera, coseste. Trece greierele, cu o chitara sub brat. - Ce faci, ma? - Ma duc sa cant cu baietii in parc. - Sa nu uiti: de la mine sa nu ceri de mancare.

Toamna. Furnica culegea de zor, facea dulceturi, punea conserve. Trece greierul, tot cu chitara sub brat. - Ce faci, ma? - Ma duc sa cant cu baietii in bar. - Bine, ma, da' la munca nu vii pana la iarna?

Vine iarna. Furnica statea in pridvor, infofolita intr-un sal si cu un ceai fierbinte in mana, cand vede o limuzina. Din ea coboara greierasul. - Ce faci, greierasule? - Uite, ma duc la Paris sa cant. Am avut succes cu chitara. - Bine, greierasule, bafta. Si daca-l vezi pe unu', Toparceanu, zi-ica-mi bag picioarele in fabulele lui!