PHP验证码刷新完整实例
PHP验证码实例的学习,一个简单进行 JS 进行刷新的PHP验证码,共有三个文件实现的简单PHP验证码刷新实例,可以完整的应用到注册或登陆等系统中。
index.php 是页面的主程序,主要验证验证码的正确与否,可以验证输出,按照这个方法可以应用到ph程序当中。
yzm.js 验证码 JS 的刷新文件,主要实现无刷新页面功能。
yzm.php 这个就是验证码的实例文件了。。
其实这三个文件在使用的时候可以整合成为一个文件的,通常情况下都是 一个验证文件(index.php),一个验证码的单独文件(yzm.php),根据自己的需要修改吧!
index.php 的源码:
<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" src="yzm.js"></script>
</head>
<?php
//验证验证码实例
if(isset($_REQUEST['code'])){
if($_REQUEST['code']==$_SESSION['code']){
echo 'OK';
echo $_REQUEST['code'];
echo '<br>';
echo '上面是接受过来的验证码';
echo '<br>';
echo '下面是保存到SESSION里的验证码';
echo '<br>';
echo $_SESSION['code'];
}else{
echo 'NO';
}
}else{
?>
<body>
<form action="" method="post">
<input type="text" name="code" />
<img src="yzm.php" alt="this is code" id="img" />
<a href="#" name="can not see" id="test">can't see</a>
<br />
<input type="submit" value="OK" />
</form>
<?
}
?>
</body>
</html>
yzm.js 的源码:
// Javascript Document
function test(img){
var src=img.getAttribute("src");
src=src+"?new="+Math.random(0,10);
img.setAttribute("src",src);
}
function prepare(){
var nav=document.getElementById("test");
var name=nav.getAttribute("name");
var str="can not see";
if(name==str){
nav.onclick=function(){
var img=document.getElementById("img");
test(img);
return false;
}
}
}
window.onload=prepare;
yzm.php 的源码:
<?php
session_start();
if(isset($_SESSION['code'])){
unset($_SESSION['code']);
}
?>
<?php
header("Content-Type:image/png");
$img=@imagecreate(90,80)or die("you can't create image ");
$background_color=imagecolorallocate($img,255,255,255);
$text_color=imagecolorallocate($img,255,0,0);
$line_color=imagecolorallocate($img,34,56,78);
imagefilledrectangle($img,10,10,80,70,$line_color);
for($i=0;$i<4;$i++){
$number=rand(0,2);
switch ($number){
case 0:
$randnumber=rand(48,57);break;//this is a dig number;
case 1:
$randnumber=rand(65,90);break;//this is a lower string;
case 2:
$randnumber=rand(97,122);break;//this is a upper stirng;
}
$asciinumber=sprintf("%c",$randnumber);
$lastnumber=$lastnumber.$asciinumber;
}
imagestring($img,5,30,30,$lastnumber,$text_color);
imagepng($img);
imagedestroy($img);
?>
<?php
$_SESSION['code']=$lastnumber;
?>
aaaaaaaaaaaaaaaaaaas你好