Formulário de login + captcha + ajax ()
Olá pessoal,
estou tentando criar uma formulário de login em PHP com Captcha e Ajax. Usando alguns script baixados na net pude fazer o seguinte:
index.php
<?php
ini_set('session.use_trans_sid', '0');
// Include the random string file
require 'includes/rand.php';
// Begin the session
session_start();
// Set the session contents
$_SESSION['captcha_id'] = $str;
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="[http://www.w3.org/1999/xhtml"](http://www.w3.org/1999/xhtml) xml:lang="en" lang="en">
<head>
<title>AJAX Contact form (with captcha)</title>
<script type="text/javascript" src="captcha.js"></script>
<style type="text/css">
body{
font: 14px 'lucida sans unicode', lucida, helvetica, verdana, arial, sans-serif;
}
img { border: 1px solid #eee; margin-top: 3px; }
fieldset { width:600px; border: dotted 1px #000; margin-left: auto; margin-right: auto; }
fieldset label { display: block; margin: 3px 0px 0 0; }
fieldset h1 { text-align:center; }
fieldset input, textarea { font-family: "Lucida Grande", "Lucida Sans Unicode", Tahoma, Verdana, sans-serif; font-weight:bold; font-size:12px;}
fieldset input { width:300px; }
#refreshmsg{
color: #ccc;
font-size:10px;
}
#submit {
width:100px;
}
#elem{
margin-left:10px;
}
#results{
color:#73A2F9;
}
#desc{
margin-top: 25px;
margin-left: auto; margin-right: auto;
width:600px;
text-align:left;
color:#73A2F9;
}
a:link, a:visited {
color: #000;
text-decoration: underline;
}
a:hover{
text-decoration: none;
}
</style>
</head>
<body>
<form action="process.php" onsubmit="check(); return false;" name="captchaform">
<fieldset>
<div id="elem">
<h1> AJAX Contact form (with captcha) </h1>
<div id="results"></div>
<div id="loading" style="display:none; color:#73A2F9;"><img src="images/ajax-loader.gif" alt="" /><br/><b> Sending the mail...</b><br/><br/></div>
<label for="name">Login:</label> <input type="text" name="login" id="login"/>
<label for="senha">Senha:</label> <input type="password" name="senha" id="senha"/>
<div id="captchaimage"><a href="<?php echo $_SERVER['PHP_SELF']; ?>" onclick="refreshimg(); return false;" title="Click to refresh image"><img src="images/image.jpg?<?php echo time(); ?>" width="132" height="46" alt="Captcha image" /></a>
<div id="refreshmsg">If you cannot crack the captcha, click on the image once to reload a new one.</div></div>
<label for="captcha">Enter the characters as seen on the image above (case insensitive):</label>
<input type="text" maxlength="6" name="captcha" id="captcha" /><div id="captchaerror"></div><br/>
<input type="submit" name="submit" id="submit" value="Login" />
</div>
</fieldset>
</form>
</body>
</html>
process.php
<?php
// Begin the session
session_start();
// To avoid case conflicts, make the input uppercase and check against the session value
// If it's correct, echo '1' as a string
if(strtoupper($_GET['captcha']) == $_SESSION['captcha_id'])
echo '1';
// Else echo '0' as a stringelse
echo '0';
?>mailer.php
<?
####################### Define Important Constants #######################
define('IN_SC', true);
// ############################### Functions ################################
require_once('functions.php');
//sleep(3);
//print_r($_GET);
if (isset($_GET['login'])){
$login = $_GET['login'];
$senha = $_GET['senha'];
$ip = get_ip();
if (empty($login))
{
echo '<font color="#c24949"><b>One or more required fields left blank. Please try again.</b></font><br/>';
}
else
{
// inclui o arquivo de configuração do sistema
include "../config/config_sistema.php";
// recebe dados do formulario de login
$novasenha = md5($senha);
$consulta = "select * from dizimista where login='$login'";
$resultado = mysql_query($consulta) or die("Falha na execucao da consulta");while($linha = mysql_fetch_assoc($resultado)){
$senhabd = $linha["senha"]; //
$loginbd = $linha["login"]; //
$ativo = $linha["ativo"]; //
$nivel = $linha["nivel"]; //
}// fim do while
if($login == $loginbd) {
if($ativo == 0){
echo "<font color='#c24949'><b>Cadastro inativo! Entre em contato com a Pastoral do Dízimo!</font></b><br/>";
exit;
}
// se o login existe verifica a senha dele é válida
elseif($novasenha != $senhabd) {
echo "<font color='#c24949'><b>Senha incorreta!</font></b><br/>";
exit;
}
elseif($nivel == 1){
//verfica se é pastoral, se for transfere ara área específica da pastoral
session_start();
$_SESSION['login_usuario'] = $login;
$_SESSION['senha_usuario'] = $novasenha;
// redireciona o link para uma outra pagina
header("Location: ../restritopastoral/index.php");
}else{
session_start();
$_SESSION['login_usuario'] = $login;
$_SESSION['senha_usuario'] = $novasenha;
// redireciona o link para uma outra pagina
header("Location: ../restrito/index.php");
}
}
else {
echo "<font color='#c24949'><b>O usuario não existe!</font></b><br/>";
exit;
}
mysql_close;
} //fim do senão
}
?>captcha.js
// CREATING THE REQUEST
function createRequestObject()
{
try
{
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert('Sorry, but your browser doesn\'t support XMLHttpRequest.');
}
return xmlhttp;
}
var http = createRequestObject();
var sess = createRequestObject();
// IMAGE REFRESHING
function refreshimg()
{
var url = 'includes/image_req.php';
dorefresh(url, displayimg);
}
function dorefresh(url, callback){
sess.open('POST', 'includes/newsession.php', true);
sess.send(null);
http.open('POST', url, true);
http.onreadystatechange = displayimg;
http.send(null);
}
function displayimg(){
if(http.readyState == 4)
{
var showimage = http.responseText;
document.getElementById('captchaimage').innerHTML = showimage;
}
}
// SUBMISSION
function check()
{
var submission = document.getElementById('captcha').value;
var url = 'includes/process.php?captcha=' + submission;
docheck(url, displaycheck);
}
function docheck(url, callback){
http.open('GET', url, true);
http.onreadystatechange = displaycheck;
http.send(null);
}
//SUBMIT THE FORM, IF THE CAPTCHA IS CORRECT
function submitform(){
var login = document.getElementById("login").value;
var senha = document.getElementById("senha").value;
document.getElementById('loading').style.display = 'block';document.captchaform.submit.disabled = 'true'; //DISABLE THE SUBMIT BUTTON
http.open('GET', 'includes/mailer.php?login=' +login +'&senha=' +senha +'&login='+escape(login));
http.onreadystatechange = printit;
http.send(null);
}//PRINT THE RESPONSE FROM PHP
function printit()
{
if(http.readyState == 4)
{
document.getElementById('loading').style.display = 'none';
document.getElementById('results').innerHTML = http.responseText; //PRINT THE PHP'S RESPONSE IN THE RESULTS DIV
}
}
function displaycheck(){
if(http.readyState == 4)
{
var showcheck = http.responseText;
if(showcheck == '1') //CAPTCHA IS CORRECT
{
document.getElementById('captcha').style.border = '1px solid #49c24f';
document.getElementById('captcha').style.background = '#bcffbf';
document.getElementById('captchaerror').innerHTML = '';
submitform(); //SUBMIT THE FORM
}
if(showcheck == '0')
{
document.getElementById('captcha').style.border = '1px solid #c24949';
document.getElementById('captcha').style.background = '#ffbcbc';
document.captchaform.captcha.value = ''; //RESET THE CAPTCHA INPUT'S VALUE
document.captchaform.captcha.focus(); //CHANGE THE FOCUS TO CAPTCHA INPUT
document.getElementById('captchaerror').innerHTML = '<font color="#c24949"><b>Please Re-enter the CAPTCHA</b></font>';
}
}
}Então, as funções de validação de login, de senha e do CAPTCHA estão funcionando quase que perfeitamente.
Agora tenho um pequeno problema, e como não entendo quase nada de ajax, não conseguir resolver sozinho.
Alguém pode me ajudar?
Quando o login é validado com sucesso junto com o captcha e a senha, é axecutado via PHP oi comando
header("Location: ../restritopastoral/index.php");. No entanto, ao invéz de se abrir esta nova página, ela abre dentro do DIV
<div id="results"></div>. Esta DIV é usada para mostrar resultados de erros de validação, via função printit() e submitform().
Alguém sabe como faço para continuar gerando estas mensagens, mas quando aceitar o login redirecionar para a página correta, mantendo os dados da session?
Obrigado pela ajuda.
Abs
VOM
Discussão (2)
Carregando comentários...