Making graphic verification code based on GD Library in PHP

Posted by ishboo on Wed, 09 Feb 2022 05:25:55 +0100

I'm a sophomore student. The purpose of writing this article is to make a certain record of my knowledge and technology, and I'm willing to share it with you. Because of my shallow qualifications and limited ability, there are inevitably some mistakes and omissions in this article. Please also read this article for forgiveness and correction. If you have any questions during reading, you can also ask them through comments. I will answer the questions according to my ability.

 

preface

 

Function of verification code: the function of verification code on the website is to protect the website security. Generally, websites should use verification code to prevent large-scale registration of machines, violent cracking of data passwords and other hazards. The SMS and voice verification code of the mobile phone is to make sure that the mobile phone is the user's own. In fact, the final purpose is to verify that this operation is done by individuals rather than machines, which proves that I am my process. Next, we will generate a graphic verification code through the GD Library of PHP.

Requirements for skill reserve before making graphic verification code: have a certain understanding of php and html syntax.

 

1. Open the GD library extension of PHP

 

Before using GD library to make verification code, you need to open the GD library extension of PHP. We can use phpinfo(); Function to check whether your PHP has enabled the GD library extension (as follows)

 

Then we visit in the browser http://localhost/info.php You can view the following interface

 

Press the shortcut key ctrl+f provided by the browser to search gd, as follows:

 

The search result is as above, that is, your php has enabled the GD library extension. If there is no information shown above, it means that the GD Library of php has not been enabled. We need to manually open the GD library extension.

Find the PHP installation directory. I use the NMP integrated environment. The corresponding directory is D:\Visual-NMP-x64\Bin\PHP\php-7.0.13-nts-Win32-VC14-x64 (the path is for reference only).

After finding the installation directory, we can find the php configuration file php Ini (as shown below)

 

 

Open php INI file, find php_gd2.dll, put the semicolon ";" before the line Remove, indicating that you want to open the GD Library of php. (as shown below)

 


 

2. Make front page

 

Since we are only testing the production of graphic verification code, we can make it simple for the front-end page.

The front page is divided into home page index PHP, and alert PHP two pages, the page code can refer to the following code.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Index</title>
  <style>
    form {
      position: absolute;
      text-align: center;
      width: 160px;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    input {
      width: 160px;
    }
    h4 {
      color: deepskyblue;
    }
    #submit {
      border-radius: 5px;
      color: white;
      width: 160px;
      height: 30px;
      font-weight: bold;
      background: deepskyblue;
    }
    img {
      width: 160px;
      height: 30px;
      border: 1px solid gray;
    }
</style>
</head>
<body>
<form method="post" action="check.php">
  <h4>Ascend&nbsp;&nbsp;record&nbsp;&nbsp;page&nbsp;&nbsp;noodles</h4>
  <input name="username" type="text" placeholder="user name"/>
  <br/><br/>
  <input name="password" type="password" placeholder="password"/>
  <br/><br/>
  <input name="captcha" type="text" placeholder="Verification Code"/>
  <br/><br/>
  <img src="captcha.php">
  <br/><br/>
  <input id="submit" type="submit" value="Sign in">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Tips</title>
</head>
<body>
<script>
  alert("<?php echo $_GET['msg'] ?>");
  history.back();
</script>
</body>
</html>

visit http://localhost/ , we can see the effect of the front page as follows

 

 

3. Introduction to main functions

imagecreatetruecolor();          // Generate canvas function imagecolorallocate()// Set the background color function imagefill()// Picture filling function imagesetpixel()// The function of generating point graph imageline()// Function header ('content type: image. png ') for generating line graphics// Set the image output format to pngimagepng($image)// Output the image imagedestroy($image) in png format// Destroy pictures

 

4. Start making verification code

 

① : create captcha PHP file is used to generate verification code pictures

② : create canvas

<?php
// Create a canvas with a width of 160px and a height of 30px
$image = imagecreatetruecolor(160, 30);
// Set the background color to white
$bg_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image,0,0,$bg_color);
​
//Output in png format
header('content-type:image.png');
imagepng($image);
​
// Destroy pictures
imagedestroy($image);
?>

visit http://localhost/ , we can see that the page has generated an all white verification code image

③ : next, we need to add verification code information to the blank verification code picture. The code is as follows:

<?php
​
// Create a canvas with a width of 160px and a height of 30px
$image = imagecreatetruecolor(160, 30);
// Set the background color to white
$bg_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image,0,0,$bg_color);
​
// Alphanumeric mixed verification code
for($i = 0; $i < 4; $i++) {
    $font_size = 10;
    $font_color = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));
    $data = 'abcdefghijklmnopqrstuvwxyz1234567890';// Verification code dictionary
    $font_content = substr($data, rand(0, strlen($data)), 1);
    $x = ($i * 160 / 4) + rand(5, 10);
    $y = rand(5, 10);
    imagestring($image, $font_size, $x, $y, $font_content, $font_color);
}
​
// Output in png format
header('content-type:image.png');
imagepng($image);
​
// Destroy pictures
imagedestroy($image);
​
?>

visit http://localhost/ , the verification code information of four letters and numbers has appeared on the blank canvas.

④ : we also need to add the following interference factors to the verification code (reduce the success probability of machine identification verification code), and first add tens of dots with different colors (the code is as follows)

