Guest User

Untitled

a guest
Jan 14th, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.54 KB | None | 0 0
  1. SQL таблица `users` (база `lessons`)
  2.  
  3. Код
  4. CREATE TABLE IF NOT EXISTS `users` (
  5. `id` bigint(20) NOT NULL AUTO_INCREMENT,
  6. `login` char(64) NOT NULL,
  7. `password` char(64) NOT NULL,
  8. `email` char(64) NOT NULL,
  9. `ip` char(20) NOT NULL,
  10. `browser` char(255) NOT NULL,
  11. `date` datetime NOT NULL,
  12. `activation` tinyint(1) NOT NULL,
  13. PRIMARY KEY (`id`)
  14. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
  15.  
  16.  
  17. index.php
  18.  
  19. Код
  20. <html>
  21. <head>
  22. <title>Корневая страница сайта</title>
  23. <link rel="stylesheet" href="style.css">
  24. </head>
  25. <body>
  26.  
  27. <table class=round width=800 align=center cellspacing=4><tr>
  28. <td align=center>
  29. <form action="enter.php" method=POST>
  30. <input type=text name=login placeholder=Логин >
  31. <input type=password name=password placeholder=Пароль >
  32. <input class=button type=submit value=Войти>
  33. <a href=registration.php>Регистрация</a>
  34. <a href=passwordrepair.php>Восстановить пароль</a>
  35. </form></td></tr></table>
  36.  
  37. </body>
  38. </html>
  39.  
  40.  
  41.  
  42. registration.php
  43.  
  44. Код
  45. <html>
  46. <head>
  47. <title>Регистрация</title>
  48. <script type="text/javascript" src="jquery-1.7.min.js"></script>
  49. <script type="text/javascript" src="check.js"></script>
  50. <link rel="stylesheet" href="style.css">
  51. </head>
  52. <body onLoad=page_load();>
  53.  
  54. <table class=round width=800 align=center cellspacing=4>
  55. <form action="">
  56. <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>
  57. <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>
  58. <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>
  59. <tr><td valign=top width=50% align=right><input type=button value=Регистрация onClick=send();></td><td><div id=result></div></td></tr>
  60. </form>
  61. </table>
  62.  
  63. </body>
  64. </html>
  65.  
  66.  
  67. activation.php
  68.  
  69. Код
  70. <?php
  71. include "functions.php"
  72. ?>
  73. <html>
  74. <head>
  75. <title>Активация</title>
  76. <link rel="stylesheet" href="style.css">
  77. </head>
  78. <body>
  79.  
  80. <table class=round width=800 align=center cellspacing=4>
  81. <tr><td align=center>
  82.  
  83. <?php
  84. //чистим неактивных
  85. mysql_query("DELETE FROM users WHERE activation='0' AND UNIX_TIMESTAMP()-UNIX_TIMESTAMP(date)>3600");
  86. //код активации
  87. if(isset($_GET['code'])) {$code =$_GET['code']; }
  88. //если не указали code, то выдаем ошибку
  89. else{
  90. print "<font color=#ff0000> <small>код активации не обнаружен</small></font>";
  91. goto_index();
  92. exit;
  93. }
  94. //id,который нужно активировать
  95. if (isset($_GET[id])) {$id=$_GET[id];}
  96. //если не указали id, то выдаем ошибку
  97. else{
  98. print "<font color=#ff0000> <small>ID пользователя не обнаружен</small></font>";
  99. goto_index();
  100. exit;
  101. }
  102. //получаем логин по ID пользователя
  103. $sql = mysql_fetch_array(mysql_query("SELECT id, login FROM users WHERE id='$id'"));
  104. $activation = md5($id).md5($sql[login]);//создаем такой же код подтверждения
  105. //сравниваем полученный из url и сгенерированный код, если равны, то активируем пользователя
  106. if ($activation==$code){
  107. mysql_query("UPDATE users SET activation='1' WHERE id='$id'");
  108. unset($activation);
  109. print "<font color=#339900> <small>код активации подтвержден</small></font>";
  110. goto_index();
  111. exit;
  112. }
  113. //если же полученный из url и сгенерированный код не равны, то выдаем ошибку
  114. else {
  115. print "<font color=#ff0000> <small>код активации не подтвержден</small></font>";
  116. goto_index();
  117. exit;
  118. }
  119. ?>
  120. </td></tr></table>
  121.  
  122. </body>
  123. </html>
  124.  
  125.  
  126. login.php
  127.  
  128. Код
  129. <html>
  130. <head>
  131. <title>Авторизация</title>
  132. <script type="text/javascript" src="jquery-1.7.min.js"></script>
  133. <script type="text/javascript" src="check.js"></script>
  134. </head>
  135. <body>
  136.  
  137. <table>
  138. <form action="enter.php" method=POST>
  139. <tr><td><input type=text name=login placeholder=Логин ></td>
  140. <td><input type=password name=password placeholder=Пароль ></td>
  141. <td><input class=button type=submit value=Войти></td></tr>
  142. </form>
  143. </table>
  144.  
  145. </body>
  146. </html>
  147.  
  148.  
  149. logout.php
  150.  
  151. Код
  152. <?
  153. session_start();
  154. include "functions.php";
  155.  
  156. if(!empty($_GET[login])){
  157. session_unset();
  158. session_destroy();
  159. $_SESSION = array();
  160. goto_index_quick();
  161. }
  162. ?>
  163.  
  164.  
  165. main.php
  166.  
  167. Код
  168. <?
  169. session_start();
  170. include "functions.php";
  171. ?>
  172. <html>
  173. <head>
  174. <title>Главная страница</title>
  175. <script type="text/javascript" src="hideshow.js"></script>
  176. <link rel="stylesheet" href="style.css">
  177. </head>
  178. <body>
  179. <table class=round width=800px align=center><tr>
  180. <td valign=top width=50% align=left>
  181. <?
  182. if((!empty($_GET[login]))AND(!empty($_SESSION[login]))AND($_GET[login]==$_SESSION[login])){
  183. print "<font color=#339900> <small>Доброго времени суток </small><b>$_GET[login]</b></font>";
  184. $sql = mysql_fetch_array(mysql_query("SELECT activation FROM users WHERE login='$_GET[login]'"));
  185. if($sql[activation]==0){
  186. print "<font color=#ff0000> <small>ваш аккаунт еще не активирован. Отключаю...</small></font>";
  187. goto_index();
  188. exit;
  189. }
  190. }
  191. else{
  192. print "<font color=#ff0000> <small>логин и/или сессия не совпадают</small></font>";
  193. goto_index();
  194. exit;
  195. }
  196. ?>
  197. </td>
  198. <td valign=top width=50% align=right><a href="logout.php?login=<?print $_SESSION[login];?>">Выход</a></td>
  199. </tr></table>
  200.  
  201. </body>
  202. </html>
  203.  
  204.  
  205. passwordrepair.php
  206.  
  207. Код
  208. <html>
  209. <head>
  210. <title>Восстановление пароля</title>
  211. <script type="text/javascript" src="jquery-1.7.min.js"></script>
  212. <script type="text/javascript" src="check.js"></script>
  213. <link rel="stylesheet" href="style.css">
  214. </head>
  215. <body>
  216.  
  217. <table class=round width=800 align=center cellspacing=4>
  218. <tr><td align=center>
  219. <form action="">
  220. <input type=text class=reg_email name=email id=email placeholder="введите eail указаный при регистрации" onChange=test_email();>
  221. <div id=result_test_email></div>
  222. </form>
  223. </td></tr></table>
  224.  
  225. </body>
  226. </html>
  227.  
  228.  
  229. enter.php
  230.  
  231. Код
  232. <?
  233. session_start();
  234. include "functions.php";
  235. ?>
  236. <html>
  237. <head>
  238. <title>Активация</title>
  239. <link rel="stylesheet" href="style.css">
  240. </head>
  241. <body>
  242.  
  243. <table class=round width=800 align=center cellspacing=4>
  244. <tr><td align=center>
  245.  
  246. <?php
  247. $password_md = md5($_POST[password]);
  248.  
  249. if((!empty($_POST[login]))AND(!empty($_POST[password]))){
  250. $sql = mysql_fetch_array(mysql_query("SELECT login, password FROM users WHERE login='$_POST[login]'"));
  251. if(($sql[login]==$_POST[login])AND($sql[password]==$password_md)){
  252. //print "<font color=#339900> <small>входим на сайт</small></font>";
  253. //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";
  254. $_SESSION[login]=$_POST[login];
  255. goto_main($_POST[login]);
  256. }
  257. else{
  258. print "<font color=#ff0000> <small>логин и пароль не совпадают</small></font>";
  259. //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";
  260. goto_index();
  261. }
  262. }else goto_index_quick();
  263. ?>
  264. </td></tr></table>
  265.  
  266. </body>
  267. </html>
  268.  
  269.  
  270. check.php
  271.  
  272. Код
  273. <?
  274. session_start();
  275. include "functions.php";
  276.  
  277. //конвертер utf8 в WINDOWS-1251
  278. $login = iconv("utf-8","windows-1251",$_POST[login]);
  279. $password = iconv("utf-8","windows-1251",$_POST[password]);
  280. $email = iconv("utf-8","windows-1251",$_POST[email]);
  281.  
  282. if(!empty($_POST[test_email])){
  283. //проверка среди пользователей
  284. $sql = mysql_num_rows(mysql_query("SELECT id FROM users WHERE email='$_POST[test_email]'"));
  285. if($sql==0){
  286. if($mode==0) print "<font color=#ff0000> <small>eail не найден</small></font>";
  287. //$_SESSION[errors]+=1;
  288. }
  289. else{
  290. if($mode==0) print "<font color=#339900> <small>новый пароль отправлен на e-mail</small></font>";
  291. //генерируем новый пароль
  292. $chars="qazxswedcvfrtgbnhyujmkiolp1234567890QAZXSWEDCVFRTGBNHYUJMKIOLP";
  293. $max=10;
  294. $size=StrLen($chars)-1;
  295. $password=null;
  296. while($max--)$password.=$chars[rand(0,$size)];
  297. //шифруем и обновляем пользователя по email
  298. mysql_query("UPDATE users SET password='".md5($password)."' WHERE email='$_POST[test_email]'");
  299. //отправляем сообщение пользователю
  300. send_new_password($password, $_POST[test_email]);
  301. goto_index();
  302. }
  303. }
  304.  
  305. if((!empty($_POST[login]))AND(!empty($_POST[password]))AND(!empty($_POST[email]))){
  306. check_login($login,1);
  307. check_password($password,1);
  308. check_email($email,1);
  309.  
  310. if($_SESSION[errors]==0){
  311. $sql = mysql_query("INSERT INTO users (login,password,email,ip,browser,date) VALUES ('$login', '".md5($password)."', '$email', '".ip()."', '".browser()."', NOW())");
  312. if($sql=='TRUE'){
  313. send_activation_code($login, $email);
  314. print "<font color=#339900> <small>регистрация успешно завершена!</small></font>";
  315. unset($_SESSION[errors]);
  316. goto_index();
  317. }
  318. }
  319. else{
  320. print "<font color=#ff0000> <small>регистрация невозможна</small></font>";
  321. unset($_SESSION[errors]);
  322. }
  323. }
  324. else{
  325. if(!empty($_POST[login]))check_login($login,0);
  326. if(!empty($_POST[password]))check_password($password,0);
  327. if(!empty($_POST[email]))check_email($email,0);
  328. }
  329. ?>
  330.  
  331.  
  332. functions.php
  333.  
  334. Код
  335. <?
  336. session_start();
  337. //устанавливаем настройки соединения
  338. $host=$_SERVER['REMOTE_ADDR'];
  339. $user='root';
  340. $login='';
  341. $base='lessons';
  342. //подключаемся к серверу
  343. $sql = mysql_connect ($host, $user, $login);
  344. if(!$sql){
  345. exit('Error'.mysql_error());
  346. }
  347. //выбираем БД
  348. mysql_select_db ($base,$sql);
  349. if(!mysql_select_db ($base,$sql)){
  350. exit('Error'.mysql_error());
  351. }
  352. //при необходимости устанавливаем кодировку запросов cp1251 или utf8
  353. mysql_query("SET NAMES 'cp1251'");
  354. //mysql_query("SET NAMES 'utf8'");
  355.  
  356. //**********************************************************************************************\
  357. function goto_index()
  358. {
  359. $dir='../lessons/'; //здесь меняем путь к корневой директории с вашим проектом
  360. $ip=$_SERVER['REMOTE_ADDR']; //здесь меняем ip вашего сервера (на Денвере это 127.0.0.1)
  361. print "<script>setTimeout('index()', 5000);
  362. function index(){
  363. location='http://".$ip."/".$dir."';
  364. }</script>";
  365. }
  366. //**********************************************************************************************\
  367. function goto_index_quick()
  368. {
  369. $dir='../lessons/'; //здесь меняем путь к корневой директории с вашим проектом
  370. $ip=$_SERVER['REMOTE_ADDR']; //здесь меняем ip вашего сервера (на Денвере это 127.0.0.1)
  371. print "<script>setTimeout('index()', 0);
  372. function index(){
  373. location='http://".$ip."/".$dir."';
  374. }</script>";
  375. }
  376. //**********************************************************************************************\
  377. function goto_main($login)
  378. {
  379. $dir='../lessons/'; //здесь меняем путь к корневой директории с вашим проектом
  380. $ip=$_SERVER['REMOTE_ADDR']; //здесь меняем ip вашего сервера (на Денвере это 127.0.0.1)
  381. print "<script>setTimeout('index()', 0);
  382. function index(){
  383. location='http://".$ip."/".$dir."main.php?login=$login';
  384. }</script>";
  385. }
  386. //**********************************************************************************************\
  387. function goto_login()
  388. {
  389. $dir='../lessons/'; //здесь меняем путь к корневой директории с вашим проектом
  390. $ip=$_SERVER['REMOTE_ADDR']; //здесь меняем ip вашего сервера (на Денвере это 127.0.0.1)
  391. print "<script>setTimeout('index()', 5000);
  392. function index(){
  393. location='http://".$ip."/".$dir."login.php';
  394. }</script>";
  395. }
  396. //**********************************************************************************************\
  397. function check_login($login,$mode)
  398. {
  399. //проверка запрещенных символов
  400. if(!preg_match("/^[А-Яа-я Ёё a-zA-Z0-9]+$/",$login)){
  401. if($mode==0) print "<font color=#ff0000> <small>логин</small> <b>$login</b> <small>содержит запрещенные символы</small></font>";
  402. $_SESSION[errors]+=1;
  403. }
  404. else{
  405. //проверка количества символов
  406. if (strlen ($login)<3 || strlen ($login)>20){
  407. if($mode==0) print "<font color=#ff0000> <small>логин должен быть от 3 до 20 символов</small></font>";
  408. $_SESSION[errors]+=1;
  409. }
  410. else{
  411. //проверка среди пользователей
  412. $sql = mysql_num_rows(mysql_query("SELECT id FROM users WHERE login='$login'"));
  413. if($sql!=0){
  414. if($mode==0) print "<font color=#ff0000> <small>логин</small> <b>$login</b> <small>занят</small></font>";
  415. $_SESSION[errors]+=1;
  416. }
  417. else{
  418. //если все ок, выводим сообщение зеленого цвета
  419. if($mode==0) print "<font color=#339900> <small>логин</small> <b>$login</b> <small>свободен</small></font>";
  420. //$_SESSION[errors]=0;
  421. }
  422. }
  423. }
  424. }
  425. //**********************************************************************************************\
  426. function check_password($password,$mode)
  427. {
  428. //проверка количества символов
  429. if (strlen ($password)<8 || strlen ($password)>32){
  430. if($mode==0) print "<font color=#ff0000> <small>пароль должен быть от 8 до 32 символов</small></font>";
  431. $_SESSION[errors]+=1;
  432. }
  433. else{
  434. //проверка запрещенных символов
  435. if(!preg_match("/^[А-Яа-яЁёa-zA-Z0-9]+$/",$password)){
  436. if($mode==0) print "<font color=#ff0000> <small>пароль содежит недопустимые символы</small></font>";
  437. $_SESSION[errors]+=1;
  438. }
  439. else{
  440. //если все ок, выводим сообщение зеленого цвета
  441. if($mode==0) print "<font color=#339900> <small>пароль корректный</small></font>";
  442. //$_SESSION[errors]=0;
  443. }
  444. }
  445. }
  446. //**********************************************************************************************\
  447. function check_email($email,$mode)
  448. {
  449. //проверка eail на валидность
  450. if(!preg_match('/^[_.0-9a-z-]{1,}@[_.0-9a-z-]{1,}.[_.0-9a-z-]{2,}$/',$email)){
  451. if($mode==0) print "<font color=#ff0000> <small>e-mail:</small> <b>$email</b> <small>некорректный</small></font>";
  452. $_SESSION[errors]+=1;
  453. }
  454. else{
  455. //проверка среди пользователей
  456. $sql = mysql_num_rows(mysql_query("SELECT id FROM users WHERE email='$email'"));
  457. if($sql!=0){
  458. if($mode==0) print "<font color=#ff0000> <small>пользователь с таким e-mail уже зарегистрирован</small></font>";
  459. $_SESSION[errors]+=1;
  460. }
  461. else{
  462. //если все ок, выводим сообщение зеленого цвета
  463. if($mode==0) print "<font color=#339900> <small>e-mail:</small> <b>$email</b> <small>корректный</small></font>";
  464. //$_SESSION[errors]=0;
  465. }
  466. }
  467. }
  468. //**********************************************************************************************\
  469. function ip()
  470. {
  471. $ip = $_SERVER['REMOTE_ADDR'];
  472. return $ip;
  473. }
  474. //**********************************************************************************************\
  475. function browser()
  476. {
  477. $browser = strtoupper($_SERVER['HTTP_USER_AGENT']);
  478. if (strpos($browser, 'MSIE') !== false) { $browser = 'Internet Explorer';}
  479. else if (strpos($browser, 'FIREFOX') !== false){ $browser = 'Firefox'; }
  480. else if (strpos($browser, 'KONQUEROR') !== false){ $browser = 'Konqueror'; }
  481. else if (strpos($browser, 'LYNX') !== false){ $browser = 'Lynx'; }
  482. else { $browser = $_SERVER['HTTP_USER_AGENT']; }
  483. return $browser;
  484. }
  485. //**********************************************************************************************\
  486. function send_activation_code($login, $email)
  487. {
  488. $sql = mysql_fetch_array(mysql_query ("SELECT id FROM users WHERE login='$login'"));
  489. $dir='lessons'; //здесь меняем название директории с вашим проектом
  490. $sender='Администрация Проекта localhost'; //здесь меняем названия отправителя
  491. $activation = md5($sql[id]).md5($login);
  492. $subject = "Подтверждение регистрации";
  493. $message = "Доброго времени суток ".$login."! Спасибо за регистрацию на ".$_SERVER['REMOTE_ADDR']."n
  494. Перейдите по ссылке, чтобы активировать ваш аккаунт:nhttp://".$_SERVER['REMOTE_ADDR']."/".$dir."/activation.php?id=".$sql[id]."&code=".$activation."n
  495. С уважением,n ".$sender."";
  496. mail($email,$subject,$message, "Content-type:text/plain; Charset=windows-1251rn");
  497. }
  498. //**********************************************************************************************\
  499. function send_new_password($password, $email)
  500. {
  501. $dir='lessons'; //здесь меняем название директории с вашим проектом
  502. $sender='Администрация Проекта localhost'; //здесь меняем названия отправителя
  503. $subject = "Восстановление пароля";
  504. $message = "Доброго времени суток!n
  505. Ваш новый пароль: ".$password."n
  506. С уважением,n ".$sender."";
  507. mail($email,$subject,$message, "Content-type:text/plain; Charset=windows-1251rn");
  508. }
  509. //**********************************************************************************************\
  510. ?>
  511.  
  512.  
  513. check.js
  514.  
  515. Код
  516. function check_login(){
  517. var login=$("#login").val()
  518. $.ajax({
  519. type: "POST", url: "check.php", data: {login: login},
  520. success: function(html) {
  521. $("#result_login").empty();
  522. $("#result_login").append(html);
  523. }
  524. });
  525. }
  526. function check_password(){
  527. var password=$("#password").val()
  528. $.ajax({
  529. type: "POST", url: "check.php", data: {password: password},
  530. success: function(html) {
  531. $("#result_password").empty();
  532. $("#result_password").append(html);
  533. }
  534. });
  535. }
  536. function check_email(){
  537. var email=$("#email").val()
  538. $.ajax({
  539. type: "POST", url: "check.php", data: {email: email},
  540. success: function(html) {
  541. $("#result_email").empty();
  542. $("#result_email").append(html);
  543. }
  544. });
  545. }
  546. function send(){
  547. var login = $("#login").val()
  548. var password = $("#password").val()
  549. var email = $("#email").val()
  550. $.ajax({
  551. type: "POST", url: "check.php", data: {login: login, password: password, email: email},
  552. success: function(html) {
  553. $("#result").empty();
  554. $("#result").append(html);
  555. }
  556. });
  557. }
  558. function test_email(){
  559. var email=$("#email").val()
  560. $.ajax({
  561. type: "POST", url: "check.php", data: {test_email: email},
  562. success: function(html) {
  563. $("#result_test_email").empty();
  564. $("#result_test_email").append(html);
  565. }
  566. });
  567. }
  568. function page_load(){
  569. document.getElementById('result_login').innerHTML = '<small><font color=Silver>логин должен быть от 3 до 20 символов</font></small>';
  570. document.getElementById('result_password').innerHTML = '<small><font color=Silver>пароль должен быть от 8 до 32 символов</font></small>';
  571. document.getElementById('result_email').innerHTML = '<small><font color=Silver>eail должен быть рабочим, на него придет код активации</font></small>';
  572. }
  573.  
  574.  
  575. style.css
  576.  
  577. Код
  578. a:link {color:Blue; text-decoration:none;}
  579. a:visited {color:Blue; text-decoration:none;}
  580. a:active {color:Blue; text-decoration:none;}
  581. a:hover {color:DodgerBlue; text-decoration:none;}
  582.  
  583. body, table, div {
  584. font-family: sans-serif;
  585. font-size: 11pt;
  586. vertical-align: baseline;
  587. }
  588. input {
  589. backgroundolor: White;
  590. border-collapse: separate;
  591. font-family: sans-serif;
  592. font-size: 9pt;
  593. vertical-align: baseline;
  594. border: 1px solid DarkGray;
  595. border-radius: 4px;
  596. width: 130px;
  597. }
  598.  
  599. .button {
  600. background-color: White;
  601. border-collapse: separate;
  602. font-family: sans-serif;
  603. font-size: 9pt;
  604. vertical-align: baseline;
  605. border: 1px solid DarkGray;
  606. border-radius: 4px;
  607. width: 60px;
  608. }
  609. .reg_email {
  610. background-color: White;
  611. border-collapse: separate;
  612. font-family: sans-serif;
  613. font-size: 9pt;
  614. vertical-align: baseline;
  615. border: 1px solid DarkGray;
  616. border-radius: 4px;
  617. width: 300px;
  618. }
  619. .round {
  620. background-color: GhostWhite;
  621. border-collapse: separate;
  622. padding: 8px;
  623. border: 1px solid DarkGray;
  624. border-radius: 8px;
  625. 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