Кладь registration form php. PHP сценарии обработки HTML форм. Какой способ следует применять

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.

Over the past few years, web hosting has undergone a dramatic change. Web hosting services have changed the way websites perform. There are several kinds of services but today we will talk about the options that are available for reseller hosting providers. They are Linux Reseller Hosting and Windows Reseller Hosting. Before we understand the fundamental differences between the two, let’s find out what is reseller hosting.

Reseller Hosting

In simple terms, reseller hosting is a form of web hosting where an account owner can use his dedicated hard drive space and allotted bandwidth for the purpose of reselling to the websites of third parties. Sometimes, a reseller can take a dedicated server from a hosting company (Linux or Windows) on rent and further let it out to third parties.

Most website users either are with Linux or Windows. This has got to do with the uptime. Both platforms ensure that your website is up 99% of the time.

1. Customization

One of the main differences between a Linux Reseller Hostingplan and the one provided by Windows is about customization. While you can experiment with both the players in several ways, Linux is way more customizable than Windows. The latter has more features than its counterpart and that is why many developers and administrators find Linux very customer- friendly.

2. Applications

Different reseller hosting services have different applications. Linux and Windows both have their own array of applications but the latter has an edge when it comes to numbers and versatility. This has got to do with the open source nature of Linux. Any developer can upload his app on the Linux platform and this makes it an attractive hosting provider to millions of website owners.

However, please note that if you are using Linux for web hosting but at the same time use the Windows OS, then some applications may not simply work.

3. Stability

While both the platforms are stable, Linux Reseller Hosting is more stable of the two. It being an open source platform, can work in several environments.This platform can be modified and developed every now and then.

4. .NET compatibility

It isn’t that Linux is superior to Windows in every possible way. When it comes to .NET compatibility, Windows steals the limelight. Web applications can be easily developed on a Windows hosting platform.

5. Cost advantages

Both the hosting platforms are affordable. But if you are feeling a cash crunch, then you should opt for Linux. It is free and that is why it is opted by so many developers and system administrators all around the world.

6. Ease of setup

Windows is easier to set up than its counterpart. All things said and done, Windows still retains its user-friendliness all these years.

7. Security

Opt for Linux reseller hosting because it is more secure than Windows. This holds true especially for people running their E-commerce businesses.

Conclusion

Choosing between the two will depend on your requirement and the cost flexibility. Both the hosting services have unique advantages. While Windows is easy to set up, Linux is cost effective, secure and is more versatile.



Back in March of this year, I had a very bad experience with a media company refusing to pay me and answer my emails. They still owe me thousands of dollars and the feeling of rage I have permeates everyday. Turns out I am not alone though, and hundreds of other website owners are in the same boat. It"s sort of par for the course with digital advertising.

In all honesty, I"ve had this blog for a long time and I have bounced around different ad networks in the past. After removing the ad units from that company who stiffed me, I was back to square one. I should also note that I never quite liked Googles AdSense product, only because it feels like the "bottom of the barrel" of display ads. Not from a quality perspective, but from a revenue one.

From what I understand, you want Google advertising on your site, but you also want other big companies and agencies doing it as well. That way you maximize the demand and revenue.

After my negative experience I got recommend a company called Newor Media . And if I"m honest I wasn"t sold at first mostly because I couldn"t find much information on them. I did find a couple decent reviews on other sites, and after talking to someone there, I decided to give it a try. I will say that they are SUPER helpful. Every network I have ever worked with has been pretty short with me in terms of answers and getting going. They answered every question and it was a really encouraging process.

I"ve been running the ads for a few months and the earnings are about in line with what I was making with the other company. So I can"t really say if they are that much better than others, but where they do stand out is a point that I really want to make. The communication with them is unlike any other network I"ve ever worked it. Here is a case where they really are different:

They pushed the first payment to me on time with Paypal. But because I"m not in the U.S (and this happens for everyone I think), I got a fee taken out from Paypal. I emailed my representative about it, asking if there was a way to avoid that in the future.

They said that they couldn"t avoid the fee, but that they would REIMBURSE ALL FEES.... INCLUDING THE MOST RECENT PAYMENT! Not only that, but the reimbursement payment was received within 10 MINUTES! When have you ever been able to make a request like that without having to be forwarded to the "finance department" to then never be responded to.

The bottom line is that I love this company. I might be able to make more somewhere else, I"m not really sure, but they have a publisher for life with me. I"m not a huge site and I don"t generate a ton of income, but I feel like a very important client when I talk to them. It"s genuinely a breathe of fresh air in an industry that is ripe with fraud and non-responsiveness.

Microcomputers that have been created by the Raspberry Pi Foundation in 2012 have been hugely successful in sparking levels of creativity in young children and this UK based company began offering learn-to-code startup programs like pi-top an Kano. There is now a new startup that is making use of Pi electronics, and the device is known as Pip, a handheld console that offers a touchscreen, multiple ports, control buttons and speakers. The idea behind the device is to engage younger individuals with a game device that is retro but will also offer a code learning experience through a web based platform.

