Домой Программы Создаем невероятную простую систему регистрации на PHP и MySQL. Создаем невероятную простую систему регистрации на PHP и MySQL Уклонение member registration php

Создаем невероятную простую систему регистрации на PHP и MySQL. Создаем невероятную простую систему регистрации на PHP и MySQL Уклонение member registration php

Creating a membership based site seems like a daunting task at first. If you ever wanted to do this by yourself, then just gave up when you started to think how you are going to put it together using your PHP skills, then this article is for you. We are going to walk you through every aspect of creating a membership based site, with a secure members area protected by password.

The whole process consists of two big parts: user registration and user authentication. In the first part, we are going to cover creation of the registration form and storing the data in a MySQL database. In the second part, we will create the login form and use it to allow users access in the secure area.

Download the code

You can download the whole source code for the registration/login system from the link below:

Configuration & Upload
The ReadMe file contains detailed instructions.

Open the source\include\membersite_config.php file in a text editor and update the configuration. (Database login, your website’s name, your email address etc).

Upload the whole directory contents. Test the register.php by submitting the form.

The registration form

In order to create a user account, we need to gather a minimal amount of information from the user. We need his name, his email address and his desired username and password. Of course, we can ask for more information at this point, but a long form is always a turn-off. So let’s limit ourselves to just those fields.

Here is the registration form:

Register

So, we have text fields for name, email and the password. Note that we are using the for better usability.

Form validation

At this point it is a good idea to put some form validation code in place, so we make sure that we have all the data required to create the user account. We need to check if name and email, and password are filled in and that the email is in the proper format.

Handling the form submission

Now we have to handle the form data that is submitted.

Here is the sequence (see the file fg_membersite.php in the downloaded source):

function RegisterUser() { if(!isset($_POST["submitted"])) { return false; } $formvars = array(); if(!$this->ValidateRegistrationSubmission()) { return false; } $this->CollectRegistrationSubmission($formvars); if(!$this->SaveToDatabase($formvars)) { return false; } if(!$this->SendUserConfirmationEmail($formvars)) { return false; } $this->SendAdminIntimationEmail($formvars); return true; }

First, we validate the form submission. Then we collect and ‘sanitize’ the form submission data (always do this before sending email, saving to database etc). The form submission is then saved to the database table. We send an email to the user requesting confirmation. Then we intimate the admin that a user has registered.

Saving the data in the database

Now that we gathered all the data, we need to store it into the database.
Here is how we save the form submission to the database.

function SaveToDatabase(&$formvars) { if(!$this->DBLogin()) { $this->HandleError("Database login failed!"); return false; } if(!$this->Ensuretable()) { return false; } if(!$this->IsFieldUnique($formvars,"email")) { $this->HandleError("This email is already registered"); return false; } if(!$this->IsFieldUnique($formvars,"username")) { $this->HandleError("This UserName is already used. Please try another username"); return false; } if(!$this->InsertIntoDB($formvars)) { $this->HandleError("Inserting to Database failed!"); return false; } return true; }

Note that you have configured the Database login details in the membersite_config.php file. Most of the cases, you can use “localhost” for database host.
After logging in, we make sure that the table is existing.(If not, the script will create the required table).
Then we make sure that the username and email are unique. If it is not unique, we return error back to the user.

The database table structure

This is the table structure. The CreateTable() function in the fg_membersite.php file creates the table. Here is the code:

function CreateTable() { $qry = "Create Table $this->tablename (". "id_user INT NOT NULL AUTO_INCREMENT ,". "name VARCHAR(128) NOT NULL ,". "email VARCHAR(64) NOT NULL ,". "phone_number VARCHAR(16) NOT NULL ,". "username VARCHAR(16) NOT NULL ,". "password VARCHAR(32) NOT NULL ,". "confirmcode VARCHAR(32) ,". "PRIMARY KEY (id_user)". ")"; if(!mysql_query($qry,$this->connection)) { $this->HandleDBError("Error creating the table \nquery was\n $qry"); return false; } return true; }

