Создаем невероятную простую систему регистрации на PHP и MySQL. PHP сценарии обработки HTML форм Амбулатория register form php

Процесс создания системы регистрации – это довольно большой объем работы. Вам нужно написать код, который бы перепроверял валидность 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-сайте, либо модернизировать ее, придерживаясь собственных требований.

PHP | 25 Jan, 2017 | Clever Techie

In this lesson, we learn how to create user account registration form with PHP validation rules, upload profile avatar image and insert user data in MySQL database. We will then retrieve the information from the database and display it on the user profile welcome page. Here is what the welcome page is going to look like:

Setting up Form CSS and HTML

First, go ahead and copy the HTML source from below codepen and place the code in a file called form.php. Also create another file named form.css in the same directory and copy and paste all of the CSS code from the codepen below into it:

Once you"ve saved form.php and form.css, you may go ahead and run form.php to see what the form looks like. It should look exactly the same as the one showing in the "Result" tab from the codepen above.

Creating the Database and Table

Before we start adding PHP code to our form, let"s go ahead and create the database with a table which will store our registered users information in it. Below in the SQL script to create the database "accounts" and table "users":

CREATE DATABASE accounts; CREATE TABLE `accounts`.`users` (`id` INT NOT NULL AUTO_INCREMENT, `username` VARCHAR(100) NOT NULL, `email` VARCHAR(100) NOT NULL, `password` VARCHAR(100) NOT NULL, `avatar` VARCHAR(100) NOT NULL, PRIMARY KEY (`id`));

Below is a complete code with error checking for connecting to MySQL database and running above SQL statements to create the database and users table:

//connection variables $host = "localhost"; $user = "root"; $password = "mypass123"; //create mysql connection $mysqli = new mysqli($host,$user,$password); if ($mysqli->connect_errno) { printf("Connection failed: %s\n", $mysqli->connect_error); die(); } //create the database if (!$mysqli->query("CREATE DATABASE accounts2")) { printf("Errormessage: %s\n", $mysqli->error); } //create users table with all the fields $mysqli->query(" CREATE TABLE `accounts2`.`users` (`id` INT NOT NULL AUTO_INCREMENT, `username` VARCHAR(100) NOT NULL, `email` VARCHAR(100) NOT NULL, `password` VARCHAR(100) NOT NULL, `avatar` VARCHAR(100) NOT NULL, PRIMARY KEY (`id`));") or die($mysqli->error);

With our HTML, CSS and the database table in place, we"re now reading to start working on our form. The first step is to create a place for error messages to show up and then we"ll start writing some form validation.

Starting New Session for Error Messages

Open up the form.php and add the following lines to it at the very top, make sure to use the php opening and closing tags (I have not included the html part of form.php to keep things clean).

We have created new session because we"re going to need to access $_SESSION["message"] on the "welcome.php" page after user successfully registers. MySQL connection has also been created right away, so we can work with the database later on.

We also need to print out $_SESSION["message"] on the current page. From the beginning the message is set to "" (empty string) which is what we want, so nothing will be printed at this point. Let"s go ahead and add the message inside the proper DIV tag:

Creating Validation Rules

This form already comes with some validation rules, the keyword "required" inside the HTML input tags, is checking to make sure the field is not empty, so we don"t have to worry about empty fields. Also, by setting input type to "email and "password", HTML5 validates the form for proper email and password formatting, so we don"t need to create any rules for those fields either.

However, we still need to write some validation rules, to make sure the passwords are matching, the avatar file is in fact an image and make sure the user has been added to our database.

Let"s create another file and call it validate.php to keep things well organized. We"ll also include this file from our form.php.

The first thing we"re going to do inside validate.php is to make sure the form is being submitted.

/* validate.php */ //the form has been submitted with post method if ($_SERVER["REQUEST_METHOD"] == "POST") { }

Then we"ll check if the password and confirm password are equal to each other

