code.php:
<?php
$image_w = 100;
$image_h =30;
$image = imagecreate($image_w,$image_h);
$bg_color = imagecreatetruecolor($image,0xcc,0xcc,0xcc);
imagefill($image,0,0,$bg_color);
$code = "";
$count=5;
$charset="ABCDEFGHIGKLMNPQRSTUVWXYZ23456789";
for($i=0;$i<$count;$i++){
$code .= $charset[mt_rand(0,strlen($charset)-1)];
}
$font_style = "./SourceCodePro-Bold.ttf";
for($i=0;$i<$count;$i++){
$color = imagecolorallocate($image,rand(0,255),rand(0,255),rand(0,255));
imagettftext(
$image ,
16,
rand(0,20)-mt_rand(0,25),
16*$i+15,
mt_rand($image_h/2,$image_h),
$color,
$font_style ,
$code[$i]
);
}
//噪点
for($i=0;$i<200;$i++){
$color = imagecolorallocate($image,rand(0,255),rand(0,255),rand(0,255));
imagesetpixel($image,rand(0,$image_w),rand(0,$image_h),$color);
}
//干扰线
for($i=0;$i<5;$i++){
$color = imagecolorallocate($image,rand(0,255),rand(0,255),rand(0,255));
imageline($image,rand(0,$image_w),rand(0,$image_w),rand(0,$image_h),rand(0,$image_h),$color);
}
ob_clean();
header("content-type:image/gif");
imagegif($image);
login.php:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<table border="1" style="width: 300px;height: 200px;background-color: #1a83ff" align="center">
<th bgcolor="aqua">用户登录</th>
<form name="login_form" action="login_do.php" method="post">
<tr><td align="center"><input name="username" type="text" placeholder="用户名" style="height: 30px"></td></tr>
<tr><td align="center"><input name="password" type="password" placeholder="密码" style="height: 30px"></td></tr>
<tr><td align="center"><input name="vercode" type="text" placeholder="验证码" style="height: 30px"></td></tr>
<tr><td align="center"><img src="code.php" id="vercode">
<a href="#" id="change">换一张</a></td></tr>
<td align="center"><input name="login" type="submit" value="登录"style="height: 30px;width: 173px"></td>
</form>
</table>
<script>
document.getElementById('change').onclick=function(){
document.getElementById('vercode').src='code.php?rand='+Math.random();
}
</script>
</body>
</html><?php
login_do.php(连接MySQL):
<?php
header("Content-Type: text/html; charset=utf-8");
$username = $_POST['username'];
$password = $_POST['password'];
if($username==""){
echo "请输入用户名";
}elseif($password==""){
echo "请输入密码";
}else{
connMysql($username,$password);
}
function connMysql($username,$password){
$conn = mysqli_connect("localhost","root","root","php",3306);
$sql = "select * from user where username='$username' and password='$password'";
if(!$conn){
echo "数据库连接失败";
}else{
$query = mysqli_query($conn,$sql);
$result = mysqli_fetch_all($query,MYSQLI_ASSOC);
if($result==null){
echo "用户或密码不正确!";
}else{
echo "登录成功!";
}
}
}