PHP Verification Code certification process to prevent machine registration

Source: Internet
Author: User
Tags auth hash numeric php script sprintf strlen


This time in writing PHP script, access to the Web front-end and web security issues more, then give us a brief talk about our site verification code verification process and security issues.

From three aspects to talk about the use of verification Code: Verification Code generation, verification process, verification of the security issues noted.

Verification code generation, first of all, to say that the role of verification code. As we all know, the existence of the verification code is to prevent some machines, or to brush malicious messages, unlimited registered users or brute force to crack account passwords. Now the normal verification code is generated by a PHP script, such as opening our Emlog include/lib/folder, there is a checkcode.php, which is the script to generate the CAPTCHA.

We can take a quick look at its code:
Session_Start ();

$randCode = ';
$chars = ' abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPRSTUVWXYZ23456789 ';
for ($i = 0; $i < 5; $i + +) {
$randCode. = substr ($chars, Mt_rand (0, strlen ($chars)-1), 1);
}

$_session[' Code ' = Strtoupper ($randCode);

$img = Imagecreate (70,22);
$bgColor = isset ($_get[' mode ') && $_get[' mode ' = = ' t '? Imagecolorallocate ($img, 245,245,245): Imagecolorallocate ($img, 255,255,255);
$pixColor = Imagecolorallocate ($img, Mt_rand (180), Mt_rand (+), Mt_rand (40, 250));

for ($i = 0; $i < 5; $i + +) {
$x = $i * + mt_rand (0, 4)-2;
$y = Mt_rand (0, 3);
$text _color = imagecolorallocate ($img, Mt_rand (180), Mt_rand (a), Mt_rand (40, 250));
Imagechar ($img, 5, $x + 5, $y + 3, $randCode [$i], $text _color);
}
for ($j = 0; $j < $j + +) {
$x = Mt_rand (0,70);
$y = Mt_rand (0,22);
Imagesetpixel ($img, $x, $y, $pixColor);
}

Header (' content-type:image/png ');
Imagepng ($IMG);
Imagedestroy ($IMG);

The first for loop randomly takes 5 characters in the $chars string, which is actually our real verification code. Then we can see: $_session[' Code ' = Strtoupper ($randCode); He converted our verification code into a capitalize assignment to the session.

Some friends to ask, ask what assignment to the session is not assigned to the cookie. That means you don't know anything about them. Cookies and sessions are used as a "container" for the site to temporarily store information about the client, but cookies are kept in the client, where visitors to the site are free to view and modify the contents of the cookie, so there is no verification code exists. Because the user can read the verification code directly from the cookie, of course the machine can also. And the session is stored on the server content, I generated a good captcha, the user can not read.

Then look at the source, the following two loops are generated in color with the verification code of the picture and in the picture add noise points. is to increase the difficulty of machine recognition verification code. Finally we see that header (' content-type:image/png '); Define our page as the format of the picture.

In this way, we can use the HTML code to let the Captcha show up:


Something like this:
So the validation process is that we first generate 5 random characters to save to the session. Then the 5 characters into a picture to the user to see, let the user identify, fill in the table dropdowns submitted and our session in the verification code.

It's actually that simple.

Finally, the security of the verification code. We emlog and WordPress actually verify code is not very strong, we this simple verification code can write a small script is easy to identify, so it is not suitable for the use of large Web sites. Like Tencent, Baidu, such as the site's verification code many characters can rotate, distort, and the back of the interference on more, even the Chinese verification code. However, for small sites, the normal level of the verification code enough to prevent a lot of brush review of the machine.

It is also important to note that after verifying code is used, you should remember to delete the corresponding session. Otherwise, the verification code loses its meaning, which is the mistake I made before.

Why do you say that? As a normal user, each time we need to fill in the Verification Code of the page, the script to generate the verification code will be executed once, also say will generate a new validation code assignment to the session, there is no problem. But for a machine (or a brute-force password-cracking script), it first accesses the page that needs to be filled in with the verification code, and then gets a CAPTCHA in the session, and it doesn't have to visit the page again. Directly to the first packet changes and send it again, so, if the site does not clear session, each time the verification code and the first time the same, also lost the verification code of the original role.

This is where we need to be aware of our website. I hope everyone in the writing program to pay more attention to the safety of the site, to avoid the site after the release of problems

Through some examples on the net, put together a Verification code landing test program. The detailed code is as follows:

Generate the validator code ttt.php. Generate random numbers by random, then save in session:


Login.htm page


<title>login</title>
<style type= "Text/css" >
<!--
. textbox {
height:18px;
width:100px;
}
. text {
font-size:14px;
Vertical-align:bottom;
Color: #0000FF;
}
. style1 {
font-size:18px;
Color: #0000FF;
font-family: "Young Circle";
}
-->
</style>
<body>
<table width= ">"
&LT;TR&GT;&LT;TD align= "center" valign= "Bottom" class= "Style1" bgcolor= "#C7D3F9" > Please enter Verification code </td>
</tr>
</table>
<form method= "POST" action= "login.php" >
<table width= "border=" 0 "bgcolor=" c7d3f9 ">
<tr>
&LT;TD class= "Text" > Verification Code:</td>
&LT;TD align= "Right" valign= "bottom" ><input type= "text" name= "auth" class= "textbox" ></td>
</tr>
</table>

<table width= "" "><tr><td align=" right "><input type=" button "value=" can not see clearly the verification code "onclick=" Window.location.reload (); " ><input name= "Submit" type= "submit" value= "Submit" ></td></tr></table>
</form>
</body>


login.php

<?php
Session_Start ();
$name = $_post[' user '];
$password = $_post[' passwd '];
$auth = $_post[' auth '];
#require ("db.php");
# $db = new db ();
# $sql = "SELECT * from user where name = ' $name ' and password = ' $password '";
# $result = $db->query ($sql);
if ($_session[' seccode '] = = $auth)
{
#$_session[' user ' = $name;
#$_session[' passwd ' = $password;
# header ("Location:main.php");
#echo ("Login successful!");

$_session[' Seccode ']= ';
print '
<script language=javascript>
Alert ("Login succeeded!") ");
</script> ';
}else
{
print '
<script language=javascript>
Alert ("Login failed, please login again!") ");
Self.window.location= "login.html";
</script> ';
}
?>

Ttt.php Verification Code Generation program

<?php
Session_Start ();

function random ($length, $numeric = 0) {
Mt_srand (Double) microtime () * 1000000);
if ($numeric) {
$hash = sprintf ('%0 '. $length. ' d ', Mt_rand (0, pow ($length)-1));
} else {
$hash = ';
$chars = ' abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz ';
$max = strlen ($chars)-1;
for ($i = 0; $i < $length; $i + +) {
$hash. = $chars [Mt_rand (0, $max)];
}
}
return $hash;
}

#if (Preg_replace ("/https?:\ /\/([^\:\/]+). */i "," \\1 ", $_server[' Http_referer '])!= preg_replace ("/([^\:]+). * "," \\1 ", $_server[' Http_host '])) {
# exit (' Access Denied ');
#}

if ($_get[' Update ']) {
$seccode = Random (4, 1);
//}

#if ($seccode < 1 | | $seccode > 9999) {
# exit (' Access Denied ');
#}

$_session[' seccode ' = $seccode;
$seccode = sprintf ('%04d ', $seccode);

if (! $nocacheheaders) {
@header ("Expires:-1");
@header ("Cache-control:no-store, Private, post-check=0, Pre-check=0, max-age=0", FALSE);
@header ("Pragma:no-cache");
}

if (function_exists (' imagecreate ') && function_exists (' Imagecolorset ') && function_exists (' Imagecopyresized ') && function_exists (' imagecolorallocate ') && function_exists (' Imagesetpixel ') && function_exists (' Imagechar ') && function_exists (' imagecreatefromgif ') && function_exists (' Imagepng ')) {

$im = Imagecreate (62, 25);
$backgroundcolor = Imagecolorallocate ($im, 255, 255, 255);

$numorder = Array (1, 2, 3, 4);
Shuffle ($numorder);
$numorder = Array_flip ($numorder);

 for ($i = 1; $i <= 4; $i + +) {
   $imcodefile = ' seccode/'. $seccode [$numorder [$i]]. GIF ';
   $x = $numorder [$i] * + mt_rand (0, 4)-2;
   $y = Mt_rand (0, 3);
  if (file_exists ($imcodefile)) {
    $imcode = imagecreatefromgif ($imcodefile);
    $data = getimagesize ($imcodefile);
   imagecolorset ($imcode, 0, Mt_rand (m, 255), Mt_rand (128), Mt_rand (50, 255));
   imagecopyresized ($im, $imcode, $x, $y, 0, 0, $data [0] + mt_rand (0, 6)-3, $data [1] + mt_rand (0, 6) -3, $data [0], $data [1]);
  } else {
    $text _color = imagecolorallocate ($im, Mt_rand (255), Mt_rand (50, 128) , Mt_rand (50, 255));
   imagechar ($im, 5, $x + 5, $y + 3, $seccode [$numorder [$i]], $text _color);
  }
 }

$linenums = Mt_rand (10, 32);
for ($i =0; $i <= $linenums; $i + +) {
$linecolor = Imagecolorallocate ($im, Mt_rand (0, 255), Mt_rand (0, 255), Mt_rand (0, 255));
$linex = Mt_rand (0, 62);
$liney = Mt_rand (0, 25);
Imageline ($im, $linex, $liney, $linex + mt_rand (0, 4)-2, $liney + mt_rand (0, 4)-2, $linecolor);
}

for ($i =0; $i <=; $i + +) {
$pointcolor = Imagecolorallocate ($im, Mt_rand (255), Mt_rand (255), Mt_rand (50, 255));
Imagesetpixel ($im, Mt_rand (0), Mt_rand (0), $pointcolor);
}

$bordercolor = Imagecolorallocate ($im, 150, 150, 150);
Imagerectangle ($im, 0, 0,, $bordercolor);

Header (' content-type:image/png ');
Imagepng ($im);
Imagedestroy ($im);

} else {

  $numbers = array
   (
  0 => Array (' 3c ', ' 66 ', ' 66 ', ' 66 ', ' 66 ', ' 66 ', ' 66 ', ' 66 ', ') ' $ ', ' 3c '),
  1 => Array (' 1c ', ' 0c ', ' 0c ', ' 0c ', ' 0c ', ' 0c ', ' 0c ', ' 0c '), ' 1c ', ' 0c '),
  2 = > Array (' 7e ', ' ', ', ', ' ', ', ' 0c ', ' ' 66 ', ' ', ', ', ' 3c ',
  3 => Array (' 3c ', ' ', ' 06 ', ' 06 ', ' ', ' 1c ', ' ', ' ', ' $ ', ' 3c '),
  4 => Array (' 1e ', ' 0c ', ' 7e ', ' 4c ', ' 2c ', ' 2c ', ' 1c ', ' 1c ', ', ' 0c ', ' 0c ')
  5 => Array (' 3c ', ', ', ', ', ', ', ' ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ') ',
  6 => Array 3c ', ' a ', ', ' ", ', ', ' 7c ', '", ', ', ', ' 1c ',
  7 => Array (', ', ', ' ", ', ', ', ' 0c ', ' 0c '), ' ', ' ', ' $ ', ' 7e '),
  8 => Array (' 3c ', ' $ ', ' $ ', ' $ ', ' $ ', ' 3c ', ' $ ', ' $ ', ' $ ', ' 3c '),
   9 => Array (' 0c ', ' ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ')
  );

 for ($i = 0; $i < $i + +) {
  for ($j = 0; $j < 6; $j + +) {
    $a 1 = substr (' 012 ', Mt_rand (0, 2), 1). substr (' 012345 ', Mt_rand (0, 5), 1);
    $a 2 = substr (' 012345 ', Mt_rand (0, 5), 1). substr (' 0123 ', Mt_rand (0, 3), 1);
   mt_rand (0, 1) = = 1 Array_push ($numbers [$i], $a 1): Array_unshift ($numbers [$i], $a 1);
   mt_rand (0, 1) = = 0 Array_push ($numbers [$i], $a 1): Array_unshift ($numbers [$i], $a 2);
  }
 }

  $bitmap = array ();
 for ($i = 0; $i < $i + +) {
  for ($j = 0; $j < 4; $j + +) {
    $n = subst R ($seccode, $j, 1);
    $bytes = $numbers [$n] [$i];
    $a = Mt_rand (0, 14);
   switch ($a) {
    case 1:str_replace (' 9 ', ' 8 ', $bytes); break;
    case 3:str_replace (' C ', ' e ', $bytes); Break
    case 6:str_replace (' 3 ', ' B ', $bytes);
    case 8:str_replace (' 8 ', ' 9 ', $bytes);
    case 0:str_replace (' e ', ' f ', $bytes);
   }
   array_push ($bitmap, $bytes);
  }
 }

for ($i = 0; $i < 8; $i + +) {
$a = substr (' 012 ', Mt_rand (0, 2), 1). substr (' 012345 ', Mt_rand (0, 5), 1);
Array_unshift ($bitmap, $a);
Array_push ($bitmap, $a);
}

$image = Pack (' h* ', ' 424d9e000000000000003e000000280000002000000018000000010001000000 ').
' 0000600000000000000000000000000000000000000000000000ffffff00 '. Implode (', $bitmap) ');

Header (' content-type:image/bmp ');
Echo $image;

}

?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.