<?php
​
// Create a canvas with a width of 160px and a height of 30px
$image = imagecreatetruecolor(160, 30);
// Set the background color to white
$bg_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image,0,0,$bg_color);
​
// Alphanumeric mixed verification code
for($i = 0; $i < 4; $i++) {
    $font_size = 10;
    $font_color = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));
    $data = 'abcdefghijklmnopqrstuvwxyz1234567890';// Verification code dictionary
    $font_content = substr($data, rand(0, strlen($data)), 1);
    $x = ($i * 160 / 4) + rand(5, 10);
    $y = rand(5, 10);
    imagestring($image, $font_size, $x, $y, $font_content, $font_color);
}
​
// Add interference points
for($i = 0 ; $i < 200; $i++){
    $point_color = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
    imagesetpixel($image, rand(1, 159), rand(1, 29), $point_color);//
}
​
// Output in png format
header('content-type:image.png');
imagepng($image);
​
// Destroy pictures
imagedestroy($image);
?>

visit http://localhost/ , on the basis of the original verification code picture, many interference points are added

⑤ : in order to further reduce the success probability of machine identification verification code, finally, we add several interference lines. The code is as follows

<?php
​
// Create a canvas with a width of 160px and a height of 30px
$image = imagecreatetruecolor(160, 30);
// Set the background color to white
$bg_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image,0,0,$bg_color);
​
// Alphanumeric mixed verification code
for($i = 0; $i < 4; $i++) {
    $font_size = 10;
    $font_color = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));
    $data = 'abcdefghijklmnopqrstuvwxyz1234567890';// Verification code dictionary
    $font_content = substr($data, rand(0, strlen($data)), 1);
    $x = ($i * 160 / 4) + rand(5, 10);
    $y = rand(5, 10);
    imagestring($image, $font_size, $x, $y, $font_content, $font_color);
}
​
// Add interference points
for($i = 0 ; $i < 200; $i++){
    $point_color = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
    imagesetpixel($image, rand(1, 159), rand(1, 29), $point_color);//
}
​
// Add interference line
for($i = 0; $i < 3; $i++){
    $line_color = imagecolorallocate($image, rand(80, 280), rand(80, 220), rand(80, 220));
    imageline($image, rand(1, 159), rand(1, 29), rand(1, 99), rand(1, 29), $line_color);
}
​
// Output in png format
header('content-type:image.png');
imagepng($image);
​
// Destroy pictures
imagedestroy($image);
​
?>

visit http://localhost/ , the verification code image has become the pattern we want

 

So far, our verification code picture has been improved, but we haven't thought about the judgment of verification code information. We need to use a global variable to save the verification code information, and then use this global variable and the verification code information entered by the user for judgment. What are the global variables in the browser? We can use session to save our variables. When we need to verify with the verification code entered by the user, we can take the matching variables from the session.

 

⑥ For this, we're on our captcha Modify the PHP code as follows:

<?php
​
session_start();// Open session
​
// Create a canvas with a width of 160px and a height of 30px
$image = imagecreatetruecolor(160, 30);
// Set the background color to white
$bg_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image,0,0,$bg_color);
​
$captcha='';// Store verification code
​
// Alphanumeric mixed verification code
for($i = 0; $i < 4; $i++) {
    $font_size = 10;
    $font_color = imagecolorallocate($image, rand(0, 120), rand(0, 120), rand(0, 120));
    $data = 'abcdefghijklmnopqrstuvwxyz1234567890';
    $font_content = substr($data, rand(0, strlen($data)), 1);
    $captcha.=$font_content;
    $x = ($i * 160 / 4) + rand(5, 10);
    $y = rand(5, 10);
    imagestring($image, $font_size, $x, $y, $font_content, $font_color);
}
​
// Use session to save the verification code information for subsequent verification
$_SESSION['captcha']=$captcha;
​
// Add interference points
for($i = 0 ; $i < 200; $i++){
    $point_color = imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
    imagesetpixel($image, rand(1, 159), rand(1, 29), $point_color);//
}
​
// Add interference line
for($i = 0; $i < 3; $i++){
    $line_color = imagecolorallocate($image, rand(80, 280), rand(80, 220), rand(80, 220));
    imageline($image, rand(1, 159), rand(1, 29), rand(1, 99), rand(1, 29), $line_color);
}
​
// Output in png format
header('content-type:image.png');
imagepng($image);
​
// Destroy pictures
imagedestroy($image);
​
?>

 

So far, captcha The code for generating verification code from PHP file has been improved.

 

 4. Background verification

 

Create check The PHP file is verified by background logical processing (the user name and password use the fixed test: 123456), and the code is as follows:

<?php
​
session_start();// Open session
​
$db_username = "test";
$db_password = "123456";
​
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$captcha = $_REQUEST['captcha'];
​
if ($username == "" || $password == "") {
    header('location:alert.php?msg=User name and password cannot be empty');
    exit();
}
if ($captcha == "") {
    header('location:alert.php?msg=Verification code cannot be empty');
    exit();
}
if ($captcha != $_SESSION['captcha']) {
    header('location:alert.php?msg=Verification code error');
    exit();
}
if ($db_username == $username && $db_password == $password) {
    header('location:alert.php?msg=Login successful');
    exit();
}
header('location:alert.php?msg=Login failed');
?>

 

5. Test

 

visit http://localhost/ , start the test.

You can see that the content of the verification code is "6d9o". At this time, we enter test in the user name and 123456 in the password. The verification code is empty. After clicking login, we will get the following prompt ("the verification code cannot be empty").

 

 

Next, enter the wrong verification code

Click login and get a prompt ("verification code error").

 

 

Enter the correct verification code and click login

Get a prompt ("login succeeded").

 

summary

 

I believe that for those who have a basic understanding of php and html syntax, this technology should be well understood, and I hope this article will be helpful to you. If there are mistakes and omissions in the article, please correct them.

 

👇 Scan QR code attention

Topics: PHP