The id_user field will contain the unique id of the user, and is also the primary key of the table. Notice that we allow 32 characters for the password field. We do this because, as an added security measure, we will store the password in the database encrypted using MD5. Please note that because MD5 is an one-way encryption method, we won’t be able to recover the password in case the user forgets it.

Inserting the registration to the table

Here is the code that we use to insert data into the database. We will have all our data available in the $formvars array.

function InsertIntoDB(&$formvars) { $confirmcode = $this->MakeConfirmationMd5($formvars["email"]); $insert_query = "insert into ".$this->tablename."(name, email, username, password, confirmcode) values ("" . $this->SanitizeForSQL($formvars["name"]) . "", "" . $this->SanitizeForSQL($formvars["email"]) . "", "" . $this->SanitizeForSQL($formvars["username"]) . "", "" . md5($formvars["password"]) . "", "" . $confirmcode . "")"; if(!mysql_query($insert_query ,$this->connection)) { $this->HandleDBError("Error inserting data to the table\nquery:$insert_query"); return false; } return true; }

Notice that we use PHP function md5() to encrypt the password before inserting it into the database.
Also, we make the unique confirmation code from the user’s email address.

Sending emails

Now that we have the registration in our database, we will send a confirmation email to the user. The user has to click a link in the confirmation email to complete the registration process.

function SendUserConfirmationEmail(&$formvars) { $mailer = new PHPMailer(); $mailer->CharSet = "utf-8"; $mailer->AddAddress($formvars["email"],$formvars["name"]); $mailer->Subject = "Your registration with ".$this->sitename; $mailer->From = $this->GetFromAddress(); $confirmcode = urlencode($this->MakeConfirmationMd5($formvars["email"])); $confirm_url = $this->GetAbsoluteURLFolder()."/confirmreg.php?code=".$confirmcode; $mailer->Body ="Hello ".$formvars["name"]."\r\n\r\n". "Thanks for your registration with ".$this->sitename."\r\n". "Please click the link below to confirm your registration.\r\n". "$confirm_url\r\n". "\r\n". "Regards,\r\n". "Webmaster\r\n". $this->sitename; if(!$mailer->Send()) { $this->HandleError("Failed sending registration confirmation email."); return false; } return true; }

Updates

9th Jan 2012
Reset Password/Change Password features are added
The code is now shared at GitHub .

Welcome back UserFullName(); ?>!

License


The code is shared under LGPL license. You can freely use it on commercial or non-commercial websites.

No related posts.

Comments on this entry are closed.

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

Reseller Hosting

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

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

1. Customization

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

2. Applications

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

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

3. Stability

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

4. .NET compatibility

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

5. Cost advantages

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

6. Ease of setup

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

7. Security

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

Conclusion

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



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

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

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

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

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

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

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

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

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

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

Future of Coding

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

How Pip Engages Children

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

Innovations to Come

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

A tutorial for the very beginner! No matter where you go on the Internet, there"s a staple that you find almost everywhere - user registration. Whether you need your users to register for security or just for an added feature, there is no reason not to do it with this simple tutorial. In this tutorial we will go over the basics of user management, ending up with a simple Member Area that you can implement on your own website.

If you need any extra help or want a shortcut, check out the range of PHP service providers on Envato Studio. These experienced developers can help you with anything from a quick bug fix to developing a whole app from scratch. So just browse the providers, read the reviews and ratings, and pick the right one for you.

Introduction

In this tutorial we are going to go through each step of making a user management system, along with an inter-user private messaging system. We are going to do this using PHP, with a MySQL database for storing all of the user information. This tutorial is aimed at absolute beginners to PHP, so no prior knowledge at all is required - in fact, you may get a little bored if you are an experienced PHP user!

