Интернет-журнал дачника. Сад и огород своими руками

Код регистрации на php при помощи mysqli. Создаем невероятную простую систему регистрации на PHP и MySQL. Проверка email на валидность с помощью jQuery

На множестве сайтов, которые мы каждый день просматриваем в сети, почти на всех имеется пользовательская регистрация. В том уроке мы пробежимся по основам пользовательского управления, заканчивая простой Областью Участника, которую Вы можете осуществить на своем собственном вебсайте.

Этот урок рассчитан для начинающих изучение php где мы рассмотрим основы управления пользователями.

Шаг-1

Создадим в базе таблицу user в которой, мы будем хранить информацию о пользователях в таблице 4 поля

  • UserID
  • Username
  • Password
  • EmailAddress

Используйте SQL запрос ниже для создания базы данных

CREATE TABLE `users` ( `UserID` INT(25 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `Username` VARCHAR(65 ) NOT NULL , `Password` VARCHAR(32 ) NOT NULL , `EmailAddress` VARCHAR(255 ) NOT NULL ) ;

session_start () ; $dbhost = "localhost" ; // Имя хоста где расположен сервер mysql обычно localhost $dbname = "database" ; // Имя базы данных $dbuser = "username" ; // Имя пользователя базы данных $dbpass = "password" ; // Пароль для доступа к базе данных mysql_connect ($dbhost , $dbuser , $dbpass ) or die ("MySQL Error: " . mysql_error () ) ; mysql_select_db ($dbname ) or die ("MySQL Error: " . mysql_error () ) ; ?>

Этот файл отвечает за подключение к базе данных и будет выводиться на всех страницах. Рассмотрим строки кода более подробно

session_start();

Эта функция начинает сессию для нового пользователя, далее в ней мы будем хранить данные о ходе сессии, чтобы мы могли узнавать пользователей которые уже прошли идентификацию

mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());

mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());

Каждая из этих функций выполняет отдельные, но связанные задачи.

Функция mysql_connect выполняет соединение с сервером баз данных MySQL в качестве параметров в скобках указаны переменные которым присвоены соответствующие значения Хост, Имя пользователя, Пароль если данные не верные выдаст сообщение об ошибке

Функция mysql_select_db выбирает базу данных имя которой мы присвоили переменной $dbname , в случае если не удаётся найти базу выводит сообщение об ошибке

Шаг-2 Создаем файл index.php

Немало важным элементом на нашей странице – является первая строка PHP; эта строка будет включать файл, который мы создали выше (base.php ), и по существу позволим нам обращаться к чему-нибудь от того файла в нашем текущем файле. Мы сделаем это со следующей строкой кода PHP. Создайте файл, названный index.php, и поместите этот код наверху.

Создайте новый файл index.php и вставите в самое начало следующий код

Эта строка будет подключать фаил который мы создали выше (base.php), что позволит нам обращаться к коду того файла в нашем текущем файле.

Это осуществляет функция include()

Теперь мы займёмся созданием внешнего интерфейса, где пользователь будет вводить свои данные для регистрации, а если он уже зарегистрирован дать возможность изменения данных. Так как этот урок нацелен на PHP мы не будем разбираться с кодом HTML/CSS внешний вид сделаем потом когда мы создадим нашу таблицу стилей CSS, а пока просто вставим этот код после предыдущей строки.

Система управления пользователями <title> </span> <span><link rel="stylesheet" href="/style.css" type="text/css" /> </span> </head> <body> <span><div id="main">Сюда вставим php код </div> </p> <p>Теперь прежде чем пристать php программу разберём принцип её работы, что в той или иной ситуации надо выводит на экран:</p> <ol><li>Если пользователь уже вошёл то показываем страницу с различными опциями которые были скрыты до регистрации.</li> <li>Если пользователь еще не вошёл но прошёл регистрацию то показываем форму для ввода логина и пароля.</li> <li>Если 1 и 2 пункт не выполнен выводим форму для регистрации.</li> </ol><p>Выглядеть это будет так:</p> <p><?php </span> <span>if (! empty empty </span> <span>{ </span> <span>// Здесь выводиться скрытые опции </span> <span>} </span> <span>elseif (! empty empty ($_POST [ "password" ] ) ) </span> <span>{ </span> <span>// Выводим форму для входа </span> <span>} </span> <span>else </span> <span>{ </span> <span>// Выводим форму для регистрации </span> <span>} </span> <span>?> </p> <p>Когда пользователь проходит авторизацию на нашем сайте, информация сохраняется в сессии получить к ней доступ мы можем через глобальный массив <b>$ _SESSION </b>. С помощью функции empty и знака! в условии if мы проверяем имеет ли переменная значение, если переменная имеет значение выполняем код между фигурных скобок.</p> <p>В следующей строке всё работает тем же образом, только на этот раз с помощью <b>$ _POST </b> глобального массива. Этот массив содержит какие либо данные переданные через форму входа которую мы создадим позже. Последняя условие else выполниться в том случае если предыдущие условия не удовлетворяются.</p> <p>Теперь когда мы понимаем логику давайте вставим следующий код в файл index.php между тегами <div></p> <p><?php </span> <span>if (! empty ($_SESSION [ "LoggedIn" ] ) && ! empty ($_SESSION [ "Username" ] ) ) </span> <span>{ </span> <span>?> </span> <span> <h1>Пользовательская зона</h1> </span> <span> <p Спасибо что вошли! Вы <b><?= $_SESSION [ "Username" ] ?> </b> и Ваш адрес электронной почты <b><?= $_SESSION [ "EmailAddress" ] ?> </b>.</p> </span> <span><?php </span> <span>} </span> <span>elseif (! empty ($_POST [ "username" ] ) && ! empty ($_POST [ "password" ] ) ) </span> <span>{ </span> <span>$username = mysql_real_escape_string ($_POST [ "username" ] ) ; </span> <span>$password = md5 (mysql_real_escape_string </span> <span>$checklogin = mysql_query (</span> <span>if (mysql_num_rows ($checklogin ) == 1 ) </span> <span>{ </span> <span>$row = mysql_fetch_array ($checklogin ) ; </span> <span> echo <span>"<h1>Вы успешно вошли</h1>" </span>; </span> <span> echo <span>"<p>Сейчас вы будете переадресованы в ваш профиль.</p>" </span>; </span> <span> echo <span>"<meta content="=2;index.php" />" </span>; </span> <span>} </span> <span>else </span> <span>{ </span> <span> echo "<h1>Ошибка</h1>" ; </span> <span> echo <span>"<p>Ваша учётная запись не найдена или вы неправильно ввели логин или пароль. <a href=\" index.php\" >Попробовать снова </a>.</p>" </span>; </span> <span>} </span> <span>} </span> <span>else </span> <span>{ </span> <span>?> </span> <h1>Вход</h1> <span> <p>Хорошо что зашли Регистрация .</p> </span> <span> <form method="post" action="index.php" name="loginform" id="loginform"> </span> <fieldset> <span> <label for="username">Логин:</label><input type="text" name="username" id="username" /><br /> </span> <span> <label for="password">Пароль:</label><input type="password" name="password" id="password" /><br /> </span> <span> <input type="submit" name="login" id="login" value="Войти" /> </span> </fieldset> </form> <span><?php </span> <span>} </span> <span>?> </p> <p>В этом участке кода две функции,это<b>mysql _real _escape _string </b>которая экранирует специальные символы в строках для использования в базе данных тем самым обезопасит вас от нехорошихлюдей, и <b>md 5 </b> эта функция шифрует всё что передано ей в качестве параметра, в данном случае это пароль в глобальном массиве <b>$_POST </b>. Всё результаты работы функций мы присваиваем переменным<b>$username , <span>$password </span> </b>.</p> <p>$checklogin = mysql_query (<span>"SELECT * FROM users WHERE Username = "" </span>. $username . "" AND Password = "" . $password . """ ) ; </span> <span>if (mysql_num_rows ($checklogin ) == 1 ) </span> <span>{ </span> <span>$row = mysql_fetch_array ($checklogin ) ; </span> <span>$email = $row [ "EmailAddress" ] ; </span> <span>$_SESSION [ "Username" ] = $username ; </span> <span>$_SESSION [ "EmailAddress" ] = $email ; </span> <span>$_SESSION [ "LoggedIn" ] = 1 ; </p> <p>В этом участке кода нам надо проверить существует ли такой пользователь,для этого направляем запрос в базу данных, вытащить все поля из таблицы users где поля Username и Password равны переменным<b>$username и $password </b>. Результат запроса заносим в переменную<b>$checklogin </b> далее в условии <b>if </b> функция <b>mysql _num _row </b>s считает количество строк в запросе к базе и если равно 1 то есть пользователь найденвыполняем код в фигурных скобках, функция <b>mysql _fetch _array </b>преобразовывает результат запроса из <b>$checklogin </b>в ассоциативный массив, присваиваеваем значение поля EmailAddress переменной <b>$email </b>для использовать в дальнейшем.</p> <p>Заносим логин и email в текущею сессию после этого пользователь перенаправляется в свою учётную запись.</p> <p><b>Шаг-3 </b></p> <p>Теперь надо сделать страницу где пользователи будут регистрироваться.</p> <p>Создаем файл register.phpи скопируйте в него следующий код:</p> <p><?php include "base.php" ; ?> </span> <span><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> </span> <span><html xmlns="http://www.w3.org/1999/xhtml"> </span> <span><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </span> <span><title> Система управления пользователями - Регистрацияtitle> </span> <span><link rel="stylesheet" href="/style.css" type="text/css" /> </span> </head> <body> <div id="main"> <span><?php </span> <span>if (! empty ($_POST [ "username" ] ) && ! empty ($_POST [ "password" ] ) ) </span> <span>{ </span> <span>$username = mysql_real_escape_string ($_POST [ "username" ] ) ; </span> <span>$password = md5 (mysql_real_escape_string ($_POST [ "password" ] ) ) ; </span> <span>$email = mysql_real_escape_string ($_POST [ "email" ] ) ; </span> <span>$checkusername = mysql_query (<span>"SELECT * FROM users WHERE Username = "" </span>. $username . """ ) ; </span> <span>if (mysql_num_rows ($checkusername ) == 1 ) </span> <span>{ </span> <span> echo "<h1>Ошибка</h1>" ; </span> <span> echo <span>"<p>Такой логин уже занят p>" </span>; </span> <span>} </span> <span>else </span> <span>{ </span> <span>$registerquery = mysql_query (<span>"INSERT INTO users (Username, Password, EmailAddress) VALUES("" </span>. $username . "", "" . $password . "", "" . $email . "")" ) ; </span> <span>if ($registerquery ) </span> <span>{ </span> <span> echo "<h1>Отлично</h1>" ; </span> <span> echo <span>"<p>Ваша учетная запись была успешно создана. Вы можете<a href=\" index.php\" >Воити</a>.</p>" </span>; </span> <span>} </span> <span>else </span> <span>{ </span> <span> echo "<h1>Ошибка</h1>" ; </span> <span> echo <span>"<p>Попробуйте повторить регистрацию снова.</p>" </span>; </span> <span>} </span> <span>} </span> <span>} </span> <span>else </span> <span>{ </span> <span>?> </span> <span> <h1>Регистрация</h1> </span> <span> <form method="post" action="register.php" name="registerform" id="registerform"> </span> <fieldset> <span> <label for="username">Логин:</label><input type="text" name="username" id="username" /><br /> </span> <span> <label for="password">Пароль:</label><input type="password" name="password" id="password" /><br /> </span> <span> <label for="email">Email:</label><input type="text" name="email" id="email" /><br /> </span> <span> <input type="submit" name="register" id="register" value="Регистрация" /> </span> </fieldset> </form> <span><?php </span> <span>} </span> <span>?> </span> </div> </body> </html> </p> <p>В этом коде есть немного нового, запись в базу данных</p> <p>Это такой же запрос к базе данных который был раньше только теперь мы не получаеминформацию, а записываем командой INSERT , первым деломнадо указать в какие поля будет вноситься информация а в область VALUES информация которая будет записана в нашем случае это переменные со значением которые были переданы пользователем.Обратите особое внимание правила формирования запросов.</p> <p><b>Шаг-4 Завершение </b></p> <p>Для того чтобы пользователь мог выйти создайте файл logout.php и скопируйте в него код:</p> <p><?php include "base.php; <span>$_SESSION = array(); session_destroy(); ?> </span> <meta http-equiv=" refresh" content=" 0 ; index. php" </p> <p>В результате этого кода происходит сбросглобального массива $_SESSION и разрушение сессии, не забудьтев опция пользователя поставить ссылку на этот фаил.</p> <p>И наконец придадим стиль всему вышеописанному, создайте файл style.css и поместите туда следующий ниже код.</p> <p>* { </span> <span>margin : 0 ; </span> <span>padding : 0 ; </span> <span>} </span> body <span>{ </span> <span>} </span> a <span>{ </span> <span>color : #000 ; </span> <span>} </span> a<span>:hover , a:active , a:visited { </span> <span>text-decoration : none ; </span> <span>} </span> <span>#main { </span> <span>width : 780px ; </span> <span>margin : 0 auto ; </span> <span>margin-top : 50px ; </span> <span>padding : 10px ; </span> <span>background-color : #EEE ; </span> <span>} </span> form fieldset <span>{ border : 0 ; } </span> form fieldset p br <span>{ clear : left ; } </span> label <span>{ </span> <span>margin-top : 5px ; </span> <span>display : block ; </span> <span>width : 100px ; </span> <span>padding : 0 ; </span> <span>float : left ; </span> <span>} </span> input <span>{ </span> <span>font-family : Trebuchet MS; </span> <span>border : 1px solid #CCC ; </span> <span>margin-bottom : 5px ; </span> <span>background-color : #FFF ; </span> <span>padding : 2px ; </span> <span>} </span> input<span>:hover { </span> <span>border : 1px solid #222 ; </span> <span>background-color : #EEE ; </span> <span>} </p> <p>Вот в принципе и всё конечно приведенный в этом уроке пример далёк от совершенства но он и был рассчитан для начинающих чтобы дать понятие основ.</p> <p>Разберём некоторые части данного кода</p> <p>$username = mysql_real_escape_string($_POST["username"]); </p> <p>$password = md5(mysql_real_escape_string($_POST["password"])); </p> <p>В этом участке кода две функции,этоmysql _real _escape _string которая экранирует специальные символы в строках для использования в базе данных тем самым обезопасит вас от нехорошихлюдей, и md 5 эта функция шифрует всё что передано ей в качестве параметра, в данном случае это пароль в глобальном массиве $_POST . Всё результаты работы функций мы присваиваем переменным$username , <span>$password </span>.</p> <p>In this tutorial, I walk you through the complete process of creating a user registration system where users can create an account by providing username, email and password, login and logout using PHP and MySQL. I will also show you how you can make some pages accessible only to logged in users. Any other user not logged in will not be able to access the page.</p> <p>If you prefer a video, you can watch it on my YouTube channel </p> <p>The first thing we"ll need to do is set up our database.</p> <p>Create a database called <b>registration </b>. In the <b>registration </b> database, add a table called <b>users </b>. The users table will take the following four fields.</p> <ul><li>username - varchar(100)</li> <li>email - varchar(100)</li> <li>password - varchar(100)</li> </ul><p>You can create this using a MySQL client like PHPMyAdmin.</p> <p>Or you can create it on the MySQL prompt using the following SQL script:</p><p>CREATE TABLE `users` (`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `username` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(100) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1; </p><p>And that"s it with the database.</p> <p>Now create a folder called <b>registration </b> in a directory accessible to our server. i.e create the folder inside htdocs (if you are using XAMPP server) or inside <b>www </b>(if you are using wampp server).</p> <p>Inside the folder <b>registration, </b>create the following files:</p> <p><img src='https://i1.wp.com/codewithawa.com/assets/post_images/Screenshot%20from%202017-07-09%2016-44-54.png.2017-07-09.1499615116.png' width="100%" loading=lazy></p> <p>Open these files up in a text editor of your choice. Mine is Sublime Text 3.</p> <h3>Registering a user</h3> <p>Open the register.php file and paste the following code in it:</p> <p><b>regiser.php: </b></p><p> <?php include("server.php") ?> <!DOCTYPE html> <html> <head> <title>

Register

Already a member? Sign in

Nothing complicated so far right?

A few things to note here:

First is that our form"s action attribute is set to register.php. This means that when the form submit button is clicked, all the data in the form will be submitted to the same page (register.php). The part of the code that receives this form data is written in the server.php file and that"s why we are including it at the very top of the register.php file.

Notice also that we are including the errors.php file to display form errors. We will come to that soon.

As you can see in the head section, we are linking to a style.css file. Open up the style.css file and paste the following CSS in it:

* { margin: 0px; padding: 0px; } body { font-size: 120%; background: #F8F8FF; } .header { width: 30%; margin: 50px auto 0px; color: white; background: #5F9EA0; text-align: center; border: 1px solid #B0C4DE; border-bottom: none; border-radius: 10px 10px 0px 0px; padding: 20px; } form, .content { width: 30%; margin: 0px auto; padding: 20px; border: 1px solid #B0C4DE; background: white; border-radius: 0px 0px 10px 10px; } .input-group { margin: 10px 0px 10px 0px; } .input-group label { display: block; text-align: left; margin: 3px; } .input-group input { height: 30px; width: 93%; padding: 5px 10px; font-size: 16px; border-radius: 5px; border: 1px solid gray; } .btn { padding: 10px; font-size: 15px; color: white; background: #5F9EA0; border: none; border-radius: 5px; } .error { width: 92%; margin: 0px auto; padding: 10px; border: 1px solid #a94442; color: #a94442; background: #f2dede; border-radius: 5px; text-align: left; } .success { color: #3c763d; background: #dff0d8; border: 1px solid #3c763d; margin-bottom: 20px; }

Now the form looks beautiful.

Let"s now write the code that will receive information submitted from the form and store (register) the information in the database. As promised earlier, we do this in the server.php file.

Open server.php and paste this code in it:

server.php

Sessions are used to track logged in users and so we include a session_start() at the top of the file.

The comments in the code pretty much explain everything, but I"ll highlight a few things here.

The if statement determines if the reg_user button on the registration form is clicked. Remember, in our form, the submit button has a name attribute set to reg_user and that is what we are referencing in the if statement.

All the data is received from the form and checked to make sure that the user correctly filled the form. Passwords are also compared to make sure they match.

If no errors were encountered, the user is registered in the users table in the database with a hashed password. The hashed password is for security reasons. It ensures that even if a hacker manages to gain access to your database, they would not be able to read your password.

But error messages are not displaying now because our errors.php file is still empty. To display the errors, paste this code in the errors.php file.

0) : ?>

When a user is registered in the database, they are immediately logged in and redirected to the index.php page.

And that"s it for registration. Let"s look at user login.

Login user

Logging a user in is an even easier thing to do. Just open the login page and put this code inside it:

Registration system PHP and MySQL

Login

Not yet a member? Sign up

Everything on this page is quite similar to the register.php page.

Now the code that logs the user in is to be written in the same server.php file. So open the server.php file and add this code at the end of the file:

// ... // LOGIN USER if (isset($_POST["login_user"])) { $username = mysqli_real_escape_string($db, $_POST["username"]); $password = mysqli_real_escape_string($db, $_POST["password"]); if (empty($username)) { array_push($errors, "Username is required"); } if (empty($password)) { array_push($errors, "Password is required"); } if (count($errors) == 0) { $password = md5($password); $query = "SELECT * FROM users WHERE username="$username" AND password="$password""; $results = mysqli_query($db, $query); if (mysqli_num_rows($results) == 1) { $_SESSION["username"] = $username; $_SESSION["success"] = "You are now logged in"; header("location: index.php"); }else { array_push($errors, "Wrong username/password combination"); } } } ?>

Again all this does is check if the user has filled the form correctly, verifies that their credentials match a record from the database and logs them in if it does. After logging in, the user is redirected them to the index.php file with a success message.

Now let"s see what happens in the index.php file. Open it up and paste the following code in it:

Home

Home Page

Welcome

logout

The first if statement checks if the user is already logged in. If they are not logged in, they will be redirected to the login page. Hence this page is accessible to only logged in users. If you"d like to make any page accessible only to logged in users, all you have to do is place this if statement at the top of the file.

The second if statement checks if the user has clicked the logout button. If yes, the system logs them out and redirects them back to the login page.

Now go on, customize it to suit your needs and build an awesome site. If you have any worries or anything you need to clarify, leave it in the comments below and help will come.

You can always support by sharing on social media or recommending my blog to your friends and colleagues.

Здравствуйте! Сейчас мы попробуем реализовать самую простую регистрацию на сайте с помощью PHP + MySQL. Для этого на вашем компьютере должен быть установлен Apache. Принцип работы нашего скрипта изображен ниже.

1. Начнем с создания таблички users в базе . Она будет содержать данные пользователя (логин и пароль). Зайдем в phpmyadmin (если вы создаете базу на своем ПК http://localhost/phpmyadmin/ ). Создаем таблицу users , в ней будет 3 поля.

Я создаю ее в базе mysql, вы можете создавать в другой базе. Далее устанавливаем значения, как на рисунке:

2. Необходимо соединение с этой таблицей. Давайте создадим файл bd.php . Его содержание:

$db = mysql_connect ("ваш MySQL сервер","логин к этому серверу","пароль к этому серверу");
mysql_select_db ("имя базы, к которой подключаемся",$db);
?>

В моем случае это выглядит так:

$db = mysql_connect ("localhost","user","1234");
mysql_select_db ("mysql",$db);
?>

Сохраняем bd.php .
Отлично! У нас есть таблица в базе, соединение к ней. Теперь можно приступать к созданию странички, на которой пользователи будут оставлять свои данные.

3. Создаем файл reg.php с содержанием (все комментарии внутри):



Регистрация


Регистрация
















4. Создаем файл , который будет заносить данные в базу и сохранять пользователя. save_user.php (комментарии внутри):



{
}
//если логин и пароль введены, то обрабатываем их, чтобы теги и скрипты не работали, мало ли что люди могут ввести


//удаляем лишние пробелы
$login = trim($login);
$password = trim($password);
// подключаемся к базе
// проверка на существование пользователя с таким же логином
$result = mysql_query("SELECT id FROM users WHERE login="$login"",$db);
if (!empty($myrow["id"])) {
exit ("Извините, введённый вами логин уже зарегистрирован. Введите другой логин.");
}
// если такого нет, то сохраняем данные
$result2 = mysql_query ("INSERT INTO users (login,password) VALUES("$login","$password")");
// Проверяем, есть ли ошибки
if ($result2=="TRUE")
{
echo "Вы успешно зарегистрированы! Теперь вы можете зайти на сайт. Главная страница";
}
else {
echo "Ошибка! Вы не зарегистрированы.";
}
?>

5. Теперь наши пользователи могут регистрироваться! Далее необходимо сделать "дверь" для входа на сайт уже зарегистрированным пользователям. index.php (комментарии внутри) :

// вся процедура работает на сессиях. Именно в ней хранятся данные пользователя, пока он находится на сайте. Очень важно запустить их в самом начале странички!!!
session_start();
?>


Главная страница


Главная страница











Зарегистрироваться



// Проверяем, пусты ли переменные логина и id пользователя
if (empty($_SESSION["login"]) or empty($_SESSION["id"]))
{
// Если пусты, то мы не выводим ссылку
echo "Вы вошли на сайт, как гость
Эта ссылка доступна только зарегистрированным пользователям";
}
else
{

В файле index.php мы выведем ссылочку, которая будет открыта только для зарегистрированных пользователей. В этом и заключается вся суть скрипта - ограничить доступ к каким-либо данным.

6. Остался файл с проверкой введенного логина и пароля. testreg.php (комментарии внутри):

session_start();// вся процедура работает на сессиях. Именно в ней хранятся данные пользователя, пока он находится на сайте. Очень важно запустить их в самом начале странички!!!
if (isset($_POST["login"])) { $login = $_POST["login"]; if ($login == "") { unset($login);} } //заносим введенный пользователем логин в переменную $login, если он пустой, то уничтожаем переменную
if (isset($_POST["password"])) { $password=$_POST["password"]; if ($password =="") { unset($password);} }
//заносим введенный пользователем пароль в переменную $password, если он пустой, то уничтожаем переменную
if (empty($login) or empty($password)) //если пользователь не ввел логин или пароль, то выдаем ошибку и останавливаем скрипт
{
exit ("Вы ввели не всю информацию, вернитесь назад и заполните все поля!");
}
//если логин и пароль введены,то обрабатываем их, чтобы теги и скрипты не работали, мало ли что люди могут ввести
$login = stripslashes($login);
$login = htmlspecialchars($login);
$password = stripslashes($password);
$password = htmlspecialchars($password);
//удаляем лишние пробелы
$login = trim($login);
$password = trim($password);
// подключаемся к базе
include ("bd.php");// файл bd.php должен быть в той же папке, что и все остальные, если это не так, то просто измените путь

$result = mysql_query("SELECT * FROM users WHERE login="$login"",$db); //извлекаем из базы все данные о пользователе с введенным логином
$myrow = mysql_fetch_array($result);
if (empty($myrow["password"]))
{
//если пользователя с введенным логином не существует
}
else {
//если существует, то сверяем пароли
if ($myrow["password"]==$password) {
//если пароли совпадают, то запускаем пользователю сессию! Можете его поздравить, он вошел!
$_SESSION["login"]=$myrow["login"];
$_SESSION["id"]=$myrow["id"];//эти данные очень часто используются, вот их и будет "носить с собой" вошедший пользователь
echo "Вы успешно вошли на сайт! Главная страница";
}
else {
//если пароли не сошлись

Exit ("Извините, введённый вами login или пароль неверный.");
}
}
?>

Ну вот и все! Может урок и скучный, но очень полезный. Здесь показана только идея регистрации, далее Вы можете усовершенствовать ее: добавить защиту, оформление, поля с данными, загрузку аватаров, выход из аккаунта (для этого просто уничтожить переменные из сессии функцией unset ) и так далее. Удачи!

Все проверил, работает исправно!

Creating a membership based site seems like a daunting task at first. If you ever wanted to do this by yourself, then just gave up when you started to think how you are going to put it together using your PHP skills, then this article is for you. We are going to walk you through every aspect of creating a membership based site, with a secure members area protected by password.

The whole process consists of two big parts: user registration and user authentication. In the first part, we are going to cover creation of the registration form and storing the data in a MySQL database. In the second part, we will create the login form and use it to allow users access in the secure area.

Download the code

You can download the whole source code for the registration/login system from the link below:

Configuration & Upload
The ReadMe file contains detailed instructions.

Open the source\include\membersite_config.php file in a text editor and update the configuration. (Database login, your website’s name, your email address etc).

Upload the whole directory contents. Test the register.php by submitting the form.

The registration form

In order to create a user account, we need to gather a minimal amount of information from the user. We need his name, his email address and his desired username and password. Of course, we can ask for more information at this point, but a long form is always a turn-off. So let’s limit ourselves to just those fields.

Here is the registration form:

Register

So, we have text fields for name, email and the password. Note that we are using the for better usability.

Form validation

At this point it is a good idea to put some form validation code in place, so we make sure that we have all the data required to create the user account. We need to check if name and email, and password are filled in and that the email is in the proper format.

Handling the form submission

Now we have to handle the form data that is submitted.

Here is the sequence (see the file fg_membersite.php in the downloaded source):

function RegisterUser() { if(!isset($_POST["submitted"])) { return false; } $formvars = array(); if(!$this->ValidateRegistrationSubmission()) { return false; } $this->CollectRegistrationSubmission($formvars); if(!$this->SaveToDatabase($formvars)) { return false; } if(!$this->SendUserConfirmationEmail($formvars)) { return false; } $this->SendAdminIntimationEmail($formvars); return true; }

First, we validate the form submission. Then we collect and ‘sanitize’ the form submission data (always do this before sending email, saving to database etc). The form submission is then saved to the database table. We send an email to the user requesting confirmation. Then we intimate the admin that a user has registered.

Saving the data in the database

Now that we gathered all the data, we need to store it into the database.
Here is how we save the form submission to the database.

function SaveToDatabase(&$formvars) { if(!$this->DBLogin()) { $this->HandleError("Database login failed!"); return false; } if(!$this->Ensuretable()) { return false; } if(!$this->IsFieldUnique($formvars,"email")) { $this->HandleError("This email is already registered"); return false; } if(!$this->IsFieldUnique($formvars,"username")) { $this->HandleError("This UserName is already used. Please try another username"); return false; } if(!$this->InsertIntoDB($formvars)) { $this->HandleError("Inserting to Database failed!"); return false; } return true; }

Note that you have configured the Database login details in the membersite_config.php file. Most of the cases, you can use “localhost” for database host.
After logging in, we make sure that the table is existing.(If not, the script will create the required table).
Then we make sure that the username and email are unique. If it is not unique, we return error back to the user.

The database table structure

This is the table structure. The CreateTable() function in the fg_membersite.php file creates the table. Here is the code:

function CreateTable() { $qry = "Create Table $this->tablename (". "id_user INT NOT NULL AUTO_INCREMENT ,". "name VARCHAR(128) NOT NULL ,". "email VARCHAR(64) NOT NULL ,". "phone_number VARCHAR(16) NOT NULL ,". "username VARCHAR(16) NOT NULL ,". "password VARCHAR(32) NOT NULL ,". "confirmcode VARCHAR(32) ,". "PRIMARY KEY (id_user)". ")"; if(!mysql_query($qry,$this->connection)) { $this->HandleDBError("Error creating the table \nquery was\n $qry"); return false; } return true; }

The id_user field will contain the unique id of the user, and is also the primary key of the table. Notice that we allow 32 characters for the password field. We do this because, as an added security measure, we will store the password in the database encrypted using MD5. Please note that because MD5 is an one-way encryption method, we won’t be able to recover the password in case the user forgets it.

Inserting the registration to the table

Here is the code that we use to insert data into the database. We will have all our data available in the $formvars array.

function InsertIntoDB(&$formvars) { $confirmcode = $this->MakeConfirmationMd5($formvars["email"]); $insert_query = "insert into ".$this->tablename."(name, email, username, password, confirmcode) values ("" . $this->SanitizeForSQL($formvars["name"]) . "", "" . $this->SanitizeForSQL($formvars["email"]) . "", "" . $this->SanitizeForSQL($formvars["username"]) . "", "" . md5($formvars["password"]) . "", "" . $confirmcode . "")"; if(!mysql_query($insert_query ,$this->connection)) { $this->HandleDBError("Error inserting data to the table\nquery:$insert_query"); return false; } return true; }

Notice that we use PHP function md5() to encrypt the password before inserting it into the database.
Also, we make the unique confirmation code from the user’s email address.

Sending emails

Now that we have the registration in our database, we will send a confirmation email to the user. The user has to click a link in the confirmation email to complete the registration process.

function SendUserConfirmationEmail(&$formvars) { $mailer = new PHPMailer(); $mailer->CharSet = "utf-8"; $mailer->AddAddress($formvars["email"],$formvars["name"]); $mailer->Subject = "Your registration with ".$this->sitename; $mailer->From = $this->GetFromAddress(); $confirmcode = urlencode($this->MakeConfirmationMd5($formvars["email"])); $confirm_url = $this->GetAbsoluteURLFolder()."/confirmreg.php?code=".$confirmcode; $mailer->Body ="Hello ".$formvars["name"]."\r\n\r\n". "Thanks for your registration with ".$this->sitename."\r\n". "Please click the link below to confirm your registration.\r\n". "$confirm_url\r\n". "\r\n". "Regards,\r\n". "Webmaster\r\n". $this->sitename; if(!$mailer->Send()) { $this->HandleError("Failed sending registration confirmation email."); return false; } return true; }

Updates

9th Jan 2012
Reset Password/Change Password features are added
The code is now shared at GitHub .

Welcome back UserFullName(); ?>!

License


The code is shared under LGPL license. You can freely use it on commercial or non-commercial websites.

No related posts.

Comments on this entry are closed.

Laravel requires Composer to manage the project dependencies. So before installing Laravel, make sure you have Composer installed on your system. In case you are hearing about Composer for the first time, it"s a dependency management tool for php similar to node"s npm.

To install Composer on your machine, check this post:

Installing Laravel on Windows:

Follow the below steps to install laravel on windows machine. No matter you have xampp/wamp stack, it works for both. On WAMP, make sure to install laravel on "www" folder and on XAMPP, obviously the "htdocs".

STEP-1) Open "htdocs" folder on XAMPP, hold SHIFT key and right click on the folder, and choose "open command window here". Alternatively, you can open command window and change directory to "xampp/htdocs".

STEP-2) Enter the following command.

Composer create-project laravel/laravel my_laravel_site --prefer-dist

Here "my_laravel_site" is the folder name where laravel files will be installed. Change this to your liking.

STEP-3) Now it"s time to be patient as laravel installation is going to take some time.

STEP-4) Once installed, change directory to "my_laravel_site" (cd "my_laravel_site") on the command prompt and enter the below command.

Php artisan serve

STEP-5) This will show a message something like, "Laravel development server started:" along with an url.

STEP-6) Copy and paste the url on the browser. If things go right, you"d see the laravel welcome screen.

STEP-7) Done! You have successfully installed laravel on windows machine and ready to go with.

Setting Application Key:

Laravel requires little configuration after installation. It requires you to set the application key. This is a random string of 32 characters long used for encrypting session and other sensitive data. Usually this will be set automatically when you install laravel via composer or laravel installer.

In case it"s not set, you have to do it manually. First make sure to rename the ".env.example" file to ".env" on your application root. Then open command prompt and change to the laravel project folder. Now run the below command to generate the key.

Php artisan key:generate

Copy this generated key to the APP_KEY variable on ".env" file. Save and you are done.

Installing Specific Laravel Version:

The above given method will make composer to download and install the latest version of laravel. If you want to install earlier versions of laravel on your machine, make sure to include the respective version number on create-project command.

Composer create-project laravel/laravel=5.4 your-project-name --prefer-dist Read Also:

Likewise you can easily install laravel using composer on windows . I hope you find this tutorial useful. Please share it on your social circle if you like it.

Похожие публикации