tipoloko 0 Denunciar post Postado Novembro 26, 2008 Salve galera, desenvolvi um script, para cadastro de usuario/cliente/ com envio de email para confirmacao do cadastro. resolvi postar para poder dar uma melhorada no codigo... use e abusem.... qualquer coisa poste aew... segue aew... Dados da tabela -- -- Estrutura da tabela `ativa` -- CREATE TABLE `ativa` ( `id` int(10) unsigned NOT NULL auto_increment, `usuario` varchar(200) default NULL, `senha` varchar(200) default NULL, `ativo` tinyint(1) default NULL, `chave` varchar(200) default NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1; -- index.php <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>:: Cadastro Simples de Usuario ::</title> </head> <body> <form id="form1" name="form1" method="post" action="user_exe.php"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td style="width:100px;">E-Mail</td> <td><label> <input name="user" type="text" id="user" /> </label></td> </tr> <tr> <td>Senha</td> <td><input name="pass" type="password" id="pass" /></td> </tr> <tr> <td> </td> <td><label> <input type="submit" name="Submit" value="[C A D A S T R A R ]" /> </label></td> </tr> </table> </form> </body> </html> conexao.php <?php /** * @author Luciano Azevedo * @email luciano@bysites.com.br * @website www.bysites.com.br * @copyright 2008 */ $host = 'localhost'; $banco = 'seu_banco_de_dados'; $usuario1 = 'root'; $senha = ''; mysql_connect($host,$usuario1,$senha)or die('Não foi possivel efetuar a conexão'); mysql_select_db($banco); ?> funcoes.php <?php /** * @author Luciano Azevedo * @email luciano@bysites.com.br * @website www.bysites.com.br * @copyright 2008 */ function chavekey(){ $chave = ""; $letras = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","r","s","t","u","v","w","x","z"); $num = array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"); for($i=0;$i<58;$i++){ $c = $letras[array_rand($num)]; $x = $num[array_rand($letras)]; $chave .= $c.$x; } return $chave; } function anti($sql){ $sql = preg_replace(sql_regcase("/(from|select|insert|delete|where|drop table|show tables|#|\*|--|\\\\)/"),"",$sql); $sql = trim($sql); $sql = strip_tags($sql); $sql = addslashes($sql); return $sql; } ?> usu_exe.php <?php /** * @author Luciano Azevedo * @email luciano@bysites.com.br * @website www.bysites.com.br * @copyright 2008 */ include_once('conexao.php'); include_once('funcoes.php'); $user = anti($_POST['user']); $pass = anti(md5($_POST['pass'])); $key = chavekey(); $ema = $user; if (!eregi("^[-_a-z0-9]+(\\.[-_a-z0-9]+)*\\@([-a-z0-9]+\\.)*([a-z]{2,4})$", $ema)) { echo "Email inválido: $ema"; exit(); } if($user == "") { echo "Digite um email"; exit(); } if($pass == "") { echo "digite sua senha"; exit(); } $sql = "INSERT INTO ativa VALUES ('null', '$user', '$pass', '0', '$key')"; $nro = mysql_query($sql) or die (mysql_error()); if ($nro >0) { $id = mysql_insert_id(); // funcao para mandar o email para o cadastrante, // funciona em localhost =) // claro configurando certo !!!! require_once('classe.smtpmail.php'); $smtp = new SMTPMAIL(); $smtp->Servidor = 'mail.seusite.com.br'; // menos gmail... $smtp->Autenticado = TRUE; $smtp->Usuario = "seuemail@seusite.com.br"; $smtp->Senha = "suaconta"; $smtp->Codificacao = "UTF-8"; $smtp->EmailDe = 'seuemail@seusite.com.br'; $smtp->EmailDeVisual = 'Luciano Azevedo <luciano@bysites.com.br>'; $smtp->EmailPara = "$user"; $smtp->Assunto = 'Confirmacao Cadastro no Site !!!'; $smtp->Corpo = " <BODY bgColor=#ffffff> <DIV><FONT face=Arial size=2><STRONG>Obrigado por se Registrar em nosso site</STRONG></FONT></DIV> <DIV><FONT face=Arial size=2></FONT> </DIV> <DIV><FONT face=Arial size=2></FONT> </DIV> <DIV><FONT face=Arial size=2><STRONG>para efetivar o seu cadastro, favor clique no link abaixo, <BR>para ativar seu login.</STRONG></FONT></DIV> <DIV><FONT face=Arial size=2></FONT> </DIV> <DIV><FONT face=Arial size=2><A href='http://localhost/ativacao/ativar.php?id=$id&key=$key'>Clique Aqui para Ativar</A></FONT></DIV> <DIV><FONT face=Arial size=2></FONT> </DIV> <DIV><FONT face=Arial size=2>caso o link nao abra copie e cole link no seu navegador:</FONT></DIV> <DIV><FONT face=Arial size=2></FONT> http://localhost/ativacao/ativar.php?id=$id&key=$key</DIV> <DIV><FONT face=Arial size=2></FONT> </DIV> <DIV><FONT face=Arial size=2>Obrigado a Equipe do Site BLABLALBLA</FONT></DIV> <DIV><FONT face=Arial size=2>agrade-se seu cadastro.</FONT></DIV>"; echo 'Cadastro efetuado com sucesso, <br> Favor verificar seu email para concluir seu cadastro.'; $smtp->Enviar(); }else { echo 'nao rolo, algo errado'; } ?> agora vem o code comprido, mas vai aew... classe.smtpmail.php <?php /** * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of California, Berkeley nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Classe de manipulação do protocolo SMTP * @author Bruno Pitteli Gonçalves <scorninpc<at>gmail<dot>com> * @version 0.2 * @license BSD license * * 0.1 * Classe inicial * * 0.2 * Possibilidade de envio de email HTML * * 0.3 * Suporte a varios TOs separados por; * * 0.4 * Suporte à mudança da codificação * */ // Seta o tempo limite para 60 segundos set_time_limit(120); /** * SMTPMAIL * Escrito por Bruno Pitteli Gonçalves <scorninpc()gmail*com> * Classe que trata o protocolo SMTP */ class SMTPMAIL { /** * Variavel que armazena o endereço do servidor de email * @access public */ public $Servidor; /** * Variavel que armazena a porta do servidor de email * @access public */ public $Porta = 25; /** * Variavel que armazena a codificação * @access public */ public $Codificacao = 'ISO-8859-1'; /** * Variavel que armazena se o servidor é autenticado * @access public */ public $Autenticado; /** * Variavel que armazena o usuario do servidor de email, caso autenticado * @access public */ public $Usuario; /** * Variavel que armazena a senha do usuario do servidor de email, caso autenticado * @access public */ public $Senha; /** * Variavel que armazena o email de quem está enviando * @access public */ public $EmailDe; /** * Variavel que armazena o nome+email de quem está enviando, para aparecer no email * @access public */ public $EmailDeVisual; /** * Variavel que armazena o email para quem vai * @access public */ public $EmailPara; /** * Variavel que armazena o nome+email de quem está enviando, para aparecer no email * @access public */ public $EmailParaVisual; /** * Variavel que armazena o assunto do email * @access public */ public $Assunto; /** * Variavel que armazena a senha corpo do email * @access public */ public $Corpo; /** * Vetor que armazena os arquivos para anexo * @access private */ private $Anexos = array(); /** * Variavel que armazena a situação do envio do email * @access private */ private $erros = FALSE; /** * Construtor da classe * @name __construct * @access public */ public function __construct() { } // __construct /** * Método que anexa um arquivo ao vetor * @name anexarArquivo * @param string $path - Caminho do arquivo * @access public */ public function anexarArquivo($path) { $this->Anexos[] = $path; } // anexarArquivo /** * Método que verifica se a classe esta pronta está pronta para o envio de email * @name verificarIntegridade * @access private * @return boolean */ private function verificarIntegridade() { // Verifica as pendencias se o servidor for autenticado if($this->Autenticado === TRUE) { if((empty($this->Usuario)) || (empty($this->Senha))) { $this->erros = TRUE; return FALSE; } } // Verifica se o servidor foi digitado if(empty($this->Servidor)) { $this->erros = TRUE; return FALSE; } // Verifica se os outros parametros são validos if((empty($this->EmailDe)) || (empty($this->EmailPara)) || (empty($this->Assunto)) || (empty($this->Corpo))) { $this->erros = TRUE; return FALSE; } return TRUE; } // verificarIntegridade /** * Método que espera a resposta do servidor * @name esperarResposta * @access private * @param integer $socket - Ponteiro para o socket * @param integer $response - Codigo de resposta OK * @return boolean */ private function esperarResposta($socket, $response) { while (substr($server_response, 3, 1) != ' ') { if (!($server_response = fgets($socket, 256))) { $this->erros = TRUE; return FALSE; } if (!(substr($server_response, 0, 3) == $response)) { $this->erros = TRUE; return FALSE; } // echo '<font color="red">S</font> <- ' . $server_response . '<br />'; } return TRUE; } // esperarResposta /** * Método que envia uma string ao servidor * @name enviaPacote * @access private * @param integer $socket - Ponteiro para o socket * @param integer $data - String contendo as informações à serem enviadas * @return boolean */ private function enviaPacote($socket, $data) { if(!fputs($socket, $data . "\r\n")) { return FALSE; } // echo "<font color=\"blue\">C</font> -> " . $data . "<br />"; return TRUE; } // enviaResposta /** * Método que envia o email * @name Enviar * @access prublic * @return boolean */ function Enviar() { $boundary = md5(date('r', time())); // Verifica se esta pronto para iniciar o envio if(!$this->verificarIntegridade()) { return FALSE; } // Tenta conectar if(!$socket = fsockopen($this->Servidor, $this->Porta, $errno, $errstr, 30)) { $this->erros = TRUE; return FALSE; } // Espera por resposta $this->esperarResposta($socket, "220"); // Se o servidor é autenticado if($this->Autenticado) { $this->enviaPacote($socket, "EHLO " . $this->Servidor); $this->esperarResposta($socket, "250"); $this->enviaPacote($socket, "AUTH LOGIN"); $this->esperarResposta($socket, "334"); $this->enviaPacote($socket, base64_encode($this->Usuario)); $this->esperarResposta($socket, "334"); $this->enviaPacote($socket, base64_encode($this->Senha)); $this->esperarResposta($socket, "235"); } else { $this->enviaPacote($socket, "HELO " . $this->Servidor); $this->esperarResposta($socket, "250"); } // Envia quem está mandando o email $this->enviaPacote($socket, "MAIL FROM: " . $this->EmailDe); $this->esperarResposta($socket, "250"); // Envia quem esta recebendo o email $Emails = explode(';', $this->EmailPara); for($i=0;$i<count($Emails);$i++) { $this->enviaPacote($socket, "RCPT TO: " . $Emails[$i]); $this->esperarResposta($socket, "250"); } // Diz ao servidor que estou pronto para enviar a mensagem $this->enviaPacote($socket, "DATA"); $this->esperarResposta($socket, "354"); // Cabeçalho do email if(strlen($this->EmailDeVisual) == 0) { $this->enviaPacote($socket, "From: " . $this->EmailDe); } else { $this->enviaPacote($socket, "From: " . $this->EmailDeVisual . " <" . $this->EmailDe . ">"); } $To = 'To: '; $Emails = explode(';', $this->EmailPara); for($i=0; $i<count($Emails); $i++) { if(empty($Emails[$i])) { continue; } $To .= $Emails[$i] . ', '; } $To = substr($To, 0, strrpos($To, ',')); $this->enviaPacote($socket, $To); // Mando o assunto do email $this->enviaPacote($socket, "Subject: " . $this->Assunto); // Envia o cabeçalho $this->enviaPacote($socket, "Date: " . date("d M y H:i:s")); $this->enviaPacote($socket, "MIME-Version: 1.0"); $this->enviaPacote($socket, "Content-Type: multipart/mixed; boundary=" . $boundary); $this->enviaPacote($socket, "--" . $boundary); $this->enviaPacote($socket, "Content-Type: text/html; charset=" . $this->Codificacao . "\r\n"); $this->enviaPacote($socket, $this->Corpo); $this->enviaPacote($socket, "\r\n"); // Verifica se existe arquivo para ser enviado junto if(count($this->Anexos) > 0) { for($i=0; $i<count($this->Anexos); $i++) { $info = pathinfo($this->Anexos[$i]); // Pega o tipo para o MIME TYPE strtolower($info['extension']); switch($tipo) { case "jpeg": case "jpg": $Tipo = "image/jpeg"; break; case "gif": $Tipo = "image/gif"; break; case "doc": $Tipo = "application/msword"; break; case "rar": $Tipo = "application/rar"; break; case "zip": $Tipo = "application/zip"; break; case "pdf": $Tipo = "application/pdf"; break; default: $Tipo = "application/octet-stream"; break; } // Envia os cabeçalhos do anexo $this->enviaPacote($socket, "--" . $boundary); $this->enviaPacote($socket, "Content-Type: " . $Tipo . "; name=\"". $info['filename'] . "\""); $this->enviaPacote($socket, "Content-Transfer-Encoding: base64"); $this->enviaPacote($socket, "Content-Disposition: attachment; filename=\"" . $info['filename'] . "\""); $this->enviaPacote($socket, "\r\n"); // Envia o arquivo codificado $this->enviaPacote($socket, base64_encode(file_get_contents($this->Anexos[$i]))); $this->enviaPacote($socket, "\r\n"); } $this->enviaPacote($socket, "--" . $boundary . "--"); } // Avisa o o termino do envio $this->enviaPacote($socket, "\r\n\r\n."); $this->esperarResposta($socket, "250"); // Sai do servidor e fecha o socket $this->enviaPacote($socket, "QUIT"); fclose($socket); // Retorna FALSE se o email não foi enviado if($this->erros == TRUE) { return FALSE; // Ou TRUE se não houve erro } else { return TRUE; } } // Enviar } ?> e o ultimo ativar.php <?php /** * @author Luciano Azevedo * @email luciano@bysites.com.br * @website www.bysites.com.br * @copyright 2008 */ include('conexao.php'); include('funcoes.php'); $id = anti($_GET['id']); $key = anti( $_GET['key']); $sql = "select * from ativa where id = '$id'"; $res = mysql_query($sql); $vet = mysql_fetch_array($res); if ($vet['chave'] != $key ) { echo 'dados incorreto'; } else { $sql = "update ativa set ativo = '1' where id = '$id'"; $num = mysql_query($sql); if ($num >0) { echo 'Cadastro concluido <br /><br />'; echo 'Aguarde voce estará sendo redirecionano a pagina principal <br />'; } else { echo 'nao rolo, algo deu errado.!!'; } } ?> Obrigado ! Compartilhar este post Link para o post Compartilhar em outros sites