This tutorial is intended as a basic introduction to Sessions, and to using Databases in PHP. Although the end result of this tutorial may not immediately seem useful to you, the skills that you gain from this tutorial will allow you to go on to produce a membership system of your own; suiting your own needs.

Before you begin this tutorial, make sure you have on hand the following information:

  • Database Hostname - this is the server that your database is hosted on, in most situations this will simply be "localhost".
  • Database Name, Database Username, Database Password - before starting this tutorial you should create a MySQL database if you have the ability, or have on hand the information for connecting to an existing database. This information is needed throughout the tutorial.

If you don"t have this information then your hosting provider should be able to provide this to you.

Now that we"ve got the formalities out of the way, let"s get started on the tutorial!

Step 1 - Initial Configuration

Setting up the database

As stated in the Introduction, you need a database to continue past this point in the tutorial. To begin with we are going to make a table in this database to store our user information.

The table that we need will store our user information; for our purposes we will use a simple table, but it would be easy to store more information in extra columns if that is what you need. In our system we need the following four columns:

  • UserID (Primary Key)
  • Username
  • Password
  • EmailAddress

In database terms, a Primary Key is the field which uniquely identifies the row. In this case, UserID will be our Primary Key. As we want this to increment each time a user registers, we will use the special MySQL option - auto_increment .

The SQL query to create our table is included below, and will usually be run in the "SQL" tab of phpMyAdmin.

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);

Creating a Base File

In order to simplify the creation of our project, we are going to make a base file that we can include in each of the files we create. This file will contain the database connection information, along with certain configuration variables that will help us out along the way.

Start by creating a new file: base.php , and enter in it the following code:

Let"s take a look at a few of those lines shall we? There"s a few functions here that we"ve used and not yet explained, so let"s have a look through them quickly and make sense of them -- if you already understand the basics of PHP, you may want to skip past this explanation.

Session_start();

This function starts a session for the new user, and later on in this tutorial we will store information in this session to allow us to recognize users who have already logged in. If a session has already been created, this function will recognize that and carry that session over to the next page.

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

Each of these functions performs a separate, but linked task. The mysql_connect function connects our script to the database server using the information we gave it above, and the mysql_select_db function then chooses which database to use with the script. If either of the functions fails to complete, the die function will automatically step in and stop the script from processing - leaving any users with the message that there was a MySQL Error.

Step 2 - Back to the Frontend

What Do We Need to Do First?

The most important item on our page is the first line of PHP; this line will include the file that we created above (base.php), and will essentially allow us to access anything from that file in our current file. We will do this with the following line of of PHP code. Create a file named index.php , and place this code at the top.

Begin the HTML Page

The first thing that we are going to do for our frontend is to create a page where users can enter their details to login, or if they are already logged in a page where they can choose what they then wish to do. In this tutorial I am presuming that users have basic knowledge of how HTML/CSS works, and therefore am not going to explain this code in detail; at the moment these elements will be un-styled, but we will be able to change this later when we create our CSS stylesheet.

Using the file that we have just created (index.php), enter the following HTML code below the line of PHP that we have already created.

What Shall We Show Them?