The amazing software platform being offered with Pip will offer the chance to begin coding in Python, HTML/CSS, JavaScript, Lua and PHP. The device offers step-by-step tutorials to get children started with coding and allows them to even make LEDs flash. While Pip is still a prototype, it will surely be a huge hit in the industry and will engage children who have an interest in coding and will provide them the education and resources needed to begin coding at a young age.

Future of Coding

Coding has a great future, and even if children will not be using coding as a career, they can benefit from learning how to code with this new device that makes it easier than ever. With Pip, even the youngest coding enthusiasts will learn different languages and will be well on their way to creating their own codes, own games, own apps and more. It is the future of the electronic era and Pip allows the basic building blocks of coding to be mastered.
Computer science has become an important part of education and with devices like the new Pip , children can start to enhance their education at home while having fun. Coding goes far beyond simply creating websites or software. It can be used to enhance safety in a city, to help with research in the medical field and much more. Since we now live in a world that is dominated by software, coding is the future and it is important for all children to at least have a basic understanding of how it works, even if they never make use of these skills as a career. In terms of the future, coding will be a critical component of daily life. It will be the language of the world and not knowing computers or how they work can pose challenges that are just as difficult to overcome as illiteracy.
Coding will also provide major changes in the gaming world, especially when it comes to online gaming, including the access of online casinos. To see just how coding has already enhanced the gaming world, take a look at a few top rated casino sites that rely on coding. Take a quick peek to check it out and see just how coding can present realistic environments online.

How Pip Engages Children

When it comes to the opportunity to learn coding, children have many options. There are a number of devices and hardware gizmos that can be purchased, but Pip takes a different approach with their device. The portability of the device and the touchscreen offer an advantage to other coding devices that are on the market. Pip will be fully compatible with electronic components in addition to the Raspberry Pi HAT system. The device uses standard languages and has basic tools and is a perfect device for any beginner coder. The goal is to remove any barriers between an idea and creation and make tools immediately available for use. One of the other great advantages of Pip is that it uses a SD card, so it can be used as a desktop computer as well when it is connected to a monitor and mouse.
The Pip device would help kids and interested coder novice with an enthusiasm into learning and practicing coding. By offering a combination of task completion and tinkering to solve problems, the device will certainly engage the younger generation. The device then allows these young coders to move to more advanced levels of coding in different languages like JavaScript and HTML/CSS. Since the device replicates a gaming console, it will immediately capture the attention of children and will engage them to learn about coding at a young age. It also comes with some preloaded games to retain attention, such as Pac-Man and Minecraft.

Innovations to Come

Future innovation largely depends on a child’s current ability to code and their overall understanding of the process. As children learn to code at an early age by using such devices as the new Pip, they will gain the skills and knowledge to create amazing things in the future. This could be the introduction of new games or apps or even ideas that can come to life to help with medical research and treatments. There are endless possibilities. Since our future will be controlled by software and computers, starting young is the best way to go, which is why the new Pip is geared towards the young crowd. By offering a console device that can play games while teaching coding skills, young members of society are well on their way to being the creators of software in the future that will change all our lives. This is just the beginning, but it is something that millions of children all over the world are starting to learn and master. With the use of devices like Pip, coding basics are covered and children will quickly learn the different coding languages that can lead down amazing paths as they enter adulthood.

Much of the websites have a registration form for your users to sign up and thus may benefit from some kind of privilege within the site. In this article we will see how to create a registration form in PHP and MySQL.

We will use simple tags and also we will use table tag to design the Sign-Up.html webpage. Let’s start:

Listing 1 : sign-up.html

Sign-Up

Registration Form
Name
Email
UserName
Password
Confirm Password


Figure 1:

Description of sing-in.html webpage:

As you can see the Figure 1, there is a Registration form and it is asking few data about user. These are the common data which ask by any website from his users or visitors to create and ID and Password. We used table tag because to show the form fields on the webpage in a arrange form as you can see them on Figure 1. It’s looking so simple because we yet didn’t used CSS Style on it now let’s we use CSS styles and link the CSS style file with sing-up.html webpage.

Listing 2 : style.css

/*CSS File For Sign-Up webpage*/ #body-color{ background-color:#6699CC; } #Sign-Up{ background-image:url("sign-up.png"); background-size:500px 500px; background-repeat:no-repeat; background-attachment:fixed; background-position:center; margin-top:150px; margin-bottom:150px; margin-right:150px; margin-left:450px; padding:9px 35px; } #button{ border-radius:10px; width:100px; height:40px; background:#FF00FF; font-weight:bold; font-size:20px; }

Listing 3 : Link style.css with sign-up.html webpage



Figure 2:

Description of style.css file:

In the external CSS file we used some styles which could be look new for you. As we used an image in the background and set it in the center of the webpage. Which is become easy to use by the help of html div tag. As we used three div tag id’s. #button, #sing-up, and #body-color and we applied all CSS styles on them and now you can see the Figure 2, how much it’s looking beautiful and attractive. You can use many other CSS styles as like 2D and 3D CSS styles on it. It will look more beautiful than its looking now.

After these all simple works we are now going to create a database and a table to store all data in the database of new users. Before we go to create a table we should know that what we require from the user. As we designed the form we will create the table according to the registration form which you can see it on Figure 1 & 2.

