• Html to create a login page. Creating HTML Forms

    Instructions

    Start creating a registration form with the tag, between which you need to place additional tags that allow users to enter their own data into the form.

    Open the html file and start entering the code. The tag responsible for creating the form is “form”. We write down the tag along with the attributes “form action=”obrabotka.php” method=”post” name”forma1””. Let's start creating form elements. Almost all elements are made using the tag and its “type” attribute, which is responsible for the type of data, for example text, password, etc. We always set the name “name” to any of the attributes.

    Enter: "br" Enter your name: "br"

    "input type="text" name="fio""

    "br" Enter password: "br"

    "input type="password" name="pass""

    "br"Enter E-mail:l"br"

    "input type="text" name="email"".

    Next, we create a radio button selection element. A radio button is a form element that, when you click on it with the cursor, other radio buttons are turned off. Let's explain with an example of our form. When ordering a course, the choice will consist of either CD or DVD, so you need to choose one. The element of the “type” attribute – “radio” is responsible for creating such a button. We will specify the same name for the media type, so we will specify the “value” attribute so that the handler can accurately determine the value of the variable. We write the code: "br"Select the storage medium option: "br"

    "input type="radio" name="disc" value="cd"" CD "br"!}

    "input type="radio" name="disc" value="dvd"" DVD "br"!}

    If we add the “value” attribute to the text, the form will immediately display the value that we assigned to this attribute. For example, so that the full name form already contains some kind of name (value = “name”).

    Enter a different element and set type to "checkbox" to allow users to check more than one option on the form. For example:
    (Contact me when shipped)
    (Subscribe to)

    Create a "Submit" button by typing tag and type equal to "submit", value set to "Submit". In addition, in another tag, make a “Reset” button, setting the type to “reset” and the value to “Reset”, respectively. For example, like this:


    The Submit button is for submitting the data and the Reset button is for clearing the form if required.

    Enter a closing tag to complete the form. Save the page.

    Sources:

    • W3C Consortium website
    • product order form for the website

    The registration form is a built-in module of the Joomla panel. You don't need to be an expert in web programming to add it. However, if you decide to change it, you can implement it using the Community Builder component or manually. You just need to edit the necessary elements by studying the basics of website building.

    Instructions

    Go to the Joomla admin panel and open the built-in modules settings. Go to the “Advanced” tab and click on the “Create” button. The “Modules Manager” window will appear, in which you need to select and activate the registration form. Specify the desired title for the title and check the box next to the “Show title” line.

    Open the "Initial text" section in the registration form module and edit the standard text for visitors if it does not suit you. In the “Login” item, you can choose how the user will be called on the site: under your name or login. Click the "Save" button for the changes to take effect.

    Upload the Community Builder component to your site. To do this, go to the “Upload package file” section and click the “Browse” button. After selecting the required documents, click on the “Download and Install” button. Go to the admin panel and run the installed component.

    Open the “Registration” tab and make all necessary changes to the registration form. This application is very convenient to use, but if you only want to change one or two fields, it will be more convenient to edit manually.

    Create a backup copy of the files that you will modify to make adjustments to the registration form. This will allow you to roll back all actions and restore the site to functionality in case of failure. Determine which fields you want to edit or add. For example, you want to add a “City” field to the registration form.

    Open the default.php file, which is located at components/com_user/views/register/tmpl. Add a “Cities” display by inserting the appropriate HTML code into the registration form. To do this, you can copy any other item and edit it for the city. Make these changes to the jos_users table. Open the user.php file, which is located at libraries/joomla/database/table. Add a new variable to it. Save the settings and restart the site.

    Sources:

    • how to change module in joomla
    Tip 7: How to make a temporary registration without an owner

    Happy new settlers are not always able to fulfill the requirement of the law on registration at the place of residence (to make a temporary registration) within the established period of 90 days. Sometimes the reason for this may be the reluctance or inability of the apartment owner to appear at the relevant organization to carry out registration actions.

    Of course, if the owner has not expressed a desire to legalize your temporary stay in his residential premises, then you will not be able to register. The exception is when you register your minor child at your place of registration. In this case, there is no need to obtain the owner's consent.

    But if the problem with temporary registration is only the lack of desire on the part of the owner to visit with you the employees responsible for accepting documents for registration, then the regulations provide for the possibility of obtaining temporary registration without the presence of the owner.

    If the basis for moving in is a rental agreement, then you can send a notarial agreement by mail with other documents attached (copy of passport, completed application). In such a situation, the persons responsible for accepting documents do not have the obligation to certify a copy of this agreement, and the owner of the premises does not sign the application.

    If it is possible to submit only the agreement in simple written form, then the responsible persons are required to certify the signature of the owner and the registered person in the application. In this situation, the presence of the owner cannot be avoided.

    A certificate of registration at the place of residence can also be obtained by mail.

    Although the presence of the owner when obtaining temporary registration is not required, you should not hope that he will not find out about the new residents. After the registration actions have been completed, the FMS authorities will send him a notification about the person registered in his living space.

    Tip 8: How to fill out the 3-NDFL form for selling a car

    If you sold a car that you owned for more than three years, you don’t have to read any further: starting in 2011, your rights to a property tax deduction are automatically recognized. This means that you do not have to file a return. But if you have owned it for a shorter period of time, you will have to fill out the necessary papers. The easiest way to do this is using the Declaration program.

    You will need

    • - computer;
    • - Internet access;
    • - “Declaration” program from GNIIVS of the Federal Tax Service of the Russian Federation;
    • - car purchase and sale agreement;
    • - documents confirming your other income and payment of personal income tax on it for the past year.

    Instructions

    You can download the latest version of the program on the website of the Main Research Center of the Federal Tax Service (GNIVC FTS) of Russia. It spreads

    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 Your Full Name*: Email Address*: UserName*: Password*:

    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 ,". ")"; 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!

    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.

    Hello! Now we will try to implement the simplest registration on the site using PHP + MySQL. To do this, Apache must be installed on your computer. The working principle of our script is shown below.

    1. Let's start by creating a users table in the database. It will contain user data (login and password). Let's go to phpmyadmin (if you are creating a database on your PC http://localhost/phpmyadmin/). We create a table users , it will have 3 fields.

    I create it in the mysql database, you can create it in another database. Next, set the values ​​as in the figure:

    2. A connection to this table is required. Let's create a bd.php file. Its content:

    In my case it looks like this:

    Save bd.php .
    Great! We have a table in the database and a connection to it. Now you can start creating a page on which users will leave their data.

    3. Create a reg.php file with the contents (all comments inside):



    Registration


    Registration


    Your login:




    Your password:








    4. Create a file that will enter data into the database and save the user. save_user.php (comments inside):

    5. Now our users can register! Next, you need to create a “door” for already registered users to enter the site. index.php (comments inside) :




    Home page


    Home page


    Your login:


    Your password:






    Register



    Well that's it! The lesson may be boring, but very useful. Only the idea of ​​registration is shown here, then you can improve it: add security, design, data fields, loading avatars, logging out of your account (to do this, simply destroy variables from the session with the unset function) and so on. Good luck!

    I checked everything, it works properly!

    The process of creating a registration system is quite a lot of work. You need to write code that double-checks the validity of email addresses, sends confirmation emails, offers the ability to recover passwords, stores passwords in a safe place, validates input forms, and much more. Even when you do all this, users will be reluctant to register, since even the most minimal registration requires their activity.

    In today's tutorial, we'll be developing a simple registration system that won't require any passwords! The results will be a system that can be easily modified or integrated into an existing PHP website. If you're interested, keep reading.

    PHP

    Now we're ready to get started with the PHP code. The main functionality of the registration system is provided by the User class, which you can see below. The class uses (), which is a minimalist database library. The User class is responsible for accessing databases, generating login tokens and validating them. It presents us with a simple interface that can be easily incorporated into the registration system of your PHP based websites.

    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 session
    $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;
    }
    }
    Tokens are generated using an algorithm and stored in a database. We use MySQL to set the token_validity column to 10 minutes. When validating a token, we tell the engine that we need a token, the token_validity field has not yet expired. This way we limit the time during which the token will be valid.

    Notice that we use the magic __get() method at the end of the document to access the properties of the user object. This allows us to access data that is stored in the database as properties: $user->email, $user->token. As an example, let's see how we can use this class in the following code snippet:


    Another file that stores the necessary functionality is functions.php. There we have a few helper functions that allow us to keep the rest of the code neater.

    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;
    }
    The rate_limit and rate_limit_tick functions allow us to limit the number of authorization attempts for a certain period of time. Authorization attempts are recorded in the reg_login_attempt database. These functions are triggered when the login form is verified, as you can see in the following code snippet.

    The code below was taken from index.php and is responsible for validating the login form. It returns a JSON response that is driven by the jQuery code we saw in 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 to 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()
    )));
    }
    Upon successful authorization or registration, the above code sends an email to the person with a link for authorization. The token is made available as a $_GET variable "tkn" due to the generated 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");
    }
    Running $user->login() will create the necessary session variables, allowing the user to remain logged in on subsequent logins.

    Logging out of the system is implemented in approximately the same way:

    Index.php

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

    $user = new User();

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

    Redirect("index.php");
    }
    At the end of the code, we redirect the user to index.php again, so the ?logout=1 parameter in the URL is eliminated.

    Our index.php file will also need protection - we don't want already logged in users to see the form. To do this we use the $user->loggedIn() method:

    Index.php

    $user = new User();

    if($user->loggedIn())(
    redirect("protected.php");
    }
    Finally, let's look at how you can protect your website page and make it accessible only after authorization:

    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");
    }
    After this check, you can be sure that the user has successfully logged in. You will also have access to data that is stored in the database as properties of the $user object. To display the user's email and their rank, use the following code:

    Echo "Your email: ".$user->email;
    echo "Your rank: ".$user->rank();
    Here rank() is the method because the rank column in the database usually contains numbers (0 for regular users and 1 for administrators) and we need to convert all of these into rank names, which is implemented using this method. To convert a standard user to an administrator, simply edit the user's entry in phpmyadmin (or any other database program). As an administrator, the user will not be granted any special capabilities. You yourself have the right to choose what rights to grant administrators.

    Ready!

    With this our simple registration system is ready! You can use it on an existing PHP site, or modernize it to suit your own requirements.

    Reg.ru: domains and hosting

    The largest registrar and hosting provider in Russia.

    More than 2 million domain names in service.

    Promotion, domain mail, business solutions.

    More than 700 thousand customers around the world have already made their choice.

    *Mouse over to pause scrolling.

    Back Forward

    Creating a simple user registration system in PHP and MySQL

    Creating a registration system is a lot of work. You have to write code that validates email addresses, sends an email confirming registration, and also validates other form fields, and much more.

    And even after you write all this, users will be reluctant to register, because... this requires some effort on their part.

    In this tutorial, we will create a very simple system registration that does not require or store passwords at all! The result will be easy to modify and add to an existing PHP site. Want to find out how it works? Read below.



    Here's how our super simple system will work:

    We will combine the authorization form and registration. This form will have a field for entering your email address and a registration button;
    - When filling out the field with an email address, clicking on the registration button will create a record about a new user, but only if the entered email address was not found in the database.

    After this, a random unique set of characters (token) is created, which is sent to the user-specified email in the form of a link that will be relevant for 10 minutes;
    - The link takes the user to our website. The system determines the presence of a token and authorizes the user;

    Advantages of this approach:

    There is no need to store passwords or validate fields;
    - There is no need to recover your password, security questions, etc.;
    - From the moment a user registers/logs in, you can always be sure that this user will be in your access zone (that the email address is true);
    - Incredibly simple registration process;

    Flaws:

    User account security. If someone has access to the user's mail, they can log in.
    - Email is not secure and can be intercepted. Keep in mind that this question is also relevant in the case where the password has been forgotten and needs to be restored, or in any authorization system that does not use HTTPS for data transfer (login/password);
    - While you configure your mail server properly, there is a chance that messages with authorization links will end up in spam;

    Comparing the advantages and disadvantages of our system, we can say that the system has high usability (maximum convenience for the end user) and, at the same time, has a low security indicator.

    So it is suggested to use it for registrations on forums and services that do not work with important information.

    How to use this system

    In case you just need to use a system to authorize users on your site, and you don’t want to take this lesson apart, here’s what you need to do:

    You need to download the sources attached to the lesson
    - Find the tables.sql file in the archive. Import it into your database using the import option in phpMyAdmin. Alternative way: open this file through a text editor, copy the SQL query and execute it;
    - Open includes/main.php and fill in the settings for connecting with your database (specify the user and password for connecting with the database, as well as the host and name of the database). In the same file, you must also specify the email, which will be used as the original address for messages sent by the system. Some hosts block outgoing emails until the real one is indicated in the form. email address, which was created from the host control panel, so provide a real address;
    - Upload all index.php , protected.php files and assets and includes folders via FTP to your host;
    - Add the code below to each PHP page where you want to display the login form;

    Require_once "includes/main.php"; $user = new User(); if(!$user->loggedIn())( redirect("index.php"); )
    - Ready!

    For those who are interested in how it all works, read on below!

    The first step is to write the HTM code for the authorization form. This code is located in the index.php file. This file also contains PHP code that processes form data and other useful features authorization systems. You can learn more about this in the section below dedicated to the PHP code review.

    index.php

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

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

    Login/Register

    In the head section (between the and tags) I included the main styles (they are not covered in this tutorial, so you can look at them yourself. Folder assets/css/style.css). Before the closing tag, I included the jQuery library and the script.js file, which we will write and analyze below.


    JavaScript

    jQuery tracks the state of the "Register/Login" button using the function e.preventDefault() and sends AJAX requests. Depending on the server response, it displays one or another message and determines further actions/

    assets/js/script.js

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

    was added to the form to display the current state of the AJAX request (this was made possible thanks to the methods ajaxStart()) And ajaxComplete(), which you can find towards the end of the file).

    This class displays a spinning animated gif file (as if to hint to us that the request is being processed), and also acts as a flag to prevent the form from being submitted again (when the register button has already been clicked once). The .loggedIn class is another flag - it is set when the email was sent. This flag immediately blocks any further actions with the form.

    Database schema

    Our incredibly simple logging system uses 2 MySQL tables (the SQL code is in the tables.sql file). The first stores data about user accounts. The second stores information about the number of login attempts.


    User table schema.

    The system does not use passwords, as can be seen in the diagram. On it you can see the token column with tokens adjacent to the token_validity column. The token is installed as soon as the user connects to the system and sets his email to send a message (more on this in the next block). The token_validity column sets the time 10 minutes later, after which the token is no longer valid.


    Table schema that counts the number of authorization attempts.

    In both tables, the IP address is stored in processed form, using the ip2long function in a field of type integer.

    Now we can write some PHP code. The main functionality of the system is assigned to the class User.class.php, which you can see below.

    This class actively uses idorm (docs), these libraries are the minimum necessary tools for working with databases. It handles database access, token generation, and token validation. It provides a simple interface that makes it easy to connect a registration system to your site if it uses PHP.

    User.class.php

    Class User( // Private ORM case private $orm; /** * Find a user by token. Only valid tokens are accepted for consideration. The token is generated only for 10 minutes from the moment it was created * @param string $token. This is the one we are looking for token * @return User. Return the value of the User function */ public static function findByToken($token)( // find the token in the database and make sure the correct timestamp is set $result = ORM::for_table("reg_users") ->where ("token", $token) ->where_raw("token_validity > NOW()") ->find_one(); if(!$result)( return false; ) return new User($result) /** *); Authorize or register a user * @param string $email. User email address * @return User */ public static function loginOrRegister($email)( // If such a user already exists, return the value of the User function from the specified email address stored in the database if(User::exists($email))( return new User($email); ) // Otherwise, create a new user in the database and return the value of the User::create function from the specified email return User::create($email ); ) /** * Create a new user and save to the database * @param string $email. User email address * @return User */ private static function create($email)( // Write a new user and return the result of the User function from these values ​​$result = ORM::for_table("reg_users")->create(); $result->email = $email; $result->save(); return new User($result); /** * Check if such a user exists in the database and return the boolean value of the variable * @param string $email. User 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 instance $param ORM , id, email or 0 * @return User */ public function __construct($param = null) ( if($param instanceof ORM)( // ORM check passed $this->orm = $param; ) else if(is_string($param))( // Email check passed $this->orm = ORM::for_table ("reg_users") ->where("email", $param) ->find_one(); ) else( $id = 0; if(is_numeric($param))( // the value of the variable $param $id is passed to the user identifier = $param; ) else if(isset($_SESSION["loginid"]))( // Otherwise, see session $id = $_SESSION["loginid"]; ) $this->orm = ORM::for_table( "reg_users") ->where("id", $id) ->find_one() ) ) /** * Generate a new SHA1 authorization token, writes it to the database and returns its value * @return string */ public function generateToken( )( // Generate a token for an authorized user and save it to the database $token = sha1($this->email.time().rand(0, 1000000)); // Save the token in the database // And mark it that it is only valid for the next 10 minutes $this->orm->set("token", $token); $this->orm->set_expr("token_validity", "ADDTIME(NOW(),"0:10")"); $this->orm->save(); return $token; ) /** * Authorize the user * @return void */ public function login())( // Mark the user as logged in $_SESSION["loginid"] = $this->orm->id; // Update the value of the last_login database field $this->orm->set_expr("last_login", "NOW()"); $this->orm->save(); ) /** * Destroy the session and log out the user * @return void */ public function logout ()( $_SESSION = array(); unset($_SESSION); ) /** * Check if the user is logged in * @return boolean */ public function loggedIn())( return isset($this->orm->id) && $_SESSION["loginid"] == $this->orm->id ) /** * Checks whether the user is an administrator * @return boolean */ public function isAdmin())( return $this->rank() = = "administrator"; ) /** * Find the user type, can be either administrator or regular * @return string */ public function rank())( if($this->orm->rank == 1)( return "administrator" "; ) return "regular"; ) /** * Method that allows you to get the user's private information *as properties of the User object * @param string $key The name of the property that gets access * @return mixed */ public function __get($key)( if(isset($this->orm->$key))( return $this->orm->$key; ) return null; ) )

    Tokens are generated using the SHA1 algorithm and stored in the database. I'm using MySQL's timing functions to set a 10-minute time limit for a token's validity.

    When a token is validated, we directly tell the handler that we are only considering tokens that have not yet expired, stored in the token_validity column.

    Please note that I am using the magic method __get docs library at the end of the file to intercept access to the properties of the User object.

    Thanks to this, it becomes possible to access information stored in the database, thanks to the properties $user->email, $user->token, etc. In the next code fragment, we will look at how to use these classes as an example.


    Protected page

    Another file that stores useful and necessary functionality is the functions.php file. There are several so-called helpers - assistant functions that allow you to create cleaner and more readable code in other files.

    functions.php

    Function send_email($from, $to, $subject, $message)( // Helper that sends 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())( // Determine the URL of the 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)( // Number of login attempts in the last hour for this IP address $count_hour = ORM: :for_table("reg_login_attempt") ->where("ip", sprintf("%u", ip2long($ip))) ->where_raw("ts > SUBTIME(NOW(),"1:00")") ->count(); // Number of login attempts in the last 10 minutes for 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 new entry in the table that counts the number of login attempts $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; )

    Functions rate_limit And rate_limit_tick monitor the number of authorization attempts over the elapsed period of time since the first attempt. The login attempt is recorded in the database in the reg_login_attempt column. These functions are called when the form data is processed and submitted as you can see from the following code snippet.

    The code below is taken from the index.php file and it handles the form submission. It returns a JSON response, which in turn is processed by jQuery in the assets/js/script.js file that we looked at earlier.

    index.php

    Try( if(!empty($_POST) && isset($_SERVER["HTTP_X_REQUESTED_WITH"]))( // Output a JSON header header("Content-type: application/json"); // Is this email address valid if(!isset($_POST["email"]) || !filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))( throw new Exception("Please enter a valid email."); ) // Check. Is the user allowed to log in, has he exceeded the number of allowed connections? (functions.php file for more information) rate_limit($_SERVER["REMOTE_ADDR"]); // Record this authorization attempt rate_limit_tick($_SERVER["REMOTE_ADDR"], $ _POST["email"]); // Send an email to the user $message = ""; $email = $_POST["email"]; $subject = "Your Login Link"; )( $subject = "Thank You For Registering!"; $message = "Thank you for registering at our site!\n\n"; ) // Attempt to authorize or register a user $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 to 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() )));

    After successful login/registration, the code above will send the user a login link. The token becomes available because it is passed as a variable in the generated link by the method $_GET with tkn marker

    index.php

    If(isset($_GET["tkn"]))( // Is this token valid for authorization? $user = User::findByToken($_GET["tkn"]); if($user)( // Yes , is. Redirect to the protected page $user->login(); redirect("protected.php"); // No, the token is not valid. Redirect to the page with the authorization/registration form redirect("index.php). "); )

    $user->login()

    will create the necessary variables for the session, so that the user, viewing subsequent pages of the site, will remain authorized at all times.

    The processing of the function to exit the system is arranged in a similar way.

    index.php

    If(isset($_GET["logout"]))( $user = new User(); if($user->loggedIn())( $user->logout(); ) redirect("index.php") ; )

    At the end of the code, I again set a redirect to index.php, so the parameter ?logout=1 transmitted via URL is not required.

    Our index.php file requires additional. protection - we don't want people who have logged into the system to see the registration form again. For these purposes, we use the method $user->loggedIn().

    index.php

    $user = new User(); if($user->loggedIn())( redirect("protected.php"); )

    Finally, here is a piece of code that allows you to protect the pages of your site and make it accessible only after authorization.

    protected.php

    // To protect every page on your site, include a main.php file // and create a new User object. That's how easy it is! require_once "includes/main.php"; $user = new User(); if(!$user->loggedIn())( redirect("index.php"); )

    After this check, you can be sure that the user was successfully authorized. You can also access stored information in the database using object properties $user. To display the user's email and status, use this code:

    Echo "Your email: ".$user->email; echo "Your rank: ".$user->rank();

    Method rank() is used here because the database usually stores numbers (0 for a regular user, 1 for an administrator) and we need to convert this data into the statuses to which they relate, which is what this method helps us with.

    To make a regular user an administrator, simply edit the user entry through phpMyAdmin (or any other program that allows you to manage databases). Administrator status does not provide any privileges, including in this example the page will display that you are an administrator - and that’s it.

    But what to do with this is left to your discretion; you can write and compose code yourself that sets certain privileges and capabilities for administrators.

    We're done!

    We're done with this incredibly super quasi simple shape! You can use it in your PHP sites, it's quite simple. You can also modify it for yourself and make it the way you want.

    The material was prepared by Denis Malyshok specifically for the website

    P.S. Do you want to move further in mastering PHP and OOP? Pay attention to premium lessons on various aspects of website building, including PHP programming, as well as free course on creating your own CMS system in PHP from scratch using OOP:

    Did you like the material and want to thank me?
    Just share with your friends and colleagues!