Before we output the rest of the page we have a few questions to ask ourselves:

  1. Is the user already logged in?
  • Yes - we need to show them a page with options for them to choose.
  • No
  • Has the user already submitted their login details?
    • Yes - we need to check their details, and if correct we will log them into the site.
    • No - we continue onto the next question.
  • If both of the above were answered No , we can now assume that we need to display a login form to the user.
  • These questions are in fact, the same questions that we are going to implement into our PHP code. We are going to do this in the form of if statements . Without entering anything into any of your new files, lets take a look at the logic that we are going to use first.

    Looks confusing, doesn"t it? Let"s split it down into smaller sections and go over them one at a time.

    If(!empty($_SESSION["LoggedIn"]) && !empty($_SESSION["Username"])) { // let the user access the main page }

    When a user logs into our website, we are going to store their information in a session - at any point after this we can access that information in a special global PHP array - $_SESSION . We are using the empty function to check if the variable is empty, with the operator ! in front of it. Therefore we are saying:

    If the variable $_SESSION["LoggedIn"] is not empty and $_SESSION["Username"] is not empty, execute this piece of code.

    The next line works in the same fashion, only this time using the $_POST global array. This array contains any data that was sent from the login form that we will create later in this tutorial. The final line will only execute if neither of the previous statements are met; in this case we will display to the user a login form.

    So, now that we understand the logic, let"s get some content in between those sections. In your index.php file, enter the following below what you already have.

    Member Area

    and your email address is .

    Success"; echo "

    We are now redirecting you to the member area.

    "; echo ""; } else { echo "

    Error

    "; echo "

    Sorry, your account could not be found. Please click here to try again.

    "; } } else { ?>

    Member Login

    Thanks for visiting! Please either login below, or click here to register.



    Hopefully, the first and last code blocks won"t confuse you too much. What we really need to get stuck into now is what you"ve all come to this tutorial for - the PHP code. We"re now going to through the second section one line at a time, and I"ll explain what each bit of code here is intended for.

    $username = mysql_real_escape_string($_POST["username"]); $password = md5(mysql_real_escape_string($_POST["password"]));

    There are two functions that need explaining for this. Firstly, mysql_real_escape_string - a very useful function to clean database input. It isn"t a failsafe measure, but this will keep out the majority of the malicious hackers out there by stripping unwanted parts of whatever has been put into our login form. Secondly, md5 . It would be impossible to go into detail here, but this function simply encrypts whatever is passed to it - in this case the user"s password - to prevent prying eyes from reading it.

    $checklogin = mysql_query("SELECT * FROM users WHERE Username = "".$username."" AND Password = "".$password."""); if(mysql_num_rows($checklogin) == 1) { $row = mysql_fetch_array($checklogin); $email = $row["EmailAddress"]; $_SESSION["Username"] = $username; $_SESSION["EmailAddress"] = $email; $_SESSION["LoggedIn"] = 1;

    Here we have the core of our login code; firstly, we run a query on our database. In this query we are searching for everything relating to a member, whose username and password match the values of our $username and $password that the user has provided. On the next line we have an if statement, in which we are checking how many results we have received - if there aren"t any results, this section won"t be processed. But if there is a result, we know that the user does exist, and so we are going to log them in.

    The next two lines are to obtain the user"s email address. We already have this information from the query that we have already run, so we can easily access this information. First, we get an array of the data that has been retrieved from the database - in this case we are using the PHP function mysql_fetch_array . I have then assigned the value of the EmailAddress field to a variable for us to use later.

    Now we set the session. We are storing the user"s username and email address in the session, along with a special value for us to know that they have been logged in using this form. After this is all said and done, they will then be redirect to the Member Area using the META REFRESH in the code.

    So, what does our project currently look like to a user?

    Great! It"s time to move on now, to making sure that people can actually get into your site.

    Let the People Signup

    It"s all well and good having a login form on your site, but now we need to let user"s be able to use it - we need to make a login form. Make a file called register.php and put the following code into it.

    User Management System (Tom Cameron for NetTuts)

    Error"; echo "

    Sorry, that username is taken. Please go back and try again.

    "; } else { $registerquery = mysql_query("INSERT INTO users (Username, Password, EmailAddress) VALUES("".$username."", "".$password."", "".$email."")"); if($registerquery) { echo "

    Success

    "; echo "

    Your account was successfully created. Please click here to login.

    "; } else { echo "

    Error

    "; echo "

    Sorry, your registration failed. Please go back and try again.

    "; } } } else { ?>

    Register

    Please enter your details below to register.




    So, there"s not much new PHP that we haven"t yet learned in that section. Let"s just take a quick look at that SQL query though, and see if we can figure out what it"s doing.

    $registerquery = mysql_query("INSERT INTO users (Username, Password, EmailAddress) VALUES("".$username."", "".$password."", "".$email."")");

    So, here we are adding the user to our database. This time, instead of retrieving data we"re inserting it; so we"re specifying first what columns we are entering data into (don"t forget, our UserID will go up automatically). In the VALUES() area, we"re telling it what to put in each column; in this case our variables that came from the user"s input. So, let"s give it a try; once you"ve made an account on your brand-new registration form, here"s what you"ll see for the Member"s Area.

    Make Sure That They Can Logout

    We"re almost at the end of this section, but there"s one more thing we need before we"re done here - a way for user"s to logout of their accounts. This is very easy to do (fortunately for us); create a new filed named logout.php and enter the following into it.

    In this we are first resetting our the global $_SESSION array, and then we are destroying the session entirely.

    And that"s the end of that section, and the end of the PHP code. Let"s now move onto our final section.

    Step 3 - Get Styled

    I"m not going to explain much in this section - if you don"t understand HTML/CSS I would highly recommend when of the many excellent tutorials on this website to get you started. Create a new file named style.css and enter the following into it; this will style all of the pages that we have created so far.

    * { margin: 0; padding: 0; } body { font-family: Trebuchet MS; } a { color: #000; } a:hover, a:active, a:visited { text-decoration: none; } #main { width: 780px; margin: 0 auto; margin-top: 50px; padding: 10px; border: 1px solid #CCC; background-color: #EEE; } form fieldset { border: 0; } form fieldset p br { clear: left; } label { margin-top: 5px; display: block; width: 100px; padding: 0; float: left; } input { font-family: Trebuchet MS; border: 1px solid #CCC; margin-bottom: 5px; background-color: #FFF; padding: 2px; } input:hover { border: 1px solid #222; background-color: #EEE; }

    Now let"s take a look at a few screenshots of what our final project should look like:

    The login form.

    The member area.

    The registration form.

    And Finally...

    And that"s it! You now have a members area that you can use on your site. I can see a lot of people shaking their heads and shouting at their monitors that that is no use to them - you"re right. But what I hope any beginners to PHP have learned is the basics of how to use a database, and how to use sessions to store information. The vital skills to creating any web application.

    • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.

    Сегoдня мы рассмотрим эксплуатацию критической 1day-уязвимости в популярной CMS Joomla, которая прогремела на просторах интернета в конце октября. Речь пойдет об уязвимостях с номерами CVE-2016-8869 , CVE-2016-8870 и CVE-2016-9081 . Все три происходят из одного кусочка кода, который пять долгих лет томился в недрах фреймворка в ожидании своего часа, чтобы затем вырваться на свободу и принести с собой хаос, взломанные сайты и слезы ни в чем не повинных пользователей этой Joomla. Лишь самые доблестные и смелые разработчики, чьи глаза красны от света мониторов, а клавиатуры завалены хлебными крошками, смогли бросить вызов разбушевавшейся нечисти и возложить ее голову на алтарь фиксов.

    WARNING

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

    С чего все началось

    6 октября 2016 года Дэмис Пальма (Demis Palma) создал топик на Stack Exchange , в котором поинтересовался: а почему, собственно, в Joomla версии 3.6 существуют два метода регистрации пользователей с одинаковым названием register() ? Первый находится в контроллере UsersControllerRegistration , а второй - в UsersControllerUser . Дэмис хотел узнать, используется ли где-то метод UsersControllerUser::register() , или это лишь эволюционный анахронизм, оставшийся от старой логики. Его беспокоил тот факт, что, даже если этот метод не используется никаким представлением, он может быть вызван при помощи сформированного запроса. На что получил ответ от девелопера под ником itoctopus, подтвердившего: проблема действительно существует. И направил отчет разработчикам Joomla.

    Далее события развивались самым стремительным образом. 18 октября разработчики Joomla принимают репорт Дэмиса, который к тому времени набросал PoC, позволяющий регистрировать пользователя. Он опубликовал заметку на своем сайте , где в общих чертах рассказал о найденной проблеме и мыслях по этому поводу. В этот же день выходит новая версия Joomla 3.6.3, которая все еще содержит уязвимый код.

    После этого Давиде Тампеллини (Davide Tampellini) раскручивает баг до состояния регистрации не простого пользователя, а администратора. И уже 21 октября команде безопасности Joomla прилетает новый кейс. В нем речь уже идет о повышении привилегий . В этот же день на сайте Joomla появляется анонс о том, что во вторник, 25 октября, будет выпущена очередная версия с порядковым номером 3.6.3, которая исправляет критическую уязвимость в ядре системы.

    25 октября Joomla Security Strike Team находит последнюю проблему, которую создает обнаруженный Дэмисом кусок кода. Затем в главную ветку официального репозитория Joomla пушится коммит от 21 октября с неприметным названием Prepare 3.6.4 Stable Release , который фиксит злосчастный баг.

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

    27 октября исследователь Гарри Робертс (Harry Roberts) выкладывает в репозиторий Xiphos Research готовый эксплоит , который может загружать PHP-файл на сервер с уязвимой CMS.

    Детали

    Что ж, с предысторией покончено, переходим к самому интересному - разбору уязвимости. В качестве подопытной версии я установил Joomla 3.6.3, поэтому все номера строк будут актуальны именно для этой версии. А все пути до файлов, которые ты увидишь далее, будут указываться относительно корня установленной CMS.

    Благодаря находке Дэмиса Пальмы мы знаем, что есть два метода, которые выполняют регистрацию пользователя в системе. Первый используется CMS и находится в файле /components/com_users/controllers/registration.php:108 . Второй (тот, что нам и нужно будет вызвать), обитает в /components/com_users/controllers/user.php:293 . Посмотрим на него поближе.

    286: /** 287: * Method to register a user. 288: * 289: * @return boolean 290: * 291: * @since 1.6 292: */ 293: public function register() 294: { 295: JSession::checkToken("post") or jexit(JText::_("JINVALID_TOKEN")); ... 300: // Get the form data. 301: $data = $this->input->post->get("user", array(), "array"); ... 315: $return = $model->validate($form, $data); 316: 317: // Check for errors. 318: if ($return === false) 319: { ... 345: // Finish the registration. 346: $return = $model->register($data);

    Здесь я оставил только интересные строки. Полную версию уязвимого метода можно посмотреть в репозитории Joomla.

    Разберемся, что происходит при обычной регистрации пользователя: какие данные отправляются и как они обрабатываются. Если регистрация пользователей включена в настройках, то форму можно найти по адресу http://joomla.local/index.php/component/users/?view=registration .


    Легитимный запрос на регистрацию пользователя выглядит как на следующем скриншоте.


    За работу с пользователями отвечает компонент com_users . Обрати внимание на параметр task в запросе. Он имеет формат $controller.$method . Посмотрим на структуру файлов.

    Имена скриптов в папке controllers соответствуют названиям вызываемых контроллеров. Так как в нашем запросе сейчас $controller = "registration" , то вызовется файл registration.php и его метод register() .

    Внимание, вопрос: как передать обработку регистрации в уязвимое место в коде? Ты наверняка уже догадался. Имена уязвимого и настоящего методов совпадают (register), поэтому нам достаточно поменять название вызываемого контроллера. А где у нас находится уязвимый контроллер? Правильно, в файле user.php . Получается $controller = "user" . Собираем все вместе и получаем task = user.register . Теперь запрос на регистрацию обрабатывается нужным нам методом.


    Второе, что нам нужно сделать, - это отправить данные в правильном формате. Тут все просто. Легитимный register() ждет от нас массив под названием jform , в котором мы передаем данные для регистрации - имя, логин, пароль, почту (см. скриншот с запросом).

    • /components/com_users/controllers/registration.php: 124: // Get the user data. 125: $requestData = $this->input->post->get("jform", array(), "array");

    Наш подопечный получает эти данные из массива с именем user .

    • /components/com_users/controllers/user.php: 301: // Get the form data. 302: $data = $this->input->post->get("user", array(), "array");

    Поэтому меняем в запросе имена всех параметров с jfrom на user .

    Третий наш шаг - это нахождение валидного токена CSRF, так как без него никакой регистрации не будет.

    • /components/com_users/controllers/user.php: 296: JSession::checkToken("post") or jexit(JText::_("JINVALID_TOKEN"));

    Он выглядит как хеш MD5, а взять его можно, например, из формы авторизации на сайте /index.php/component/users/?view=login .


    Теперь можно создавать пользователей через нужный метод. Если все получилось, то поздравляю - ты только что проэксплуатировал уязвимость CVE-2016-8870 «отсутствующая проверка разрешений на регистрацию новых пользователей».

    Вот как она выглядит в «рабочем» методе register() из контроллера UsersControllerRegistration:

    • /components/com_users/controllers/registration.php: 113: // If registration is disabled - Redirect to login page. 114: if (JComponentHelper::getParams("com_users")->get("allowUserRegistration") == 0) 115: { 116: $this->setRedirect(JRoute::_("index.php?option=com_users&view=login", false)); 117: 118: return false; 119: }

    А так в уязвимом:

    • /components/com_users/controllers/user.php:

    Ага, никак.

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

    Продолжение доступно только участникам

    Вариант 1. Присоединись к сообществу «сайт», чтобы читать все материалы на сайте

    Членство в сообществе в течение указанного срока откроет тебе доступ ко ВСЕМ материалам «Хакера», увеличит личную накопительную скидку и позволит накапливать профессиональный рейтинг Xakep Score!

    Здравствуйте! Сейчас мы попробуем реализовать самую простую регистрацию на сайте с помощью PHP + MySQL. Для этого на вашем компьютере должен быть установлен Apache. Принцип работы нашего скрипта изображен ниже.

    1. Начнем с создания таблички users в базе . Она будет содержать данные пользователя (логин и пароль). Зайдем в phpmyadmin (если вы создаете базу на своем ПК http://localhost/phpmyadmin/ ). Создаем таблицу users , в ней будет 3 поля.

    Я создаю ее в базе mysql, вы можете создавать в другой базе. Далее устанавливаем значения, как на рисунке:

    2. Необходимо соединение с этой таблицей. Давайте создадим файл bd.php . Его содержание:

    $db = mysql_connect ("ваш MySQL сервер","логин к этому серверу","пароль к этому серверу");
    mysql_select_db ("имя базы, к которой подключаемся",$db);
    ?>

    В моем случае это выглядит так:

    $db = mysql_connect ("localhost","user","1234");
    mysql_select_db ("mysql",$db);
    ?>

    Сохраняем bd.php .
    Отлично! У нас есть таблица в базе, соединение к ней. Теперь можно приступать к созданию странички, на которой пользователи будут оставлять свои данные.

    3. Создаем файл reg.php с содержанием (все комментарии внутри):



    Регистрация


    Регистрация
















    4. Создаем файл , который будет заносить данные в базу и сохранять пользователя. save_user.php (комментарии внутри):



    {
    }
    //если логин и пароль введены, то обрабатываем их, чтобы теги и скрипты не работали, мало ли что люди могут ввести


    //удаляем лишние пробелы
    $login = trim($login);
    $password = trim($password);
    // подключаемся к базе
    // проверка на существование пользователя с таким же логином
    $result = mysql_query("SELECT id FROM users WHERE login="$login"",$db);
    if (!empty($myrow["id"])) {
    exit ("Извините, введённый вами логин уже зарегистрирован. Введите другой логин.");
    }
    // если такого нет, то сохраняем данные
    $result2 = mysql_query ("INSERT INTO users (login,password) VALUES("$login","$password")");
    // Проверяем, есть ли ошибки
    if ($result2=="TRUE")
    {
    echo "Вы успешно зарегистрированы! Теперь вы можете зайти на сайт. Главная страница";
    }
    else {
    echo "Ошибка! Вы не зарегистрированы.";
    }
    ?>

    5. Теперь наши пользователи могут регистрироваться! Далее необходимо сделать "дверь" для входа на сайт уже зарегистрированным пользователям. index.php (комментарии внутри) :

    // вся процедура работает на сессиях. Именно в ней хранятся данные пользователя, пока он находится на сайте. Очень важно запустить их в самом начале странички!!!
    session_start();
    ?>


    Главная страница


    Главная страница











    Зарегистрироваться



    // Проверяем, пусты ли переменные логина и id пользователя
    if (empty($_SESSION["login"]) or empty($_SESSION["id"]))
    {
    // Если пусты, то мы не выводим ссылку
    echo "Вы вошли на сайт, как гость
    Эта ссылка доступна только зарегистрированным пользователям";
    }
    else
    {

    В файле index.php мы выведем ссылочку, которая будет открыта только для зарегистрированных пользователей. В этом и заключается вся суть скрипта - ограничить доступ к каким-либо данным.

    6. Остался файл с проверкой введенного логина и пароля. testreg.php (комментарии внутри):

    session_start();// вся процедура работает на сессиях. Именно в ней хранятся данные пользователя, пока он находится на сайте. Очень важно запустить их в самом начале странички!!!
    if (isset($_POST["login"])) { $login = $_POST["login"]; if ($login == "") { unset($login);} } //заносим введенный пользователем логин в переменную $login, если он пустой, то уничтожаем переменную
    if (isset($_POST["password"])) { $password=$_POST["password"]; if ($password =="") { unset($password);} }
    //заносим введенный пользователем пароль в переменную $password, если он пустой, то уничтожаем переменную
    if (empty($login) or empty($password)) //если пользователь не ввел логин или пароль, то выдаем ошибку и останавливаем скрипт
    {
    exit ("Вы ввели не всю информацию, вернитесь назад и заполните все поля!");
    }
    //если логин и пароль введены,то обрабатываем их, чтобы теги и скрипты не работали, мало ли что люди могут ввести
    $login = stripslashes($login);
    $login = htmlspecialchars($login);
    $password = stripslashes($password);
    $password = htmlspecialchars($password);
    //удаляем лишние пробелы
    $login = trim($login);
    $password = trim($password);
    // подключаемся к базе
    include ("bd.php");// файл bd.php должен быть в той же папке, что и все остальные, если это не так, то просто измените путь

    $result = mysql_query("SELECT * FROM users WHERE login="$login"",$db); //извлекаем из базы все данные о пользователе с введенным логином
    $myrow = mysql_fetch_array($result);
    if (empty($myrow["password"]))
    {
    //если пользователя с введенным логином не существует
    }
    else {
    //если существует, то сверяем пароли
    if ($myrow["password"]==$password) {
    //если пароли совпадают, то запускаем пользователю сессию! Можете его поздравить, он вошел!
    $_SESSION["login"]=$myrow["login"];
    $_SESSION["id"]=$myrow["id"];//эти данные очень часто используются, вот их и будет "носить с собой" вошедший пользователь
    echo "Вы успешно вошли на сайт! Главная страница";
    }
    else {
    //если пароли не сошлись

    Exit ("Извините, введённый вами login или пароль неверный.");
    }
    }
    ?>

    Ну вот и все! Может урок и скучный, но очень полезный. Здесь показана только идея регистрации, далее Вы можете усовершенствовать ее: добавить защиту, оформление, поля с данными, загрузку аватаров, выход из аккаунта (для этого просто уничтожить переменные из сессии функцией unset ) и так далее. Удачи!

    Все проверил, работает исправно!

    Новое на сайте

    >

    Самое популярное