Программы. Игры. Браузеры. Windows. Архиваторы
  • Главная
  • Одноклассники
  • Простая система регистрации пользователей. Создаем невероятную простую систему регистрации на PHP и MySQL Php скрипт регистрации

Простая система регистрации пользователей. Создаем невероятную простую систему регистрации на PHP и MySQL Php скрипт регистрации

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.

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

Позволяет регистрировать переменные, полученные из GET-запроса . Допустим, был такой запрос: index.php?a=15 . Таким образом, безусловно, создаётся переменная $_GET["a"] и переменная a . Вот создание переменной a и произошло в результате включённой директивы register_globals .

Теперь о том, почему данную директиву надо всегда держать отключённой. Предположим, что Вы делаете авторизацию пользователя, и Вы написали такой код:

Теперь если файл называется, например, auth.php , то, обратившись к нему следующим образом: auth.php?check_user=1 , то получится успешная авторизация, независимо от того, какие логин и пароль были отправлены и были ли отправлены вообще.

Безусловно, данный пример является слегка мистическим, поскольку так никто не пишет (хотя бы из-за отсутствия else $check_user = false; ), однако, данный пример наглядно показывает, к чему может привести включённая директива register_globals .

Теперь о том, как же отключить директиву register_globals . Для этого надо добавить в файл .htaccess всего одну строчку:

Php_value register_globals 0

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

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.

Reg.ru: домены и хостинг

Крупнейший регистратор и хостинг-провайдер в России.

Более 2 миллионов доменных имен на обслуживании.

Продвижение, почта для домена, решения для бизнеса.

Более 700 тыс. клиентов по всему миру уже сделали свой выбор.

*Наведите курсор мыши для приостановки прокрутки.

Назад Вперед

Создание простой системы регистрации пользователей на PHP и MySQL

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

И даже после того как вы всё это напишите, пользователи будут регистрироваться неохотно, т.к. это требует определённых усилий с их стороны.

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



Вот как наша супер простая система будет работать:

Мы скомбинируем форму авторизации и регистрацию. В этой форме будет поле для ввода email-адреса и кнопка регистрации;
- При заполнении поля email-адресом, по нажатию на кнопку регистрации будет создана запись о новом пользователе, но только в том случае, если введённого email-адреса не было найдено в базе данных.

После этого создаётся некий случайный уникальный набор символов (токен), который отправляется на указанную пользователем почту в виде ссылки, которая будет актуальна в течение 10 минут;
- По ссылке пользователь переходит на наш сайт. Система определяет наличие токена и авторизует пользователя;

Преимущества такого подхода:

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

Недостатки:

Безопасность аккаунта пользователя. Если кто-то имеет доступ к почте пользователя, он может авторизоваться.
- Email не защищён и может быть перехвачен. Имейте в виду, что этот вопрос актуален и в случае, когда пароль был забыт и его необходимо восстановить, или в любой системе авторизации, которая не использует HTTPS для передачи данных (логин/пароль);
- Пока вы настроите как нужно почтовый сервер, существует шанс, что сообщения со ссылками на авторизацию будут попадать в спам;

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

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

Как пользоваться этой системой

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

Вам нужно скачать исходники, приложенные к уроку
- В архиве найти файл tables.sql Импортируйте его в вашу базу данных используя опцию импорта в phpMyAdmin. Альтернативный способ: открыть этот файл через текстовый редактор, скопировать SQL запрос и выполнить его;
- Открыть includes/main.php и заполнить настройки связи с вашей базой данных (указать пользователя и пароль для связи с базой а также хост и имя базы). В этом же файле, вы также должны указать email, который будет использован в качестве оригинального адреса для сообщений отправляемых системой. Некоторые хосты блокируют исходящие мейлы пока в форме не будет указан настоящий email адрес, который был создан из панели управления хостом, так что укажите реальный адрес;
- Загрузите все файлы index.php , protected.php и папки assets и includes через FTP на ваш хост;
- Добавьте код ниже на каждую PHP-страницу, где нужно отобразить форму авторизации;

Require_once "includes/main.php"; $user = new User(); if(!$user->loggedIn()){ redirect("index.php"); }
- Готово!

Для тех же, кому интересно, как это всё работает - вперёд к чтению ниже!

Первый шаг - написание HTM- кода формы авторизации. Данный код располагается в файле index.php . Этот файл также содержит PHP-код, обрабатывающий данные формы и другие полезные функции системы авторизации. Узнать об этом больше можно в разделе ниже, посвящённом обзору PHP кода.

index.php

Tutorial: Super Simple Registration System With PHP & MySQL Login or Register

Enter your email address above and we will send
you a login link.

Login / Register

В головной секции (между тегами и ) я подключил основные стили (в этом уроке они не разбираются, поэтому вы можете посмотреть их сами. Папка assets/css/style.css). До закрывающего тега я подключил библиотеку jQuery и файл script.js, который мы напишем и разберём чуть ниже.


JavaScript

jQuery отслеживает состояние кнопки "Зарегистрироваться/авторизоваться" с помощью функции e.preventDefault() и отправляет AJAX-запросы. В зависимости от ответа сервера, выводит то или иное сообщение и определяет дальнейшие действия/

assets/js/script.js

$(function(){ var form = $("#login-register"); form.on("submit", function(e){ if(form.is(".loading, .loggedIn")){ return false; } var email = form.find("input").val(), messageHolder = form.find("span"); e.preventDefault(); $.post(this.action, {email: email}, function(m){ if(m.error){ form.addClass("error"); messageHolder.text(m.message); } else{ form.removeClass("error").addClass("loggedIn"); messageHolder.text(m.message); } }); }); $(document).ajaxStart(function(){ form.addClass("loading"); }); $(document).ajaxComplete(function(){ form.removeClass("loading"); }); });

был добавлен в форму для отображения текущего состояния AJAX-запроса (это стало возможным благодаря методам ajaxStart() ) и ajaxComplete() , которые вы сможете найти ближе к концу файла).

Этот класс показывает крутящийся анимированный gif-файл (как бы намекающий нам на то, что запрос обрабатывается), и также выступает как флаг, предотвращающий повторную отправку формы (когда кнопка зарегистрироваться была уже однажды нажата). Класс .loggedIn - это другой флаг, - устанавливается тогда, когда был отправлен email. Этот флаг моментально блокирует любые дальнейшие действия с формой.

Схема базы данных

Наша невероятно простая система регистрации использует 2 MySQL таблицы (SQL-код находится в файле tables.sql ). Первая хранит данные об аккаунтах пользователей. Вторая хранит информацию о количестве попыток входа.


Схема таблицы пользователей.

Система не использует паролей, что видно на схеме. На ней же можно увидеть колонку token с токенами, соседствующую с колонкой token_validity . Токен устанавливается как только пользователь подключается к системе, задаёт свой email для отправки сообщения (чуть подробнее об этом в следующем блоке). Колонка token_validity устанавливает время на 10 минут позже, после которого токен перестаёт быть актуальным.


Схема таблицы, считающая количество попыток авторизации.

В обоих таблицах IP-адрес хранится в обработанном виде, с помощью функции ip2long в поле типа integer.

Теперь мы можем написать немножко PHP-кода. Основной функционал системы возложен на класс User.class.php , который вы можете видеть ниже.

Данный класс активно использует idorm (docs), эти библиотеки являются минимально необходимыми инструментами, для работы с базами данных. Он обрабатывает доступ к базе данных, генерацию токенов и их валидацию. Он представляет собой простой интерфейс, позволяющий легко подключить систему регистрации к вашему сайту, если он использует PHP.

User.class.php

