Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- SQL таблица `users` (база `lessons`)
- Код
- CREATE TABLE IF NOT EXISTS `users` (
- `id` bigint(20) NOT NULL AUTO_INCREMENT,
- `login` char(64) NOT NULL,
- `password` char(64) NOT NULL,
- `email` char(64) NOT NULL,
- `ip` char(20) NOT NULL,
- `browser` char(255) NOT NULL,
- `date` datetime NOT NULL,
- `activation` tinyint(1) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
- index.php
- Код
- <html>
- <head>
- <title>Корневая страница сайта</title>
- <link rel="stylesheet" href="style.css">
- </head>
- <body>
- <table class=round width=800 align=center cellspacing=4><tr>
- <td align=center>
- <form action="enter.php" method=POST>
- <input type=text name=login placeholder=Логин >
- <input type=password name=password placeholder=Пароль >
- <input class=button type=submit value=Войти>
- <a href=registration.php>Регистрация</a>
- <a href=passwordrepair.php>Восстановить пароль</a>
- </form></td></tr></table>
- </body>
- </html>
- registration.php
- Код
- <html>
- <head>
- <title>Регистрация</title>
- <script type="text/javascript" src="jquery-1.7.min.js"></script>
- <script type="text/javascript" src="check.js"></script>
- <link rel="stylesheet" href="style.css">
- </head>
- <body onLoad=page_load();>
- <table class=round width=800 align=center cellspacing=4>
- <form action="">
- <tr><td valign=top width=50% align=right><input type=text name=login id=login placeholder=Логин onChange=check_login();></td><td><div id=result_login></div></td></tr>
- <tr><td valign=top width=50% align=right><input type=password name=password id=password placeholder=Пароль onChange=check_password();></td><td><div id=result_password></div></td></tr>
- <tr><td valign=top width=50% align=right><input type=text name=email id=email placeholder=Eail onChange=check_email();></td><td><div id=result_email></div></td></tr>
- <tr><td valign=top width=50% align=right><input type=button value=Регистрация onClick=send();></td><td><div id=result></div></td></tr>
- </form>
- </table>
- </body>
- </html>
- activation.php
- Код
- <?php
- include "functions.php"
- ?>
- <html>
- <head>
- <title>Активация</title>
- <link rel="stylesheet" href="style.css">
- </head>
- <body>
- <table class=round width=800 align=center cellspacing=4>
- <tr><td align=center>
- <?php
- //чистим неактивных
- mysql_query("DELETE FROM users WHERE activation='0' AND UNIX_TIMESTAMP()-UNIX_TIMESTAMP(date)>3600");
- //код активации
- if(isset($_GET['code'])) {$code =$_GET['code']; }
- //если не указали code, то выдаем ошибку
- else{
- print "<font color=#ff0000> <small>код активации не обнаружен</small></font>";
- goto_index();
- exit;
- }
- //id,который нужно активировать
- if (isset($_GET[id])) {$id=$_GET[id];}
- //если не указали id, то выдаем ошибку
- else{
- print "<font color=#ff0000> <small>ID пользователя не обнаружен</small></font>";
- goto_index();
- exit;
- }
- //получаем логин по ID пользователя
- $sql = mysql_fetch_array(mysql_query("SELECT id, login FROM users WHERE id='$id'"));
- $activation = md5($id).md5($sql[login]);//создаем такой же код подтверждения
- //сравниваем полученный из url и сгенерированный код, если равны, то активируем пользователя
- if ($activation==$code){
- mysql_query("UPDATE users SET activation='1' WHERE id='$id'");
- unset($activation);
- print "<font color=#339900> <small>код активации подтвержден</small></font>";
- goto_index();
- exit;
- }
- //если же полученный из url и сгенерированный код не равны, то выдаем ошибку
- else {
- print "<font color=#ff0000> <small>код активации не подтвержден</small></font>";
- goto_index();
- exit;
- }
- ?>
- </td></tr></table>
- </body>
- </html>
- login.php
- Код
- <html>
- <head>
- <title>Авторизация</title>
- <script type="text/javascript" src="jquery-1.7.min.js"></script>
- <script type="text/javascript" src="check.js"></script>
- </head>
- <body>
- <table>
- <form action="enter.php" method=POST>
- <tr><td><input type=text name=login placeholder=Логин ></td>
- <td><input type=password name=password placeholder=Пароль ></td>
- <td><input class=button type=submit value=Войти></td></tr>
- </form>
- </table>
- </body>
- </html>
- logout.php
- Код
- <?
- session_start();
- include "functions.php";
- if(!empty($_GET[login])){
- session_unset();
- session_destroy();
- $_SESSION = array();
- goto_index_quick();
- }
- ?>
- main.php
- Код
- <?
- session_start();
- include "functions.php";
- ?>
- <html>
- <head>
- <title>Главная страница</title>
- <script type="text/javascript" src="hideshow.js"></script>
- <link rel="stylesheet" href="style.css">
- </head>
- <body>
- <table class=round width=800px align=center><tr>
- <td valign=top width=50% align=left>
- <?
- if((!empty($_GET[login]))AND(!empty($_SESSION[login]))AND($_GET[login]==$_SESSION[login])){
- print "<font color=#339900> <small>Доброго времени суток </small><b>$_GET[login]</b></font>";
- $sql = mysql_fetch_array(mysql_query("SELECT activation FROM users WHERE login='$_GET[login]'"));
- if($sql[activation]==0){
- print "<font color=#ff0000> <small>ваш аккаунт еще не активирован. Отключаю...</small></font>";
- goto_index();
- exit;
- }
- }
- else{
- print "<font color=#ff0000> <small>логин и/или сессия не совпадают</small></font>";
- goto_index();
- exit;
- }
- ?>
- </td>
- <td valign=top width=50% align=right><a href="logout.php?login=<?print $_SESSION[login];?>">Выход</a></td>
- </tr></table>
- </body>
- </html>
- passwordrepair.php
- Код
- <html>
- <head>
- <title>Восстановление пароля</title>
- <script type="text/javascript" src="jquery-1.7.min.js"></script>
- <script type="text/javascript" src="check.js"></script>
- <link rel="stylesheet" href="style.css">
- </head>
- <body>
- <table class=round width=800 align=center cellspacing=4>
- <tr><td align=center>
- <form action="">
- <input type=text class=reg_email name=email id=email placeholder="введите eail указаный при регистрации" onChange=test_email();>
- <div id=result_test_email></div>
- </form>
- </td></tr></table>
- </body>
- </html>
- enter.php
- Код
- <?
- session_start();
- include "functions.php";
- ?>
- <html>
- <head>
- <title>Активация</title>
- <link rel="stylesheet" href="style.css">
- </head>
- <body>
- <table class=round width=800 align=center cellspacing=4>
- <tr><td align=center>
- <?php
- $password_md = md5($_POST[password]);
- if((!empty($_POST[login]))AND(!empty($_POST[password]))){
- $sql = mysql_fetch_array(mysql_query("SELECT login, password FROM users WHERE login='$_POST[login]'"));
- if(($sql[login]==$_POST[login])AND($sql[password]==$password_md)){
- //print "<font color=#339900> <small>входим на сайт</small></font>";
- //print "<br><small><font color=#999999>DB логин:</font></small> $sql[login]<br><small><font color=#999999>POST логин:</font></small> $_POST[login]<br><small><font color=#999999>DB пароль:</font></small> $sql[password]<br><small><font color=#999999>POST пароль:</font></small> $password_md";
- $_SESSION[login]=$_POST[login];
- goto_main($_POST[login]);
- }
- else{
- print "<font color=#ff0000> <small>логин и пароль не совпадают</small></font>";
- //print "<br><small><font color=#999999>DB логин:</font></small> $sql[login]<br><small><font color=#999999>POST логин:</font></small> $_POST[login]<br><small><font color=#999999>DB пароль:</font></small> $sql[password]<br><small><font color=#999999>POST пароль:</font></small> $password_md";
- goto_index();
- }
- }else goto_index_quick();
- ?>
- </td></tr></table>
- </body>
- </html>
- check.php
- Код
- <?
- session_start();
- include "functions.php";
- //конвертер utf8 в WINDOWS-1251
- $login = iconv("utf-8","windows-1251",$_POST[login]);
- $password = iconv("utf-8","windows-1251",$_POST[password]);
- $email = iconv("utf-8","windows-1251",$_POST[email]);
- if(!empty($_POST[test_email])){
- //проверка среди пользователей
- $sql = mysql_num_rows(mysql_query("SELECT id FROM users WHERE email='$_POST[test_email]'"));
- if($sql==0){
- if($mode==0) print "<font color=#ff0000> <small>eail не найден</small></font>";
- //$_SESSION[errors]+=1;
- }
- else{
- if($mode==0) print "<font color=#339900> <small>новый пароль отправлен на e-mail</small></font>";
- //генерируем новый пароль
- $chars="qazxswedcvfrtgbnhyujmkiolp1234567890QAZXSWEDCVFRTGBNHYUJMKIOLP";
- $max=10;
- $size=StrLen($chars)-1;
- $password=null;
- while($max--)$password.=$chars[rand(0,$size)];
- //шифруем и обновляем пользователя по email
- mysql_query("UPDATE users SET password='".md5($password)."' WHERE email='$_POST[test_email]'");
- //отправляем сообщение пользователю
- send_new_password($password, $_POST[test_email]);
- goto_index();
- }
- }
- if((!empty($_POST[login]))AND(!empty($_POST[password]))AND(!empty($_POST[email]))){
- check_login($login,1);
- check_password($password,1);
- check_email($email,1);
- if($_SESSION[errors]==0){
- $sql = mysql_query("INSERT INTO users (login,password,email,ip,browser,date) VALUES ('$login', '".md5($password)."', '$email', '".ip()."', '".browser()."', NOW())");
- if($sql=='TRUE'){
- send_activation_code($login, $email);
- print "<font color=#339900> <small>регистрация успешно завершена!</small></font>";
- unset($_SESSION[errors]);
- goto_index();
- }
- }
- else{
- print "<font color=#ff0000> <small>регистрация невозможна</small></font>";
- unset($_SESSION[errors]);
- }
- }
- else{
- if(!empty($_POST[login]))check_login($login,0);
- if(!empty($_POST[password]))check_password($password,0);
- if(!empty($_POST[email]))check_email($email,0);
- }
- ?>
- functions.php
- Код
- <?
- session_start();
- //устанавливаем настройки соединения
- $host=$_SERVER['REMOTE_ADDR'];
- $user='root';
- $login='';
- $base='lessons';
- //подключаемся к серверу
- $sql = mysql_connect ($host, $user, $login);
- if(!$sql){
- exit('Error'.mysql_error());
- }
- //выбираем БД
- mysql_select_db ($base,$sql);
- if(!mysql_select_db ($base,$sql)){
- exit('Error'.mysql_error());
- }
- //при необходимости устанавливаем кодировку запросов cp1251 или utf8
- mysql_query("SET NAMES 'cp1251'");
- //mysql_query("SET NAMES 'utf8'");
- //**********************************************************************************************\
- function goto_index()
- {
- $dir='../lessons/'; //здесь меняем путь к корневой директории с вашим проектом
- $ip=$_SERVER['REMOTE_ADDR']; //здесь меняем ip вашего сервера (на Денвере это 127.0.0.1)
- print "<script>setTimeout('index()', 5000);
- function index(){
- location='http://".$ip."/".$dir."';
- }</script>";
- }
- //**********************************************************************************************\
- function goto_index_quick()
- {
- $dir='../lessons/'; //здесь меняем путь к корневой директории с вашим проектом
- $ip=$_SERVER['REMOTE_ADDR']; //здесь меняем ip вашего сервера (на Денвере это 127.0.0.1)
- print "<script>setTimeout('index()', 0);
- function index(){
- location='http://".$ip."/".$dir."';
- }</script>";
- }
- //**********************************************************************************************\
- function goto_main($login)
- {
- $dir='../lessons/'; //здесь меняем путь к корневой директории с вашим проектом
- $ip=$_SERVER['REMOTE_ADDR']; //здесь меняем ip вашего сервера (на Денвере это 127.0.0.1)
- print "<script>setTimeout('index()', 0);
- function index(){
- location='http://".$ip."/".$dir."main.php?login=$login';
- }</script>";
- }
- //**********************************************************************************************\
- function goto_login()
- {
- $dir='../lessons/'; //здесь меняем путь к корневой директории с вашим проектом
- $ip=$_SERVER['REMOTE_ADDR']; //здесь меняем ip вашего сервера (на Денвере это 127.0.0.1)
- print "<script>setTimeout('index()', 5000);
- function index(){
- location='http://".$ip."/".$dir."login.php';
- }</script>";
- }
- //**********************************************************************************************\
- function check_login($login,$mode)
- {
- //проверка запрещенных символов
- if(!preg_match("/^[А-Яа-я Ёё a-zA-Z0-9]+$/",$login)){
- if($mode==0) print "<font color=#ff0000> <small>логин</small> <b>$login</b> <small>содержит запрещенные символы</small></font>";
- $_SESSION[errors]+=1;
- }
- else{
- //проверка количества символов
- if (strlen ($login)<3 || strlen ($login)>20){
- if($mode==0) print "<font color=#ff0000> <small>логин должен быть от 3 до 20 символов</small></font>";
- $_SESSION[errors]+=1;
- }
- else{
- //проверка среди пользователей
- $sql = mysql_num_rows(mysql_query("SELECT id FROM users WHERE login='$login'"));
- if($sql!=0){
- if($mode==0) print "<font color=#ff0000> <small>логин</small> <b>$login</b> <small>занят</small></font>";
- $_SESSION[errors]+=1;
- }
- else{
- //если все ок, выводим сообщение зеленого цвета
- if($mode==0) print "<font color=#339900> <small>логин</small> <b>$login</b> <small>свободен</small></font>";
- //$_SESSION[errors]=0;
- }
- }
- }
- }
- //**********************************************************************************************\
- function check_password($password,$mode)
- {
- //проверка количества символов
- if (strlen ($password)<8 || strlen ($password)>32){
- if($mode==0) print "<font color=#ff0000> <small>пароль должен быть от 8 до 32 символов</small></font>";
- $_SESSION[errors]+=1;
- }
- else{
- //проверка запрещенных символов
- if(!preg_match("/^[А-Яа-яЁёa-zA-Z0-9]+$/",$password)){
- if($mode==0) print "<font color=#ff0000> <small>пароль содежит недопустимые символы</small></font>";
- $_SESSION[errors]+=1;
- }
- else{
- //если все ок, выводим сообщение зеленого цвета
- if($mode==0) print "<font color=#339900> <small>пароль корректный</small></font>";
- //$_SESSION[errors]=0;
- }
- }
- }
- //**********************************************************************************************\
- function check_email($email,$mode)
- {
- //проверка eail на валидность
- if(!preg_match('/^[_.0-9a-z-]{1,}@[_.0-9a-z-]{1,}.[_.0-9a-z-]{2,}$/',$email)){
- if($mode==0) print "<font color=#ff0000> <small>e-mail:</small> <b>$email</b> <small>некорректный</small></font>";
- $_SESSION[errors]+=1;
- }
- else{
- //проверка среди пользователей
- $sql = mysql_num_rows(mysql_query("SELECT id FROM users WHERE email='$email'"));
- if($sql!=0){
- if($mode==0) print "<font color=#ff0000> <small>пользователь с таким e-mail уже зарегистрирован</small></font>";
- $_SESSION[errors]+=1;
- }
- else{
- //если все ок, выводим сообщение зеленого цвета
- if($mode==0) print "<font color=#339900> <small>e-mail:</small> <b>$email</b> <small>корректный</small></font>";
- //$_SESSION[errors]=0;
- }
- }
- }
- //**********************************************************************************************\
- function ip()
- {
- $ip = $_SERVER['REMOTE_ADDR'];
- return $ip;
- }
- //**********************************************************************************************\
- function browser()
- {
- $browser = strtoupper($_SERVER['HTTP_USER_AGENT']);
- if (strpos($browser, 'MSIE') !== false) { $browser = 'Internet Explorer';}
- else if (strpos($browser, 'FIREFOX') !== false){ $browser = 'Firefox'; }
- else if (strpos($browser, 'KONQUEROR') !== false){ $browser = 'Konqueror'; }
- else if (strpos($browser, 'LYNX') !== false){ $browser = 'Lynx'; }
- else { $browser = $_SERVER['HTTP_USER_AGENT']; }
- return $browser;
- }
- //**********************************************************************************************\
- function send_activation_code($login, $email)
- {
- $sql = mysql_fetch_array(mysql_query ("SELECT id FROM users WHERE login='$login'"));
- $dir='lessons'; //здесь меняем название директории с вашим проектом
- $sender='Администрация Проекта localhost'; //здесь меняем названия отправителя
- $activation = md5($sql[id]).md5($login);
- $subject = "Подтверждение регистрации";
- $message = "Доброго времени суток ".$login."! Спасибо за регистрацию на ".$_SERVER['REMOTE_ADDR']."n
- Перейдите по ссылке, чтобы активировать ваш аккаунт:nhttp://".$_SERVER['REMOTE_ADDR']."/".$dir."/activation.php?id=".$sql[id]."&code=".$activation."n
- С уважением,n ".$sender."";
- mail($email,$subject,$message, "Content-type:text/plain; Charset=windows-1251rn");
- }
- //**********************************************************************************************\
- function send_new_password($password, $email)
- {
- $dir='lessons'; //здесь меняем название директории с вашим проектом
- $sender='Администрация Проекта localhost'; //здесь меняем названия отправителя
- $subject = "Восстановление пароля";
- $message = "Доброго времени суток!n
- Ваш новый пароль: ".$password."n
- С уважением,n ".$sender."";
- mail($email,$subject,$message, "Content-type:text/plain; Charset=windows-1251rn");
- }
- //**********************************************************************************************\
- ?>
- check.js
- Код
- function check_login(){
- var login=$("#login").val()
- $.ajax({
- type: "POST", url: "check.php", data: {login: login},
- success: function(html) {
- $("#result_login").empty();
- $("#result_login").append(html);
- }
- });
- }
- function check_password(){
- var password=$("#password").val()
- $.ajax({
- type: "POST", url: "check.php", data: {password: password},
- success: function(html) {
- $("#result_password").empty();
- $("#result_password").append(html);
- }
- });
- }
- function check_email(){
- var email=$("#email").val()
- $.ajax({
- type: "POST", url: "check.php", data: {email: email},
- success: function(html) {
- $("#result_email").empty();
- $("#result_email").append(html);
- }
- });
- }
- function send(){
- var login = $("#login").val()
- var password = $("#password").val()
- var email = $("#email").val()
- $.ajax({
- type: "POST", url: "check.php", data: {login: login, password: password, email: email},
- success: function(html) {
- $("#result").empty();
- $("#result").append(html);
- }
- });
- }
- function test_email(){
- var email=$("#email").val()
- $.ajax({
- type: "POST", url: "check.php", data: {test_email: email},
- success: function(html) {
- $("#result_test_email").empty();
- $("#result_test_email").append(html);
- }
- });
- }
- function page_load(){
- document.getElementById('result_login').innerHTML = '<small><font color=Silver>логин должен быть от 3 до 20 символов</font></small>';
- document.getElementById('result_password').innerHTML = '<small><font color=Silver>пароль должен быть от 8 до 32 символов</font></small>';
- document.getElementById('result_email').innerHTML = '<small><font color=Silver>eail должен быть рабочим, на него придет код активации</font></small>';
- }
- style.css
- Код
- a:link {color:Blue; text-decoration:none;}
- a:visited {color:Blue; text-decoration:none;}
- a:active {color:Blue; text-decoration:none;}
- a:hover {color:DodgerBlue; text-decoration:none;}
- body, table, div {
- font-family: sans-serif;
- font-size: 11pt;
- vertical-align: baseline;
- }
- input {
- backgroundolor: White;
- border-collapse: separate;
- font-family: sans-serif;
- font-size: 9pt;
- vertical-align: baseline;
- border: 1px solid DarkGray;
- border-radius: 4px;
- width: 130px;
- }
- .button {
- background-color: White;
- border-collapse: separate;
- font-family: sans-serif;
- font-size: 9pt;
- vertical-align: baseline;
- border: 1px solid DarkGray;
- border-radius: 4px;
- width: 60px;
- }
- .reg_email {
- background-color: White;
- border-collapse: separate;
- font-family: sans-serif;
- font-size: 9pt;
- vertical-align: baseline;
- border: 1px solid DarkGray;
- border-radius: 4px;
- width: 300px;
- }
- .round {
- background-color: GhostWhite;
- border-collapse: separate;
- padding: 8px;
- border: 1px solid DarkGray;
- border-radius: 8px;
- boxadow: inset 0 1px 0 rgba(255,255,255,0.5), 0 2px 2px rgba(0,0,0,0.3), 0 0 4px 1px rgba(0,0,0,0.2);
Add Comment
Please, Sign In to add comment