Listing 3 : Query for table in MySQL

CREATE TABLE WebsiteUsers (userID int(9) NOT NULL auto_increment, fullname VARCHAR(50) NOT NULL, userName VARCHAR(40) NOT NULL, email VARCHAR(40) NOT NULL, pass VARCHAR(40) NOT NULL, PRIMARY KEY(userID));

Description of Listing 3:

One thing you should know that if you don’t have MySQL facility to use this query, so should follow my previous article about . from this link you will able to understand the installation and requirements. And how we can use it.

In the listing 3 query we used all those things which we need for the registration form. As there is Email, Full name, password, and user name variables. These variable will store data of the user, which he/she will input in the registration form in Figure 2 for the sing-up.

After these all works we are going to work with PHP programming which is a server side programming language. That’s why need to create a connection with the database.

Listing 4 : Database connection

Description of Listing 4:

We created a connection between the database and our webpages. But if you don’t know is it working or not so you use one thing more in the last check listing 5 for it.

Listing 5 : checking the connection of database connectivity

Description Listing 5:

In the Listing 5 I just tried to show you that you can check and confirm the connection between the database and PHP. And one thing more we will not use Listing 5 code in our sing-up webpage. Because it’s just to make you understand how you can check the MySQL connection.

Now we will write a PHP programming application to first check the availability of user and then store the user if he/she is a new user on the webpage.

Listing 6 : connectivity-sign-up.php

Description of connectivity-sign-up.php

In this PHP application I used simplest way to create a sign up application for the webpages. As you can see first we create a connection like listing 4. And then we used two functions the first function is SignUP() which is being called by the if statement from the last of the application, where its first confirming the pressing of sign up button. If it is pressed then it will call the SingUp function and this function will use a query of SELECT to fetch the data and compare them with userName and email which is currently entered from the user. If the userName and email is already present in the database so it will say sorry you are already registered

If the user is new as its currently userName and email ID is not present in the database so the If statement will call the NewUser() where it will store the all information of the new user. And the user will become a part of the webpage.



Figure 3

In the figure 3, user is entering data to sign up if the user is an old user of this webpage according to the database records. So the webpage will show a message the user is registered already if the user is new so the webpage will show a message the user’s registration is completed.



Figure 4:

As we entered data to the registration form (Figure 4), according to the database which userName and email we entered to the registration form for sing-up it’s already present in the database. So we should try a new userName and email address to sign-up with a new ID and Password.



Figure 5

In figure 5, it is confirming us that which userName and email id user has entered. Both are not present in the database records. So now a new ID and Password is created and the user is able to use his new ID and Password to get login next time.

Conclusion:

In this article we learnt the simplest way of creating a sign up webpage. We also learnt that how it deals with the database if we use PHP and MySQL. I tried to give you a basic knowledge about sign up webpage functionality. How it works at back end, and how we can change its look on front end. For any query don’t hesitate and comment.

Если вам необходимо сделать один из разделов своего сайта доступным ограниченному, но неопределенному кругу лиц, проще всего это сделать с помощью регистрации и авторизации пользователей. Есть множество способов авторизации пользователей. Можно использовать как инструменты веб-сервера, так и инструменты языка программирования. Мы поговорим о случае, когда используются сессии PHP .

Вероятно, вы хотели бы увидеть более современный способ создания такой формы. Полное его современное и актуальное представление у меня пока что еще в планах, но зато вы можете увидеть, что форму обратной связи можно построить с помощью объектно-ориентированных приемов в PHP.

Для начала давайте оговорим все шаги, которые сделаем далее. Что нам вообще нужно? Нам нужен сценарий, который будет регистрировать пользователя, авторизовать пользователя, переадресовывать пользователя куда-либо после авторизации. Также нам нужно будет создать страницу, которая будет защищена от доступа неавторизованных пользователей. Для регистрации и авторизации нам необходимо будет создать HTML -формы. Информацию о зарегистрированных пользователях мы будем хранить в базе данных. Это значит, что нам еще нужен скрипт подключения к СУБД . Всю работу у нас будут выполнять функции, которые мы сами напишем. Эти функции мы сохраним в отдельный файл.

Итак, нам нужны следующие файлы:

  • соединение с СУБД;
  • пользовательские функции;
  • авторизация;
  • регистрация;
  • защищенная страница;
  • сценарий завершения работы пользователя;
  • сценарий, проверяющий статус авторизации пользователя;
  • таблица стилей для простейшего оформления наших страниц.

Всё это будет бессмысленно, если у вас нет соответствующей таблицы в базе данных. Запустите инструмент управления своим СУБД (PhpMyAdmin или командную строку, как удобнее) и выполните в нем следующий запрос:

CREATE TABLE `users` (`id` int(11) NOT NULL AUTO_INCREMENT, `login` char(16) NOT NULL, `password` char(40) NOT NULL, `reg_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Наши файлы со сценариями я назову так (все они будут лежать в одном каталоге):

  • database.php;
  • functions.php;
  • login.php;
  • registration.php;
  • index.php;
  • logout.php;
  • checkAuth.php;
  • style.css.

Назначение каждого из них, я уверен, вам понятно. Начнем со скрипта соединения с СУБД. Вы его уже видели . Просто сохраните код этого скрипта в файле с именем database.php . Пользовательские функции мы будем объявлять в файле functions.php . Как это всё будет работать? Неавторизованный пользователь пытается получить доступ к защищенному документу index.php , система проверяет авторизован ли пользователь, если пользователь не авторизован, он переадресовывается на страницу авторизации. На странице авторизации пользователь должен видеть форму авторизации. Давайте сделаем её.

Авторизация пользователей

зарегистрируйтесь.

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

/* файл style.css */ .row { margin-bottom:10px; width:220px; } .row label { display:block; font-weight:bold; } .row input.text { font-size:1.2em; padding:2px 5px; } .to_reg { font-size:0.9em; } .instruction { font-size:0.8em; color:#aaaaaa; margin-left:2px; cursor:default; } .error { color:red; margin-left:3px; }

Если всё сделано верно, у вас в броузере должно быть следующее:

Конечно же у нас нет пока ни одного зарегистрированного пользователя, и чтобы авторизоваться, нужно зарегистрироваться. Давайте сделаем форму регистрации.

Регистрация пользователей

" />

Вы, наверное, обратили внимание на то, что в HTML -коде присутствуют переменные PHP . Они являются содержимым атрибутов текстовых полей форм, содержимом контейнеров, предназначенных для вывода ошибок. Но мы не инициализировали эти переменные. Давайте сделаем это.

Регистрация пользователей

" />
В имени пользователя могут быть только символы латинского алфавита, цифры, символы "_", "-", ".". Длина имени пользователя должна быть не короче 4 символов и не длиннее 16 символов
В пароле вы можете использовать только символы латинского алфавита, цифры, символы "_", "!", "(", ")". Пароль должен быть не короче 6 символов и не длиннее 16 символов
Повторите введенный ранее пароль

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

Нам нужно, чтобы поля логина и пароля не были пустыми. Затем необходимо проверить логин на соответствие требованиям. Пароль также должен соответствовать описанным требованиям, а повторно указанный пароль должен с ним совпадать и, кроме того, они должны быть идентичны. Если какое-то из этих условий не выполняется, обработка данных формы должна быть прекращена, в массив сообщений об ошибке должно быть записано соответствующее оповещение, и оно должно быть отображено пользвателю. Для удобства пользователя мы сохраним введенный им логин (если он его указал), записав его значение в массив $fields .

Если всё нормально, в окне вашего броузера, обратившись к документу registration.php, вы должны увидеть примерно такую форму:

Теперь, допустим, пользователь нажал на кнопку регистрации, не заполнил поля формы. Согласно нашему алгоритму, логин и пароль не могут быть пустыми. Если это условие не выполняется, регистрация невозможно. Мы помним о том, что обработка данных формы происходит в текущем сценарии. Значит нам нужно изменить его код, добавив соответствующие проверки. Сразу же оговорим и следующие проверки. Если введены и логин, и пароль, нужно проверить их соответствие указанным требованиям. Для проверки логина и пароля мы создадим пользовательские функции в файле functions.php.

/** * functions.php * Файл с пользовательскими функциями */ // Подключаем файл с параметрами подключения к СУБД require_once("database.php"); // Проверка имени пользователя function checkLogin($str) { // Инициализируем переменную с возможным сообщением об ошибке $error = ""; // Если отсутствует строка с логином, возвращаем сообщение об ошибке if(!$str) { $error = "Вы не ввели имя пользователя"; return $error; } /** * Проверяем имя пользователя с помощью регулярных выражений * Логин должен быть не короче 4, не длиннее 16 символов * В нем должны быть символы латинского алфавита, цифры, * в нем могут быть символы "_", "-", "." */ $pattern = "/^[-_.a-z\d]{4,16}$/i"; $result = preg_match($pattern, $str); // Если проверка не прошла, возвращаем сообщение об ошибке if(!$result) { $error = "Недопустимые символы в имени пользователя или имя пользователя слишком короткое (длинное)"; return $error; } // Если же всё нормально, вернем значение true return true; } // Проверка пароля пользователя function checkPassword($str) { // Инициализируем переменную с возможным сообщением об ошибке $error = ""; // Если отсутствует строка с логином, возвращаем сообщение об ошибке if(!$str) { $error = "Вы не ввели пароль"; return $error; } /** * Проверяем пароль пользователя с помощью регулярных выражений * Пароль должен быть не короче 6, не длиннее 16 символов * В нем должны быть символы латинского алфавита, цифры, * в нем могут быть символы "_", "!", "(", ")" */ $pattern = "/^[_!)(.a-z\d]{6,16}$/i"; $result = preg_match($pattern, $str); // Если проверка не прошла, возвращаем сообщение об ошибке if(!$result) { $error = "Недопустимые символы в пароле пользователя или пароль слишком короткий (длинный)"; return $error; } // Если же всё нормально, вернем значение true return true; }

Теперь нам нужно изменить файл registration.php, чтобы задействовать объявленные нами функции. В сценарий мы добавим условие, проверяющее нажатие кнопки регистрации. Внутри этого условия запускается проверка логина и паролей. В случае, если какая-то из проверок завершается неудачей, мы вновь отображаем форму, и выводим сообщение об ошибке. Если ошибок нет, мы регистрируем пользователя, форму регистрации при этом уже не отображаем, сообщаем пользователю об успешной регистрации, и с помощью функции header() переадресовываем его к форме авторизации.

Вы успешно зарегистрировались в системе. Сейчас вы будете переадресованы к странице авторизации. Если это не произошло, перейдите на неё по прямой ссылке.

"; header("Refresh: 5; URL = login.php"); } // Иначе сообщаем пользователю об ошибке else { $errors["full_error"] = $reg; } } } ?> Регистрация пользователей
" />
В имени пользователя могут быть только символы латинского алфавита, цифры, символы "_", "-", ".". Длина имени пользователя должна быть не короче 4 символов и не длиннее 16 символов
В пароле вы можете использовать только символы латинского алфавита, цифры, символы "_", "!", "(", ")". Пароль должен быть не короче 6 символов и не длиннее 16 символов
Повторите введенный ранее пароль

В скрипте вы должны были заметить еще одну новую функцию — registration() . А мы её еще не объявляли. Давайте сделаем это.

// Функция регистрации пользователя function registration($login, $password) { // Инициализируем переменную с возможным сообщением об ошибке $error = ""; // Если отсутствует строка с логином, возвращаем сообщение об ошибке if(!$login) { $error = "Не указан логин"; return $error; } elseif(!$password) { $error = "Не указан пароль"; return $error; } // Проверяем не зарегистрирован ли уже пользователь // Подключаемся к СУБД connect(); // Пишем строку запроса $sql = "SELECT `id` FROM `users` WHERE `login`="" . $login . """; // Делаем запрос к базе $query = mysql_query($sql) or die(""); // Смотрим на количество пользователей с таким логином, если есть хоть один, // возвращаем сообщение об ошибке if(mysql_num_rows($query) > 0) { $error = "Пользователь с указанным логином уже зарегистрирован"; return $error; } // Если такого пользователя нет, регистрируем его // Пишем строку запроса $sql = "INSERT INTO `users` (`id`,`login`,`password`) VALUES (NULL, "" . $login . "","" . $password . "")"; // Делаем запрос к базе $query = mysql_query($sql) or die("

Невозможно добавить пользователя: " . mysql_error() . ". Ошибка произошла в строке " . __LINE__ . "

"); // Не забываем отключиться от СУБД mysql_close(); // Возвращаем значение true, сообщающее об успешной регистрации пользователя return true; }

Если всё нормально, ваш пользователь будет зарегистрирован. Можете потестировать форму. Попробуйте зарегистрировать пользователей с одинаковыми логинами. После успешной регистрации пользователь будет перееадресован к форме авторизации. Ранее мы просто создали разметку для отображения этой формы. Так как в её атрибуте action не указан никакой параметр, данные, отправленные формой, будут обрабатываться в этом же сценарии. Значит нам нужно написать код для обработки, и добавить его в документ login.php.

Авторизация пользователей

;">

Если вы не зарегистрированы в системе, зарегистрируйтесь.

Вы, наверное, заметили, что в скрипте авторизации у нас появилась ещё одна незнакомая функция — authorization() . Эта функция должна авторизовать пользователя, предварительно проверив, существует ли в базе данных зарегистрированный пользователь с таким логином и паролем. Если такой пользователь не будет найден, авторизация будет прервана, на экран будет выведено сообщение о неудаче. При успешной проверки функция authorization() запустит сессию, и запишет в неё значения логина и пароля пользователя, сообщит сценарию об успешности авторизации, и сценарий перенаправит пользователя на защищенную страницу ресурса.

/** * Функция авторизации пользователя. * Авторизация пользователей у нас будет осуществляться * с помощью сессий PHP. */ function authorization($login, $password) { // Инициализируем переменную с возможным сообщением об ошибке $error = ""; // Если отсутствует строка с логином, возвращаем сообщение об ошибке if(!$login) { $error = "Не указан логин"; return $error; } elseif(!$password) { $error = "Не указан пароль"; return $error; } // Проверяем не зарегистрирован ли уже пользователь // Подключаемся к СУБД connect(); // Нам нужно проверить, есть ли такой пользователь среди зарегистрированных // Составляем строку запроса $sql = "SELECT `id` FROM `users` WHERE `login`="".$login."" AND `password`="".$password."""; // Выполняем запрос $query = mysql_query($sql) or die("

Невозможно выполнить запрос: " . mysql_error() . ". Ошибка произошла в строке " . __LINE__ . "

"); // Если пользователя с такими данными нет, возвращаем сообщение об ошибке if(mysql_num_rows($query) == 0) { $error = "Пользователь с указанными данными не зарегистрирован"; return $error; } // Если пользователь существует, запускаем сессию session_start(); // И записываем в неё логин и пароль пользователя // Для этого мы используем суперглобальный массив $_SESSION $_SESSION["login"] = $login; $_SESSION["password"] = $password; // Не забываем закрывать соединение с базой данных mysql_close(); // Возвращаем true для сообщения об успешной авторизации пользователя return true; }

Когда пользователь попадает на защищенную страницу, следует проверить корректность данных о его авторизации. Для этого нам потребуется еще одна пользовательская функция. Назовем её checkAuth() . Её задачей будет сверка данных авторизации пользователя с теми, которые хранятся в нашей базе. Если данные не совпадут, пользователь будет перенаправлен на страницу авторизации.

Function checkAuth($login, $password) { // Если нет логина или пароля, возвращаем false if(!$login || !$password) return false; // Проверяем зарегистрирован ли такой пользователь // Подключаемся к СУБД connect(); // Составляем строку запроса $sql = "SELECT `id` FROM `users` WHERE `login`="".$login."" AND `password`="".$password."""; // Выполняем запрос $query = mysql_query($sql) or die("

Невозможно выполнить запрос: " . mysql_error() . ". Ошибка произошла в строке " . __LINE__ . "

"); // Если пользователя с такими данными нет, возвращаем false; if(mysql_num_rows($query) == 0) { return false; } // Не забываем закрывать соединение с базой данных mysql_close(); // Иначе возвращаем true return true; }

Теперь, когда пользователь попал на защищенную страницу, мы должны вызвать функцию проверки данных авторизации. Сценарий вызова и проверки мы поместим в отдельный файл checkAuth.php и будем подключать его к тем страницам, которые будут закрытыми для общего доступа.

/** * Скрипт проверки авторизации пользователей */ // Запускаем сессию, из которой будем извлекать логин и пароль // авторизовавшихся пользователей session_start(); // Подлючаем файл с пользовательскими функциями require_once("functions.php"); /** * Чтобы определить авторизован ли пользователь, нам нужно * проверить существуют ли в базе данных записи для его логина * и пароля. Для этого воспользуемся пользовательской функцией * проверки корректности данных авторизовавшегося пользователя. * Если эта функция вернет false, значит авторизации нет. * При отсутствии авторизации мы просто переадресовываем * пользователя к странице авторизации. */ // Если в сессии присуствуют данные и о логине, и о пароле, // проверяем их if(isset($_SESSION["login"]) && $_SESSION["login"] && isset($_SESSION["password"]) && $_SESSION["password"]) { // Если проверка существующих данных завершается неудачей if(!checkAuth($_SESSION["login"], $_SESSION["password"])) { // Переадресовываем пользователя на страницу авторизации header("location: login.php"); // Прекращаем выполнение скрипта exit; } } // Если данных либо о логине, либо о пароле пользователя нет, // считаем что авторизации нет, переадресовываем пользователя // на страницу авторизации else { header("location: login.php"); // Прекращаем выполнение сценария exit; }

А теперь давайте создадим код нашей защищенной страницы. Он будет довольно-таки прост.

Авторизация и регистрация пользователей

Успешная авторизация.

Вы получили доступ к защищенной странице. Вы можете выйти из системы.

Как видите, в защищенном документе мы подключаем только один файл — checkAuth.php. Все остальные файлы подключаются уже в других сценариях. Поэтому наш код не выглядит громоздким. Регистрацию и авторизацию пользователей мы организовали. Теперь необходимо позволить пользователям выходить из системы. Для этого мы создадим сценарий в файле logout.php.

/** * Скрипт выхода пользователя из системы. Так как пользователи * авторизуются через сессии, их логин и пароль хранятся * в суперглобаном массиве $_SESSION. Чтобы осуществить * выход из системы, достаточно просто уничтожить значения * массива $_SESSION["login"] и $_SESSION["password"], после * чего мы переадресовываем пользователя к странице авторизации */ // Обязательно запускаем сессию session_start(); unset($_SESSION["login"]); unset($_SESSION["password"]); header("location: login.php");

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

P.S. Я в курсе, что лучше писать объектно-ориентированный код, знаю, что передавать и хранить пароль в открытом виде не стоит, что информацию, заносимую в базу данных, необходимо предварительно проверять. Знаю. Об этом я здесь не буду говорить.

Процесс создания системы регистрации – это довольно большой объем работы. Вам нужно написать код, который бы перепроверял валидность email-адресов, высылал email-письма с подтверждением, предлагал возможность восстановить пароль, хранил бы пароли в безопасном месте, проверял формы ввода и многое другое. Даже когда вы все это сделаете, пользователи будут регистрироваться неохотно, так как даже самая минимальная регистрация требует их активности.

В сегодняшнем руководстве мы займемся разработкой простой системы регистрации, с использованием которой вам не понадобятся никакие пароли! В результаты мы получим, систему, которую можно будет без труда изменить или встроить в существующий PHP-сайт. Если вам интересно, продолжайте чтение.

PHP

Теперь мы готовы к тому, чтобы заняться кодом PHP. Основной функционал системы регистрации предоставляется классом User, который вы можете видеть ниже. Класс использует (), представляющую собой минималистскую библиотеку для работы с базами данных. Класс User отвечает за доступ к базам данных, генерирование token-ов для логина и их валидации. Он представляет нам простой интерфейс, который можно без труда включить в систему регистрации на ваших сайтах, основанных на PHP.

User.class.php

// Private ORM instance
private $orm;

/**
* Find a user by a token string. Only valid tokens are taken into
* consideration. A token is valid for 10 minutes after it has been generated.
* @param string $token The token to search for
* @return User
*/

Public static function findByToken($token){

// find it in the database and make sure the timestamp is correct


->where("token", $token)
->where_raw("token_validity > NOW()")
->find_one();

If(!$result){
return false;
}

Return new User($result);
}

/**
* Either login or register a user.
* @return User
*/

Public static function loginOrRegister($email){

// If such a user already exists, return it

If(User::exists($email)){
return new User($email);
}

// Otherwise, create it and return it

Return User::create($email);
}

/**
* Create a new user and save it to the database
* @param string $email The user"s email address
* @return User
*/

Private static function create($email){

// Write a new user to the database and return it

$result = ORM::for_table("reg_users")->create();
$result->email = $email;
$result->save();

Return new User($result);
}

/**
* Check whether such a user exists in the database and return a boolean.
* @param string $email The user"s email address
* @return boolean
*/

Public static function exists($email){

// Does the user exist in the database?
$result = ORM::for_table("reg_users")
->where("email", $email)
->count();

Return $result == 1;
}

/**
* Create a new user object
* @param $param ORM instance, id, email or null
* @return User
*/

Public function __construct($param = null){

If($param instanceof ORM){

// An ORM instance was passed
$this->orm = $param;
}
else if(is_string($param)){

// An email was passed
$this->
->where("email", $param)
->find_one();
}
else{

If(is_numeric($param)){
// A user id was passed as a parameter
$id = $param;
}
else if(isset($_SESSION["loginid"])){

// No user ID was passed, look into the sesion
$id = $_SESSION["loginid"];
}

$this->orm = ORM::for_table("reg_users")
->where("id", $id)
->find_one();
}

/**
* Generates a new SHA1 login token, writes it to the database and returns it.
* @return string
*/

Public function generateToken(){
// generate a token for the logged in user. Save it to the database.

$token = sha1($this->email.time().rand(0, 1000000));

// Save the token to the database,
// and mark it as valid for the next 10 minutes only

$this->orm->set("token", $token);
$this->orm->set_expr("token_validity", "ADDTIME(NOW(),"0:10")");
$this->orm->save();

Return $token;
}

/**
* Login this user
* @return void
*/

Public function login(){

// Mark the user as logged in
$_SESSION["loginid"] = $this->orm->id;

// Update the last_login db field
$this->orm->set_expr("last_login", "NOW()");
$this->orm->save();
}

/**
* Destroy the session and logout the user.
* @return void
*/

Public function logout(){
$_SESSION = array();
unset($_SESSION);
}

/**
* Check whether the user is logged in.
* @return boolean
*/

Public function loggedIn(){
return isset($this->orm->id) && $_SESSION["loginid"] == $this->orm->id;
}

/**
* Check whether the user is an administrator
* @return boolean
*/

Public function isAdmin(){
return $this->rank() == "administrator";
}

/**
* Find the type of user. It can be either admin or regular.
* @return string
*/

Public function rank(){
if($this->orm->rank == 1){
return "administrator";
}

Return "regular";
}

/**
* Magic method for accessing the elements of the private
* $orm instance as properties of the user object
* @param string $key The accessed property"s name
* @return mixed
*/

Public function __get($key){
if(isset($this->orm->$key)){
return $this->orm->$key;
}

Return null;
}
}
Token-ы генерируются при помощи алгоритма , и сохраняются в базу данных. Мы используем из MySQL для установки значения в колонку token_validity, равного 10 минутам. При валидации token, мы сообщаем движку, что нам нужен token, поле token_validity пока еще не истекло. Таким образом мы ограничиваем время, в течение которого token будет валиден.

Обратите внимание на то, что мы используем волшебный метод __get () в конце документа, чтобы получить доступ к свойствам объекта user. Это позволяет нам осуществить доступ к данным, которые хранятся в базе данных в виде свойств: $user->email, $user->token. Для примера давайте посмотрим, как мы можем использовать этот класс в следующем фрагменте кода:


Еще один файл, в котором хранится необходимый функционал, это functions.php. Там у нас есть несколько вспомогательных функций, которые позволяют нам сохранить остальной код более опрятным.

Functions.php

Function send_email($from, $to, $subject, $message){

// Helper function for sending email

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/plain; charset=utf-8" . "\r\n";
$headers .= "From: ".$from . "\r\n";

Return mail($to, $subject, $message, $headers);
}

function get_page_url(){

// Find out the URL of a PHP file

$url = "http".(empty($_SERVER["HTTPS"])?"":"s")."://".$_SERVER["SERVER_NAME"];

If(isset($_SERVER["REQUEST_URI"]) && $_SERVER["REQUEST_URI"] != ""){
$url.= $_SERVER["REQUEST_URI"];
}
else{
$url.= $_SERVER["PATH_INFO"];
}

Return $url;
}

function rate_limit($ip, $limit_hour = 20, $limit_10_min = 10){

// The number of login attempts for the last hour by this IP address

$count_hour = ORM::for_table("reg_login_attempt")
->
->where_raw("ts > SUBTIME(NOW(),"1:00")")
->count();

// The number of login attempts for the last 10 minutes by this IP address

$count_10_min = ORM::for_table("reg_login_attempt")
->where("ip", sprintf("%u", ip2long($ip)))
->where_raw("ts > SUBTIME(NOW(),"0:10")")
->count();

If($count_hour > $limit_hour || $count_10_min > $limit_10_min){
throw new Exception("Too many login attempts!");
}
}

function rate_limit_tick($ip, $email){

// Create a new record in the login attempt table

$login_attempt = ORM::for_table("reg_login_attempt")->create();

$login_attempt->email = $email;
$login_attempt->ip = sprintf("%u", ip2long($ip));

$login_attempt->save();
}

function redirect($url){
header("Location: $url");
exit;
}
Функции rate_limit и rate_limit_tick позволяют нам ограничивать число попыток авторизации на определенный промежуток времени. Попытки авторизации записываются в базу данных reg_login_attempt. Эти функции запускаются при проведении подтверждения формы авторизации, как можно видеть в следующем фрагменте кода.

Нижеприведенный код был взят из index.php, и он отвечает за подтверждение формы авторизации. Он возвращает JSON-ответ, который управляется кодом jQuery, который мы видели в assets/js/script.js.

index.php

If(!empty($_POST) && isset($_SERVER["HTTP_X_REQUESTED_WITH"])){

// Output a JSON header

Header("Content-type: application/json");

// Is the email address valid?

If(!isset($_POST["email"]) || !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
throw new Exception("Please enter a valid email.");
}

// This will throw an exception if the person is above
// the allowed login attempt limits (see functions.php for more):
rate_limit($_SERVER["REMOTE_ADDR"]);

// Record this login attempt
rate_limit_tick($_SERVER["REMOTE_ADDR"], $_POST["email"]);

// Send the message to the user

$message = "";
$email = $_POST["email"];
$subject = "Your Login Link";

If(!User::exists($email)){
$subject = "Thank You For Registering!";
$message = "Thank you for registering at our site!\n\n";
}

// Attempt to login or register the person
$user = User::loginOrRegister($_POST["email"]);

$message.= "You can login from this URL:\n";
$message.= get_page_url()."?tkn=".$user->generateToken()."\n\n";

$message.= "The link is going expire automatically after 10 minutes.";

$result = send_email($fromEmail, $_POST["email"], $subject, $message);

If(!$result){
throw new Exception("There was an error sending your email. Please try again.");
}

Die(json_encode(array(
"message" => "Thank you! We\"ve sent a link to your inbox. Check your spam folder as well."
)));
}
}
catch(Exception $e){

Die(json_encode(array(
"error"=>1,
"message" => $e->getMessage()
)));
}
При успешной авторизации или регистрации, вышеприведенный код отсылает email человеку с ссылкой для авторизации. Token (лексема) становится доступной в качестве $_GET-переменной "tkn" ввиду сгенерированного URL.

index.php

If(isset($_GET["tkn"])){

// Is this a valid login token?
$user = User::findByToken($_GET["tkn"]);

// Yes! Login the user and redirect to the protected page.

$user->login();
redirect("protected.php");
}

// Invalid token. Redirect back to the login form.
redirect("index.php");
}
Запуск $user->login() создаст необходимые переменные для сессии, что позволит пользователю оставаться авторизованным при последующих входах.

Выход из системы реализуется примерно таким же образом:

Index.php

If(isset($_GET["logout"])){

$user = new User();

If($user->loggedIn()){
$user->logout();
}

Redirect("index.php");
}
В конце кода мы снова перенаправляем пользователя на index.php, поэтому параметр?logout=1 в URL исключается.

Нашему файлу index.php также потребуется защита – мы не хотим, чтобы уже авторизованные пользователи видели форму. Для этого мы используем метод $user->loggedIn():

Index.php

$user = new User();

if($user->loggedIn()){
redirect("protected.php");
}
Наконец, давайте посмотрим, как можно защитить страницу вашего сайта, и сделать ее доступной только после авторизации:

protected.php

// To protect any php page on your site, include main.php
// and create a new User object. It"s that simple!

require_once "includes/main.php";

$user = new User();

if(!$user->loggedIn()){
redirect("index.php");
}
После этой проверки вы можете быть уверены в том, что пользователь успешно авторизовался. У вас также будет доступ к данным, которые хранятся в базе данных в качестве свойств объекта $user. Чтобы вывести email пользователя и их ранг, воспользуйтесь следующим кодом:

Echo "Your email: ".$user->email;
echo "Your rank: ".$user->rank();
Здесь rank() – это метод, так как колонка rank в базе данных обычно содержит числа (0 для обычных пользователей и 1 для администраторов), и нам нужно преобразовать это все в названия рангов, что реализуется при помощи данного метода. Чтобы преобразовать обычного пользователя в администратора, просто отредактируйте запись о пользователе в phpmyadmin (либо в любой другой программе по работе с базами данных). Будучи администратором, пользователь не будет наделен какими-то особыми возможностями. Вы сами в праве выбирать, каким правами наделять администраторов.

Готово!

На этом наша простенькая система регистрации готова! Вы можете использовать ее на уже существующем PHP-сайте, либо модернизировать ее, придерживаясь собственных требований.

Вверх