Class User{ // Частный ORM случай private $orm; /** * Найти пользователя по токену. Только валидные токены, приняты к рассмотрению. Токен генерируется только на 10 минут с того момента как был создан * @param string $token. Это искомый токен * @return User. Вернуть значение функции User */ public static function findByToken($token){ // найти токен в базе и убедиться, что установлен корректный временной штамп $result = ORM::for_table("reg_users") ->where("token", $token) ->where_raw("token_validity > NOW()") ->find_one(); if(!$result){ return false; } return new User($result); } /** * Авторизовать или зарегистрировать пользователя * @param string $email. Пользовательский email-адрес * @return User */ public static function loginOrRegister($email){ // Если такой пользователь уже существует, вернуть значение функции User от заданного email-адреса хранимого в базе if(User::exists($email)){ return new User($email); } // В противном случае создать нового пользователя в базе и вернуть значение функции User::create от указанного email return User::create($email); } /** * Создать нового пользователя и сохранить в базу * @param string $email. Пользовательский email-адрес * @return User */ private static function create($email){ // Записать нового пользователя и вернуть результат функции User от этих значений $result = ORM::for_table("reg_users")->create(); $result->email = $email; $result->save(); return new User($result); } /** * Проверить, существует ли такой пользователь в базе и вернуть булево значение переменной * @param string $email. Пользовательский email-адрес * @return boolean */ public static function exists($email){ // Существует ли пользователь в базе? $result = ORM::for_table("reg_users") ->where("email", $email) ->count(); return $result == 1; } /** * Создать новый пользовательский объект * @param экземпляр $param ORM , id, email or 0 * @return User */ public function __construct($param = null){ if($param instanceof ORM){ // ORM проверка пройдена $this->orm = $param; } else if(is_string($param)){ // Проверка на email пройдена $this->orm = ORM::for_table("reg_users") ->where("email", $param) ->find_one(); } else{ $id = 0; if(is_numeric($param)){ // идентификатору пользователя передаётся значение переменной $param $id = $param; } else if(isset($_SESSION["loginid"])){ // В противном случае смотри сессию $id = $_SESSION["loginid"]; } $this->orm = ORM::for_table("reg_users") ->where("id", $id) ->find_one(); } } /** * Сгенерировать новый SHA1 токен авторизации, записывает в базу и возвращает его значение * @return string */ public function generateToken(){ // Сгенерировать токен для авторизованного пользователя и сохранить его в базу $token = sha1($this->email.time().rand(0, 1000000)); // Сохранить токен в базе // И пометить его, что он актуален только в течение 10 следующих минут $this->orm->set("token", $token); $this->orm->set_expr("token_validity", "ADDTIME(NOW(),"0:10")"); $this->orm->save(); return $token; } /** * Авторизовать пользователя * @return void */ public function login(){ // Отметить пользователя, как авторизованного $_SESSION["loginid"] = $this->orm->id; // Обновить значение поля базы last_login $this->orm->set_expr("last_login", "NOW()"); $this->orm->save(); } /** * Уничтожить сессию и разлогинить пользователя * @return void */ public function logout(){ $_SESSION = array(); unset($_SESSION); } /** * Проверка, заходил ли пользователь * @return boolean */ public function loggedIn(){ return isset($this->orm->id) && $_SESSION["loginid"] == $this->orm->id; } /** * Проверка является ли пользователь администратором * @return boolean */ public function isAdmin(){ return $this->rank() == "administrator"; } /** * Найти тип пользователя, может быть либо administrator либо regular * @return string */ public function rank(){ if($this->orm->rank == 1){ return "administrator"; } return "regular"; } /** * Метод позволяющий получить приватную информацию пользователя в *качестве свойств объекта User * @param string $key Имя свойства, получающего доступ * @return mixed */ public function __get($key){ if(isset($this->orm->$key)){ return $this->orm->$key; } return null; } }

Токены генерируются с помощью SHA1 алгоритма и сохраняются в базе данных. Я использую функции времени MySQL, дабы задать 10-минутное ограничение актуальности токена.

Когда токен проходит процедуру валидации, мы напрямую говорим обработчику, что мы рассматриваем только токены, у которых ещё не истёк срок годности, хранимый в столбце token_validity.

Обратите внимание, что я использую волшебный метод __get библиотеки docs в конце файла, чтобы перехватить доступ к свойствам объекта User.

Благодаря этому становится возможным получить доступ к информации, хранящейся в базе, благодаря свойствам $user->email, $user->token и др. В следующем фрагменте кода рассмотрим для примера, как использовать эти классы.


Защищённая страница

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

functions.php

Function send_email($from, $to, $subject, $message){ // Хелпер, отправляющий 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(){ // Определить URL PHP-файла $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){ // Количество попыток входа за последний час по этому IP-адресу $count_hour = ORM::for_table("reg_login_attempt") ->where("ip", sprintf("%u", ip2long($ip))) ->where_raw("ts > SUBTIME(NOW(),"1:00")") ->count(); // Количество попыток входа за последние 10 минут по этому IP-адресу $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){ // Создать новую запись в таблице, считающей количество попыток входа $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

Try{ if(!empty($_POST) && isset($_SERVER["HTTP_X_REQUESTED_WITH"])){ // Output a JSON header header("Content-type: application/json"); // Является ли этот email-адрес валидным if(!isset($_POST["email"]) || !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){ throw new Exception("Please enter a valid email."); } // Проверка. Позволено ли пользователю авторизоваться, не превысил ли он количество допустимых подключений? (файл functions.php для большей информации) rate_limit($_SERVER["REMOTE_ADDR"]); // Записать эту попытку авторизации rate_limit_tick($_SERVER["REMOTE_ADDR"], $_POST["email"]); // Отправить письмо пользователю $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"; } // Попытка авторизовать или зарегистрировать пользователя $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()))); }

После успешной авторизации/регистрации код выше отправит пользователю ссылку для авторизации. Токен становится доступным, т.к. он передаётся в качестве переменной в генерируемой ссылке методом $_GET с маркером tkn

index.php

If(isset($_GET["tkn"])){ // Является ли этот токен валидным для авторизации? $user = User::findByToken($_GET["tkn"]); if($user){ // Да, является. Осуществить редирект на защищённую страницу $user->login(); redirect("protected.php"); } // Нет, токен не валидный. Осуществить редирект, на страницу с формой авторизации/регистрации 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

// Чтобы защитить каждую страницу на вашем сайте подключите к ней файл // main.php и создайте новый объект User. Вот как это просто! 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() используется здесь потому что в базе обычно хранятся номера (0 для обычного пользователя, 1 для администратора) и нам нужно преобразовать эти данные в статусы, к которым они относятся, в чём нам и помогает этот метод.

Чтобы сделать из обычного пользователя администратора, просто отредактируйте пользовательскую запись через phpMyAdmin (или любую другую программу, позволяющую управлять базами данных). Статус администратора не даёт каких-либо привилегий, в данном примере на странице будет выведено, что вы администратор - и всё.

А вот что с этим делать - остаётся уже на ваше усмотрение, вы можете сами написать и составить код, задающий определённые привилегии и возможности для администраторов.

Мы закончили!

С этой невероятно супер квази простой формой мы закончили! Вы можете использовать её в ваших PHP-сайтах, это достаточно просто. Также вы можете модифицировать её под себя и сделать её такой, как вы хотите.

Материал подготовил Денис Малышок специально для сайта сайт

P.S. Хотите двигаться дальше в освоении PHP и ООП? Обратите внимание на премиум-уроки по различным аспектам сайтостроения, включая программирование на PHP, а также на бесплатный курс по созданию своей CMS-системы на PHP с нуля с использованием ООП:

Понравился материал и хотите отблагодарить?
Просто поделитесь с друзьями и коллегами!


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.

If you prefer a video, you can watch it on my YouTube channel

The first thing we"ll need to do is set up our database.

Create a database called registration . In the registration database, add a table called users . The users table will take the following four fields.

  • username - varchar(100)
  • email - varchar(100)
  • password - varchar(100)

You can create this using a MySQL client like PHPMyAdmin.

Or you can create it on the MySQL prompt using the following SQL script:

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;

And that"s it with the database.

Now create a folder called registration in a directory accessible to our server. i.e create the folder inside htdocs (if you are using XAMPP server) or inside www (if you are using wampp server).

Inside the folder registration, create the following files:

Open these files up in a text editor of your choice. Mine is Sublime Text 3.

Registering a user

Open the register.php file and paste the following code in it:

regiser.php:

Register Username

Лучшие статьи по теме