if ($_SERVER["REQUEST_METHOD"] == "POST") { //check if two passwords are equal to each other if ($_POST["password"] == $_POST["confirmpassword"]) { } }

Working with Super Global Variables

Note how we used super global variables $_SERVER and $_POST to get the information we needed. The keys names inside the $_POST variable is available because we used method="post" to submit our form.

The key names are all the named HTML input fields with attribute name (eg: name="password", name="confirmpassword"):

/>

To clarify a bit more, here is what the $_POST would look like (assuming all the fields in the form have been filled out) if we used a print_r($_POST) function on it, followed by die(); to terminate the script right after printing it. This is a good way of debugging your script and seeing what"s going on:

if ($_SERVER["REQUEST_METHOD"] == "POST") { print_r($_POST); die(); /*output: Array ( => clevertechie => [email protected] => mypass123 => mypass123 => Register) */

Now we"re going to get the rest of our submitted values from $_POST and get them properly formatted so they can be inserted to our MySQL database table

//the form has been submitted with post if ($_SERVER["REQUEST_METHOD"] == "POST") { if ($_POST["password"] == $_POST["confirmpassword"]) { //define other variables with submitted values from $_POST $username = $mysqli->real_escape_string($_POST["username"]); $email = $mysqli->real_escape_string($_POST["email"]); //md5 hash password for security $password = md5($_POST["password"]); //path were our avatar image will be stored $avatar_path = $mysqli->real_escape_string("images/".$_FILES["avatar"]["name"]); } }

In the above code, we used real_escape_string() method to make sure our username, email and avatar_path are formatted properly to be inserted as a valid SQL string into the database. We also used md5() hash function to create a hash string out of password for security.

How File Uploading Works

Also, notice the new super global variable $_FILES, which holds the information about our image, which is the avatar being uploaded from the user"s computer. The $_FILES variable is available because we used enctype="multipart/form-data" in our form:

Here is the output if we use the print_r($_FILES) followed by die(); just like we did for the $_POST variable:

if ($_SERVER["REQUEST_METHOD"] == "POST") { print_r($_FILES); die(); /*output: Array ( => Array ( => guldan.png => image/png => C:\Windows\Temp\php18D8.tmp => 0 => 98823)) */ //this is how we"re able to access the image name: $_FILES["avatar"]["name"]; //guldan.png

When the file is first uploaded, using the post method, it will be stored in a temporary directory. That directory can be accessed with $_FILES[ "avatar "][ "tmp_name" ] which is "C:\Windows\Temp\php18D8.tmp" from the output above.

We can then copy that file from the temporary directory, to the directory that we want which is $avatar_path. But before we copy the file, we should check if the file is in fact image, for that we"ll check another key called from our $_FILES variable.

//path were our avatar image will be stored $avatar_path = $mysqli->real_escape_string("images/".$_FILES["avatar"]["name"]); //make sure the file type is image if (preg_match("!image!",$_FILES["avatar"]["type"])) { //copy image to images/ folder if (copy($_FILES["avatar"]["tmp_name"], $avatar_path)) { } }

The preg_match function matches the image from the [ "type" ] key of $_FILES array, we then use copy() function to copy our image file which takes in two parameters. The first one is the source file path which is our ["tmp_name"] directory and the second one is the destination path which is our "images/guldan.png" file path.

Saving User Data in a MySQL Database

We can now set some session variables which we"ll need on the next page, which are username and avatar_path, and we"ll also create the SQL query which will insert all the submitted data into MySQL database:

if (copy($_FILES["avatar"]["tmp_name"], $avatar_path)) { //set session variables to display on welcome page $_SESSION["username"] = $username; $_SESSION["avatar"] = $avatar_path; //create SQL query string for inserting data into the database $sql = "INSERT INTO users (username, email, password, avatar) " . "VALUES ("$username", "$email", "$password", "$avatar_path")"; }

The final step is turn our query, using the query() method and check if it"s successful. If it is, that means the user data has been saved in the "users" table successfully! We then set the final session variable $_SESSION[ "message" ] and redirect the user to the welcome.php page using the header() function:

//check if mysql query is successful if ($mysqli->query($sql) === true) { $_SESSION[ "message" ] = "Registration succesful! Added $username to the database!"; //redirect the user to welcome.php header("location: welcome.php"); }

That"s pretty much all we need for the validation, we just need to add all the "else" keywords in case things don"t go as planned from all the if statements we have created. Here is what the full code for validate.php looks so far:

/* validate.php */ //the form has been submitted with post if ($_SERVER["REQUEST_METHOD"] == "POST") { //two passwords are equal to each other if ($_POST["password"] == $_POST["confirmpassword"]) { //define other variables with submitted values from $_POST $username = $mysqli->real_escape_string($_POST["username"]); $email = $mysqli->real_escape_string($_POST["email"]); //md5 hash password for security $password = md5($_POST["password"]); //path were our avatar image will be stored $avatar_path = $mysqli->real_escape_string("images/".$_FILES["avatar"]["name"]); //make sure the file type is image if (preg_match("!image!",$_FILES["avatar"]["type"])) { //copy image to images/ folder if (copy($_FILES["avatar"]["tmp_name"], $avatar_path)){ //set session variables to display on welcome page $_SESSION["username"] = $username; $_SESSION["avatar"] = $avatar_path; //insert user data into database $sql = "INSERT INTO users (username, email, password, avatar) " . "VALUES ("$username", "$email", "$password", "$avatar_path")"; //check if mysql query is successful if ($mysqli->query($sql) === true){ $_SESSION["message"] = "Registration successful!" . "Added $username to the database!"; //redirect the user to welcome.php header("location: welcome.php"); } } } } }

Setting Session Error Messages When Things Go Wrong

Let"s go ahead and add all the else statements at once where we simply set the $_SESSION[ "message" ] error messages which will be printed out when any of our if statements fail. Add the following code right after the last if statement where we checked for successful mysqli query and within the last curly bracket like this:

If ($mysqli->query($sql) === true){ $_SESSION["message"] = "Registration succesful!" . "Added $username to the database!"; header("location: welcome.php"); } else { $_SESSION["message"] = "User could not be added to the database!"; } $mysqli->close(); } else { $_SESSION["message"] = "File upload failed!"; } } else { $_SESSION["message"] = "Please only upload GIF, JPG or PNG images!"; } } else { $_SESSION["message"] = "Two passwords do not match!"; } } //if ($_SERVER["REQUEST_METHOD"] == "POST")

The session message will then display the error message in the div tag where we put our $_SESSION["message"] if you recall:

Below is an example of what the error message is going to look like when two passwords don"t match. Feel free to play around with it to trigger other error messages:


Creating User Profile Welcome Page

We"re now done with the validate.php. The final step is to create welcome.php page which will display the username, avatar image and some users that have already been registered previously along with their own user names and mini avatar thumbnails. Here is what the complete welcome.php should look like, I will explain parts of it that may be confusing: