Home >Backend Development >PHP Tutorial >Implementation code of PHP verification code_PHP tutorial

Implementation code of PHP verification code_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:26:091391browse

checkcode.php generates a verification code image, as well as the variable $_SESSION[check_pic].

Copy code The code is as follows:

session_start();
for($i= 0; $i<4; $i++){
$rand.= dechex(rand(1,15));
}
$_SESSION[check_pic]=$rand;
//echo $_SESSION[check_pic];
//Set the image size
$im = imagecreatetruecolor(100,30);
//Set the color
$bg=imagecolorallocate($im,0,0,0 );
$te=imagecolorallocate($im,255,255,255);
//Write the string in the upper left corner of the image
imagestring($im,rand(5,6),rand(25,30) ,5,$rand,$te);
// Output image
header("Content-type:image/jpeg");
imagejpeg($im);
?>

form.php
Call the generated verification code image through
Copy code The code is as follows:


Message


your name
your email
Your website











imagestring($im,rand(5,6),rand(25,30),5,$rand,$te); used int imagestring(int im, int font, int x, int y, string s, int col); function, this function is used to draw horizontal strings.
This function draws a horizontal string on the image. The parameter font is the font, and setting it from 1 to 5 means using the default font. The parameters x and y are the starting point coordinates of the string. The contents of the string are placed on parameter s. Parameter col represents the color of the string.
post.php
Compare $_POST[check] and $_SESSION[check_pic]. If they are equal, perform database insertion. If not equal, return to the previous page.
Copy code The code is as follows:

session_start();
if(isset( $_POST[check]))
{
if($_POST[check] == $_SESSION[check_pic])
{
// echo "Verification code is correct".$_SESSION[check_pic] ;
require("dbinfo.php");
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST[ 'website'];
$content = $_POST['content'];
$date = date("Y-m-d h:m:s");
// Connect to MySQL server
$ connection = mysql_connect ($host, $username, $password);
if (!$connection)
{
die('Not connected : ' . mysql_error());
}
//Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected)
{
die ('Can't use db : ' . mysql_error ());
}
//Insert data into the database
$query = "insert into table (nowamagic_name, nowamagic_email, nowamagic_website, nowamagic_content, nowamagic_date) values ​​('$name','$email', '$website','$content','$date')";
$result = mysql_query($query);
if($result)
{
echo "<script> alert('Submission successful'); history.go(-1);</script>";
}
if (!$result)
{
die('Invalid query: ' . mysql_error());
}
}
else
{
echo "