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

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.

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

Already a member? Sign in

Nothing complicated so far right?

A few things to note here:

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

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

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

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

Now the form looks beautiful.

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

Open server.php and paste this code in it:

server.php

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

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

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

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

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

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

0) : ?>

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

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

Login user

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

Registration system PHP and MySQL

Login

Not yet a member? Sign up

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

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

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

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

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

Home

Home Page

Welcome

logout

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

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

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

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

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.

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

Шаг-1

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

  • UserID
  • Username
  • Password
  • EmailAddress

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

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

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

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

session_start();

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

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

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

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

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

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

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

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

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

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

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

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

Система управления пользователями <title> </span> <span><link rel="stylesheet" href="/style.css" type="text/css" /> </span> </head> <body> <span><div id="main">Сюда вставим php код </div> </p> <p>Теперь прежде чем пристать php программу разберём принцип её работы, что в той или иной ситуации надо выводит на экран:</p> <ol><li>Если пользователь уже вошёл то показываем страницу с различными опциями которые были скрыты до регистрации.</li> <li>Если пользователь еще не вошёл но прошёл регистрацию то показываем форму для ввода логина и пароля.</li> <li>Если 1 и 2 пункт не выполнен выводим форму для регистрации.</li> </ol><p>Выглядеть это будет так:</p> <p><?php </span> <span>if (! empty empty </span> <span>{ </span> <span>// Здесь выводиться скрытые опции </span> <span>} </span> <span>elseif (! empty empty ($_POST [ "password" ] ) ) </span> <span>{ </span> <span>// Выводим форму для входа </span> <span>} </span> <span>else </span> <span>{ </span> <span>// Выводим форму для регистрации </span> <span>} </span> <span>?> </p> <p>Когда пользователь проходит авторизацию на нашем сайте, информация сохраняется в сессии получить к ней доступ мы можем через глобальный массив <b>$ _SESSION </b>. С помощью функции empty и знака! в условии if мы проверяем имеет ли переменная значение, если переменная имеет значение выполняем код между фигурных скобок.</p> <p>В следующей строке всё работает тем же образом, только на этот раз с помощью <b>$ _POST </b> глобального массива. Этот массив содержит какие либо данные переданные через форму входа которую мы создадим позже. Последняя условие else выполниться в том случае если предыдущие условия не удовлетворяются.</p> <p>Теперь когда мы понимаем логику давайте вставим следующий код в файл index.php между тегами <div></p> <p><?php </span> <span>if (! empty ($_SESSION [ "LoggedIn" ] ) && ! empty ($_SESSION [ "Username" ] ) ) </span> <span>{ </span> <span>?> </span> <span> <h1>Пользовательская зона</h1> </span> <span> <p Спасибо что вошли! Вы <b><?= $_SESSION [ "Username" ] ?> </b> и Ваш адрес электронной почты <b><?= $_SESSION [ "EmailAddress" ] ?> </b>.</p> </span> <span><?php </span> <span>} </span> <span>elseif (! empty ($_POST [ "username" ] ) && ! empty ($_POST [ "password" ] ) ) </span> <span>{ </span> <span>$username = mysql_real_escape_string ($_POST [ "username" ] ) ; </span> <span>$password = md5 (mysql_real_escape_string </span> <span>$checklogin = mysql_query (</span> <span>if (mysql_num_rows ($checklogin ) == 1 ) </span> <span>{ </span> <span>$row = mysql_fetch_array ($checklogin ) ; </span> <span> echo <span>"<h1>Вы успешно вошли</h1>" </span>; </span> <span> echo <span>"<p>Сейчас вы будете переадресованы в ваш профиль.</p>" </span>; </span> <span> echo <span>"<meta content="=2;index.php" />" </span>; </span> <span>} </span> <span>else </span> <span>{ </span> <span> echo "<h1>Ошибка</h1>" ; </span> <span> echo <span>"<p>Ваша учётная запись не найдена или вы неправильно ввели логин или пароль. <a href=\" index.php\" >Попробовать снова </a>.</p>" </span>; </span> <span>} </span> <span>} </span> <span>else </span> <span>{ </span> <span>?> </span> <h1>Вход</h1> <span> <p>Хорошо что зашли Регистрация .</p> </span> <span> <form method="post" action="index.php" name="loginform" id="loginform"> </span> <fieldset> <span> <label for="username">Логин:</label><input type="text" name="username" id="username" /><br /> </span> <span> <label for="password">Пароль:</label><input type="password" name="password" id="password" /><br /> </span> <span> <input type="submit" name="login" id="login" value="Войти" /> </span> </fieldset> </form> <span><?php </span> <span>} </span> <span>?> </p> <p>В этом участке кода две функции,это<b>mysql _real _escape _string </b>которая экранирует специальные символы в строках для использования в базе данных тем самым обезопасит вас от нехорошихлюдей, и <b>md 5 </b> эта функция шифрует всё что передано ей в качестве параметра, в данном случае это пароль в глобальном массиве <b>$_POST </b>. Всё результаты работы функций мы присваиваем переменным<b>$username , <span>$password </span> </b>.</p> <p>$checklogin = mysql_query (<span>"SELECT * FROM users WHERE Username = "" </span>. $username . "" AND Password = "" . $password . """ ) ; </span> <span>if (mysql_num_rows ($checklogin ) == 1 ) </span> <span>{ </span> <span>$row = mysql_fetch_array ($checklogin ) ; </span> <span>$email = $row [ "EmailAddress" ] ; </span> <span>$_SESSION [ "Username" ] = $username ; </span> <span>$_SESSION [ "EmailAddress" ] = $email ; </span> <span>$_SESSION [ "LoggedIn" ] = 1 ; </p> <p>В этом участке кода нам надо проверить существует ли такой пользователь,для этого направляем запрос в базу данных, вытащить все поля из таблицы users где поля Username и Password равны переменным<b>$username и $password </b>. Результат запроса заносим в переменную<b>$checklogin </b> далее в условии <b>if </b> функция <b>mysql _num _row </b>s считает количество строк в запросе к базе и если равно 1 то есть пользователь найденвыполняем код в фигурных скобках, функция <b>mysql _fetch _array </b>преобразовывает результат запроса из <b>$checklogin </b>в ассоциативный массив, присваиваеваем значение поля EmailAddress переменной <b>$email </b>для использовать в дальнейшем.</p> <p>Заносим логин и email в текущею сессию после этого пользователь перенаправляется в свою учётную запись.</p> <p><b>Шаг-3 </b></p> <p>Теперь надо сделать страницу где пользователи будут регистрироваться.</p> <p>Создаем файл register.phpи скопируйте в него следующий код:</p> <p><?php include "base.php" ; ?> </span> <span><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> </span> <span><html xmlns="http://www.w3.org/1999/xhtml"> </span> <span><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </span> <span><title> Система управления пользователями - Регистрацияtitle> </span> <span><link rel="stylesheet" href="/style.css" type="text/css" /> </span> </head> <body> <div id="main"> <span><?php </span> <span>if (! empty ($_POST [ "username" ] ) && ! empty ($_POST [ "password" ] ) ) </span> <span>{ </span> <span>$username = mysql_real_escape_string ($_POST [ "username" ] ) ; </span> <span>$password = md5 (mysql_real_escape_string ($_POST [ "password" ] ) ) ; </span> <span>$email = mysql_real_escape_string ($_POST [ "email" ] ) ; </span> <span>$checkusername = mysql_query (<span>"SELECT * FROM users WHERE Username = "" </span>. $username . """ ) ; </span> <span>if (mysql_num_rows ($checkusername ) == 1 ) </span> <span>{ </span> <span> echo "<h1>Ошибка</h1>" ; </span> <span> echo <span>"<p>Такой логин уже занят p>" </span>; </span> <span>} </span> <span>else </span> <span>{ </span> <span>$registerquery = mysql_query (<span>"INSERT INTO users (Username, Password, EmailAddress) VALUES("" </span>. $username . "", "" . $password . "", "" . $email . "")" ) ; </span> <span>if ($registerquery ) </span> <span>{ </span> <span> echo "<h1>Отлично</h1>" ; </span> <span> echo <span>"<p>Ваша учетная запись была успешно создана. Вы можете<a href=\" index.php\" >Воити</a>.</p>" </span>; </span> <span>} </span> <span>else </span> <span>{ </span> <span> echo "<h1>Ошибка</h1>" ; </span> <span> echo <span>"<p>Попробуйте повторить регистрацию снова.</p>" </span>; </span> <span>} </span> <span>} </span> <span>} </span> <span>else </span> <span>{ </span> <span>?> </span> <span> <h1>Регистрация</h1> </span> <span> <form method="post" action="register.php" name="registerform" id="registerform"> </span> <fieldset> <span> <label for="username">Логин:</label><input type="text" name="username" id="username" /><br /> </span> <span> <label for="password">Пароль:</label><input type="password" name="password" id="password" /><br /> </span> <span> <label for="email">Email:</label><input type="text" name="email" id="email" /><br /> </span> <span> <input type="submit" name="register" id="register" value="Регистрация" /> </span> </fieldset> </form> <span><?php </span> <span>} </span> <span>?> </span> </div> </body> </html> </p> <p>В этом коде есть немного нового, запись в базу данных</p> <p>Это такой же запрос к базе данных который был раньше только теперь мы не получаеминформацию, а записываем командой INSERT , первым деломнадо указать в какие поля будет вноситься информация а в область VALUES информация которая будет записана в нашем случае это переменные со значением которые были переданы пользователем.Обратите особое внимание правила формирования запросов.</p> <p><b>Шаг-4 Завершение </b></p> <p>Для того чтобы пользователь мог выйти создайте файл logout.php и скопируйте в него код:</p> <p><?php include "base.php; <span>$_SESSION = array(); session_destroy(); ?> </span> <meta http-equiv=" refresh" content=" 0 ; index. php" </p> <p>В результате этого кода происходит сбросглобального массива $_SESSION и разрушение сессии, не забудьтев опция пользователя поставить ссылку на этот фаил.</p> <p>И наконец придадим стиль всему вышеописанному, создайте файл style.css и поместите туда следующий ниже код.</p> <p>* { </span> <span>margin : 0 ; </span> <span>padding : 0 ; </span> <span>} </span> body <span>{ </span> <span>} </span> a <span>{ </span> <span>color : #000 ; </span> <span>} </span> a<span>:hover , a:active , a:visited { </span> <span>text-decoration : none ; </span> <span>} </span> <span>#main { </span> <span>width : 780px ; </span> <span>margin : 0 auto ; </span> <span>margin-top : 50px ; </span> <span>padding : 10px ; </span> <span>background-color : #EEE ; </span> <span>} </span> form fieldset <span>{ border : 0 ; } </span> form fieldset p br <span>{ clear : left ; } </span> label <span>{ </span> <span>margin-top : 5px ; </span> <span>display : block ; </span> <span>width : 100px ; </span> <span>padding : 0 ; </span> <span>float : left ; </span> <span>} </span> input <span>{ </span> <span>font-family : Trebuchet MS; </span> <span>border : 1px solid #CCC ; </span> <span>margin-bottom : 5px ; </span> <span>background-color : #FFF ; </span> <span>padding : 2px ; </span> <span>} </span> input<span>:hover { </span> <span>border : 1px solid #222 ; </span> <span>background-color : #EEE ; </span> <span>} </p> <p>Вот в принципе и всё конечно приведенный в этом уроке пример далёк от совершенства но он и был рассчитан для начинающих чтобы дать понятие основ.</p> <p>Разберём некоторые части данного кода</p> <p>$username = mysql_real_escape_string($_POST["username"]); </p> <p>$password = md5(mysql_real_escape_string($_POST["password"])); </p> <p>В этом участке кода две функции,этоmysql _real _escape _string которая экранирует специальные символы в строках для использования в базе данных тем самым обезопасит вас от нехорошихлюдей, и md 5 эта функция шифрует всё что передано ей в качестве параметра, в данном случае это пароль в глобальном массиве $_POST . Всё результаты работы функций мы присваиваем переменным$username , <span>$password </span>.</p> <script>document.write("<img style='display:none;' src='//counter.yadro.ru/hit;artfast_after?t44.1;r"+ escape(document.referrer)+((typeof(screen)=="undefined")?"": ";s"+screen.width+"*"+screen.height+"*"+(screen.colorDepth? screen.colorDepth:screen.pixelDepth))+";u"+escape(document.URL)+";h"+escape(document.title.substring(0,150))+ ";"+Math.random()+ "border='0' width='1' height='1' loading=lazy>");</script> </div> <footer class="entry-footer"></footer> </article><div id="post-ratings-14317-loading" class="post-ratings-loading"> <img src="https://logonat.ru/wp-content/plugins/wp-postratings/images/loading.gif" width="16" height="16" alt="Loading..." title="Loading..." class="post-ratings-image" / loading=lazy>Loading...</div> <script type="text/javascript" src="//yastatic.net/share/share.js" charset="utf-8"></script><div style="margin:5px 0 30px 0;" class="yashare-auto-init" data-yashareL10n="ru" data-yashareType="button" data-yashareQuickServices="vkontakte,facebook,twitter,odnoklassniki,moimir"></div></main></div> <div id="secondary-right" class="widget-area right-sidebar sidebar"> <aside id="text-5" class="widget widget_text"> <div class="textwidget"></div> </aside> <aside id="text-4" class="widget widget_text"> <div class="textwidget"></div> </aside> <aside id="text-3" class="widget widget_text"> <div class="textwidget"></div> </aside> <aside id="recent-posts-2" class="widget widget_recent_entries"> <h3 class="widget-title">Новые статьи</h3> <ul> <li> <a href="/rezhimy-igry-shturm-i-vstrechnyi-boi-osnovy-bazovye-oshibki-i.html">Штурм и Встречный бой: основы, базовые ошибки и советы World of tanks бои стандартные</a></li> <li> <a href="/skachat-mody-world-of-tanks-karta.html">Скачать моды world of tanks карта</a></li> <li> <a href="/izometricheskie-igry-na-pc-luchshie-izometricheskie-igry-na-pk-luchshaya-rpg-na.html">Лучшие изометрические игры на пк</a></li> <li> <a href="/kak-pomenyat-platezhnuyu-kartu-na-aliekspress-kak-pomenyat-nomer-karty-v.html">Как поменять номер карты в алиэкспресс</a></li> <li> <a href="/dhl-gm-packet-priority-otslezhivanie-dostavka-zakazov-iz-iherb-v-rossiyu.html">Доставка заказов из iHerb в Россию местной почтовой службой Премиум (Global Mail by DHL, Почта России)</a></li> <li> <a href="/obshcheprinyatyi-razmer-gitary-obshcheprinyatyi-razmer-gitary-skolko-vesit-gitara.html">Общепринятый размер гитары Сколько весит гитара акустическая</a></li> <li> <a href="/analiz-trafika-v-lokalnoi-seti-cherez-router-monitoring-seti-s-ispolzovanie.html">Мониторинг сети с использование утилиты TCPView и netstat</a></li> <li> <a href="/kak-udalit-polzovatelya-kotoryi-vyshel-udalenie-yuzera-cherez-razdel.html">Удаление юзера через раздел контроля паролей</a></li> <li> <a href="/kak-sozdat-novyi-profil-v-windows-8-kto-zhe-takoi-sisadmin-pravila.html">Как создать новый профиль в windows 8</a></li> <li> <a href="/kak-dobavit-fotografiyu-vkontakte-kak-dobavit-foto-vkontakte-poshagovaya.html">Как добавить фото ВКонтакте: пошаговая инструкция для публикации фотографий с компьютера и телефона Как добавить фотографию в новом контакте</a></li> </ul> </aside> <aside id="text-2" class="widget widget_text"> <div class="textwidget"></div> </aside> </div> </div></div> <footer id="colophon"> <div id="middle-footer" class="footer-menu"> <div class="ak-container"> <div class="menu-futer-container"> <ul id="menu-futer" class="menu"> <li class="menu-item menu-item-type-post_type menu-item-object-page menu-item"><a href="/sitemap.xml">Карта сайта</a></li> <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item"><a href="/feedback.html">Написать письмо</a></li> <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item"><a href="">О сайте</a></li> </ul> </div> </div> </div> <div id="bottom-footer"> <div class="ak-container"> <div class="footer-wrap clearfix"> <div class="copyright"> <noindex> <p style="float:left;text-align:left;"></p> </noindex>© «Вход в систему», 2024</div> </div> <div class="footer-socials clearfix"> <div class="socials"></div> </div> </div> </div> </footer> </div><div class="multi-border"><ul><li class="dark-green"></li><li class="yellow"></li><li class="cream"></li><li class="orange"></li><li class="light-green"></li></ul></div><div id="wpfront-scroll-top-container"><img src="https://logonat.ru/wp-content/uploads/myup.png" alt="В начало страницы" / loading=lazy></div> <script type="text/javascript">if(typeof wpfront_scroll_top == "function") wpfront_scroll_top({ "scroll_offset":100,"button_width":0,"button_height":0,"button_opacity":0.8,"button_fade_duration":200,"scroll_duration":400,"location":1,"marginX":20,"marginY":20,"hide_iframe":false,"auto_hide":false,"auto_hide_after":2} );</script><div id="vsepr-3a31af52031e2fd6dd2a49aa81d1e8d3"></div><div id="vsepr-497139e04a2e270bb3bf23280c264c5d"></div><meta http-equiv="imagetoolbar" content="no"> <script type="text/javascript">document.oncontextmenu = function() { return false; } ; document.onselectstart = function() { if (event.srcElement.type != "text" && event.srcElement.type != "textarea" && event.srcElement.type != "password") { return false; } else { return true; } } ; if (window.sidebar) { document.onmousedown = function(e) { var obj = e.target; if (obj.tagName.toUpperCase() == 'SELECT' || obj.tagName.toUpperCase() == "INPUT" || obj.tagName.toUpperCase() == "TEXTAREA" || obj.tagName.toUpperCase() == "PASSWORD") { return true; } else { return false; } } ; } document.ondragstart = function() { return false; } ;</script> <script type="text/javascript">var q2w3_sidebar_options = new Array(); q2w3_sidebar_options[0] = { "sidebar" : "right-sidebar", "margin_top" : 10, "margin_bottom" : 700, "stop_id" : "", "screen_max_width" : 1000, "screen_max_height" : 0, "width_inherit" : false, "refresh_interval" : 1500, "window_load_hook" : false, "disable_mo_api" : false, "widgets" : ['text-2'] } ;</script> <script type='text/javascript'>/* */ var tocplus = { "smooth_scroll":"1"} ; /* */</script> <script type='text/javascript'>/* */ var stbUserOptions = { "mode":"css","cssOptions":{ "roundedCorners":false,"mbottom":30,"imgHide":"http:\/\/logonat.ru\/wp-content\/plugins\/wp-special-textboxes\/themes\/stb-metro\/minus.png","imgShow":"http:\/\/logonat.ru\/wp-content\/plugins\/wp-special-textboxes\/themes\/stb-metro\/plus.png","strHide":"\u0421\u043a\u0440\u044b\u0442\u044c","strShow":"\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c"} }; /* */</script> <script type="text/javascript" id="slb_context">/* */if ( !!window.jQuery ) { (function($){ $(document).ready(function(){ if ( !!window.SLB ) { { $.extend(SLB, { "context":["public","user_guest"]} );} } })} )(jQuery);} /* */</script> <script>var advads_tracking_ads = [];</script> <script type="text/javascript" defer src="https://logonat.ru/wp-content/cache/autoptimize/js/autoptimize_2949591b35501135449767c41f626089.js"></script></body></html>