Скрипт был успешно протестирован на версии PHP 5.3.3
и PHP 5.6.3
.
2 ШАГ
. Переходим (если используете DENWER) по адресу: http://localhost/Tools/phpmyadmin/ , если на хостинге, то нажимаете Базы Данных, и создаёте новую базу с именем: registr
и сравнение: utf8_general_ci
. Вы можете задать разумеется своё имя, но тогда замените его обязательно в файлах для соединения с базой (см. шаг 1).
После того, как вы сделали хоть одну регистрацию, можете перейти в АДМИНКУ. Вход в АДМИН-ПАНЕЛЬ
:
Не забудьте запоролить эту папку для безопасности и можно так же переименовать её. При открытие Админ Панели нажмите кнопку ПОИСК
и вам отобразятся все зарегистрированные пользователи, где при нажатие на определённый номер ID
, вам откроются данные пользователя для редактирования.
Можно так же быстро найти пользователя по его E-mail, для этого достаточно ввести в поле для ПОИСКа
известную электронную почту и нажать на кнопку. Кнопкой ДОБАВИТЬ
не советую пользоваться, так как пользователь добавляется в систему без пароля. И не имею понятия зачем её вообще сделали.
На этом всё, что не получается или не понятно, - задавайте вопросы.
. Каждому разделу можно присвоить название с помощью элемента .
Контактная информация
Имя
E-mail
Рис. 1. Группировка полей формы
Чтобы сделать форму более понятной для пользователей, в поля формы добавляют текст, содержащий пример вводимых данных. Такой текст называется подстановочным и создаётся с помощью атрибута placeholder .
Обязательные для заполнения поля также необходимо выделять. До появления HTML5 использовался символ звездочки * , установленный возле названия поля. В новой спецификации появился специальный атрибут required , который позволяет отметить обязательное поле на уровне разметки. Этот атрибут дает указание браузеру (при условии, что тот поддерживает HTML5), указание не отправлять данные после нажатия пользователем кнопки отправить, пока указанные поля не заполнены.
Для изменения внешний вид текстового поля при получении фокуса, используется псевдокласс focus . Например, можно сделать фон текущего поля более темным или добавить цветную рамку, чтобы оно выделялось среди остальных:
Input:focus {
background: #eaeaea;
}
Ещё один полезный html5-атрибут — атрибут autofocus . Он позволяет автоматически установить фокус на нужном начальном поле для элементов и
Пример создания формы регистрации
HTML разметка
Примечание
action="form.php" — ссылка на файл обработчика формы. Создайте файл в кодировке UTF-8, закачайте его на сервер и замените action="form.php" на путь к файлу на вашем сервере.
Рис. 2. Внешний вид формы по умолчанию
Как видно из рисунка, каждый элемент формы имеет стили браузера по умолчанию. Очистим стили и оформим элементы формы.
Form-wrap {
width: 550px;
background: #ffd500;
border-radius: 20px;
}
.form-wrap *{transition: .1s linear}
.profile {
width: 240px;
float: left;
text-align: center;
padding: 30px;
}
form {
background: white;
float: left;
width: calc(100% - 240px);
padding: 30px;
border-radius: 0 20px 20px 0;
color: #7b7b7b;
}
.form-wrap:after, form div:after {
content: "";
display: table;
clear: both;
}
form div {
margin-bottom: 15px;
position: relative;
}
h1 {
font-size: 24px;
font-weight: 400;
position: relative;
margin-top: 50px;
}
h1:after {
content: "\f138";
font-size: 40px;
font-family: FontAwesome;
position: absolute;
top: 50px;
left: 50%;
transform: translateX(-50%);
}
/********************** стилизация элементов формы **********************/
label, span {
display: block;
font-size: 14px;
margin-bottom: 8px;
}
input, input {
border-width: 0;
outline: none;
margin: 0;
width: 100%;
padding: 10px 15px;
background: #e6e6e6;
}
input:focus, input:focus {
box-shadow: inset 0 0 0 2px rgba(0,0,0,.2);
}
.radio label {
position: relative;
padding-left: 50px;
cursor: pointer;
width: 50%;
float: left;
line-height: 40px;
}
.radio input {
position: absolute;
opacity: 0;
}
.radio-control {
position: absolute;
top: 0;
left: 0;
height: 40px;
width: 40px;
background: #e6e6e6;
border-radius: 50%;
text-align: center;
}
.male:before {
content: "\f222";
font-family: FontAwesome;
font-weight: bold;
}
.female:before {
content: "\f221";
font-family: FontAwesome;
font-weight: bold;
}
.radio label:hover input ~ .radio-control,
.radiol input:focus ~ .radio-control {
box-shadow: inset 0 0 0 2px rgba(0,0,0,.2);
}
.radio input:checked ~ .radio-control {
color: red;
}
select {
width: 100%;
cursor: pointer;
padding: 10px 15px;
outline: 0;
border: 0;
background: #e6e6e6;
color: #7b7b7b;
-webkit-appearance: none; /*убираем галочку в webkit-браузерах*/
-moz-appearance: none; /*убираем галочку в Mozilla Firefox*/
}
select::-ms-expand {
display: none; /*убираем галочку в IE*/
}
.select-arrow {
position: absolute;
top: 38px;
right: 15px;
width: 0;
height: 0;
pointer-events: none; /*активизируем показ списка при нажатии на стрелку*/
border-style: solid;
border-width: 8px 5px 0 5px;
border-color: #7b7b7b transparent transparent transparent;
}
button {
padding: 10px 0;
border-width: 0;
display: block;
width: 120px;
margin: 25px auto 0;
background: #60e6c5;
color: white;
font-size: 14px;
outline: none;
text-transform: uppercase;
}
/********************** добавляем форме адаптивность **********************/
@media (max-width: 600px) {
.form-wrap {margin: 20px auto; max-width: 550px; width:100%;}
.profile, form {float: none; width: 100%;}
h1 {margin-top: auto; padding-bottom: 50px;}
form {border-radius: 0 0 20px 20px;}
}
Файл form.php
" . "\r\n";
$headers .= "Bcc: ваш_email". "\r\n";
if(!empty($name) && !empty($sex) && !empty($email) && !empty($country) && filter_var($email, FILTER_VALIDATE_EMAIL)){
mail($email, $subject, $msg, $headers);
echo "Спасибо! Вы успешно зарегистрировались.";
}
?>
Примечание
В переменной $subject укажите текст, который будет отображаться как заголовок письма;
Ваше_имя — здесь вы можете указать имя, которое будет отображаться в поле «от кого письмо» ;
url_вашего_сайта замените на адрес сайта с формой регистрации;
ваш_email замените на ваш адрес электронной почты;
$headers .= "Bcc: ваш_email". "\r\n"; отправляет скрытую копию на ваш адрес электронной почты.
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:
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 = $fgmembersite->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.
Здравствуйте! Сейчас мы попробуем реализовать самую простую регистрацию на сайте с помощью 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
) и так далее. Удачи!
Все проверил, работает исправно!