Hardware and software setup

Powerless auth php. HTTP Setting page security using MySQL and PHP

We will learn how to do simple user authentication on the site. The site can have pages only for authorized users and they will fully function if we add our authentication block to them. To create it, you need a base MySQL data. It can have 5 columns (minimum) or more if you want to add information about users. Let's name the database "Userauth".

Let's create the following fields in it: ID for counting the number of users, UID for the unique identification number of the user, Username for the username, Email for his address Email and Password for the password. You can use the user and the database you already have for authorization, only, as in the case of a new database, create the following table in it.

MySQL code

CREATE TABLE `users` (`ID` int (11) NOT NULL AUTO_INCREMENT, `UID` int (11) NOT NULL, `Username` text NOT NULL, `Email` text NOT NULL, `Password` text NOT NULL, PRIMARY KEY (`ID`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Now let's create the "sql.php" file. It is responsible for connecting to the database. This code firstly creates variables for the server and the user when it connects to the server. Second, it will select the database, in this case "USERAUTH". This file must be included in "log.php" and "reg.php" to access the database.

PHP code

//Your MySQL username$pass = "redere"; //password $conn = mysql_connect ($server, $user, $pass); //connection to server$db = mysql_select_db("userauth", $conn); //select database if (!$db) ( //if can't select database echo "Sorry, error:(/>"; //Show error message exit(); //Allows other PHP scripts to run } ?>

Next is the login page, let's call it "login.php". First, it checks the entered data for errors. The page has fields for username, password, a submit button, and a registration link. When the user clicks the "Login" button, the form will be processed by the code from the "log.php" file, and then the login will occur.

PHP code

0) { //if there are session errors$err = "

"; //Start a table foreach ($_SESSION["ERRMSG"] as $msg) ( //recognize each error$err .= " "; //write it into a variable) $err .= "
" . $msg . "
"; //closing the table unset($_SESSION["ERRMSG"]); //delete session } ?> Login form
Username
Password
registration

Then we write a script for logging in. Let's name it "log.php". It has a feature to clean up SQL injection inputs that can mess up your script. Second, it receives the form data and validates it for validity. If the input data is correct, the script sends the user to the authorized users page, if not, it fixes errors and sends the user to the login page.

PHP code

//start session for recording function Fix($str) ( //clear fields $str = trim($str); if (get_magic_quotes_gpc()) ( $str = stripslashes ($str); ) //array to store errors$errflag = false ; //error flag $username = Fix($_POST["username"]); //Username$password = Fix($_POST["password"]);//password ) //check password if ($password == "") ( $errmsg = "Password missing"; //error $errflag = true ; //raise flag on error ) //if the error flag is raised, redirects back to the registration form // logs errors session_write_close(); //closing the session //redirect exit(); ) //request to the database$qry = "SELECT * FROM `users` WHERE `Username` = "$username" AND `Password` = "" . md5 ($password) . """; $result = mysql_query($qry); // check if the request was successful (if there is data on it) if (mysql_num_rows ($result) == 1) ( while ($row = mysql_fetch_assoc ($result)) ( $_SESSION["UID"] = $row["UID"]; //get the UID from the database and put it into the session$_SESSION["USERNAME"] = $username; //sets if the username matches the session one session_write_close(); //closing the session header("location: member.php"); //redirect) ) else ( $_SESSION["ERRMSG"] = "Invalid username or password"; //error session_write_close(); //closing the session header("location: login.php"); //redirect exit(); ) ?>

Let's make a registration page, let's call it "register.php". It is similar to the login page, only it has a few more fields, and instead of a registration link, a link to login.php in case the user already has an account.

PHP code

0) { //if there are session errors$err = "

"; //beginning of table foreach ($_SESSION["ERRMSG"] as $msg) ( // sets each error$err .= " "; //writes them into a variable) $err .= "
" . $msg . "
"; // end of table unset ($_SESSION["ERRMSG"]); //destroys the session } ?> Registration form
Username
Email
Password
Password repeat
I have an account

Now let's make a registration script in the "reg.php" file. It will include "sql.php" to connect to the database. The same function is used as in the login script to clear the input field. Variables are set for possible errors. Next is a function to create a unique identifier that has never been provided before. The data is then retrieved from the registration form and validated. It checks that the e-mail address is specified in desired format, and whether the password you re-entered is correct. The script then checks to see if there is a user with the same name in the database, and if so, reports an error. And finally, the code adds the user to the database.

PHP code

//start session for recording function Fix($str) ( //clear fields $str = @trim($str); if (get_magic_quotes_gpc()) ( $str = stripslashes ($str); ) return mysql_real_escape_string($str); ) $errmsg = array(); //array to store errors$errflag = false ; //error flag $UID = "12323543534523453451465685454";//unique ID $username = Fix($_POST["username"]); //Username$email = $_POST["email"]; //Email $password = Fix($_POST["password"]);//password $rpassword = Fix($_POST["rpassword"]);//password repeat //check username if ($username == "") ( $errmsg = "Username missing"; //error $errflag = true ; //raise flag on error) //check Email if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@+(\.+)*(\.(2,3 ))$", $email)) ( //must follow the format: [email protected]$errmsg = "Invalid Email"; //error $errflag = true ; //raise flag on error } //check password if ($password == "") ( $errmsg = "Password missing"; //error $errflag = true ; //raise flag on error } //check password repeat if ($rpassword == "") ( $errmsg = "Repeated password missing";//error $errflag = true ; //raise flag on error } // check if the password is valid if (strcmp($password, $rpassword) != 0) ( $errmsg = "Passwords do not match";//error $errflag = true ; //raise flag on error } //check if the username is free if ($username != "") ( $qry = "SELECT * FROM `users` WHERE `Username` = "$username""; // query MySQL $result = mysql_query ($qry); if ($result) ( if (mysql_num_rows ($result) > 0) ( //if the name is already in use$errmsg = "Username already in use"; //error message$errflag = true; //raise flag on error) mysql_free_result($result); ) ) //if the data is not validated, redirects back to the registration form if ($errflag) ( $_SESSION["ERRMSG"] = $errmsg; //error message session_write_close(); //closing the session header("location: register.php"); //redirect exit(); ) //adding data to the database$qry = "INSERT INTO `userauth`.`users`(`UID`, `Username`, `Email`, `Password`) VALUES("$UID","$username","$email","" . md5 ($password) . "")"; $result = mysql_query($qry); //check if the add request was successful if ($result) ( echo "Thank you for registering, " .$username . ". Please login here"; exit (); ) else ( die ("Error, check back later"); ) ?>

You also need to make a script to log the user out of the system. It terminates the session for the user with the given unique id and name, and then redirects the user to the login page.

PHP code

Finally, the "auth.php" script can be used to make pages accessible only to authorized users. It checks the login data and, if it is correct, allows the user to view the pages, and if not, asks to log in. In addition, if someone tries to hack the site by creating one of the sessions, it will be aborted, as in the general case.

PHP code

One of the conditions in the code above is the subject of the question in .

The following code needs to be inserted on the page for authorized users, it is called, for example, "member.php", and you can call it whatever you like.

PHP code

You are authorized to access this page. Log off ( )

User authentication is ready!

Good day friends! Let's take a look at user registration in PHP. First, let's define the conditions for our user registration:

  • The password is encrypted using an algorithm MD5
  • The password will be "salt"
  • Login busy check
  • User activation by letter.
  • Recording and storage of data in DBMS MySQL

For writing this script we need to understand what user registration is. User registration is the acquisition of real user data, processing and storage of data.

If you explain in simple words then registration is just a record and storage of certain data by which we can authorize the user in our case - this is the Login and Password.

Authorization - granting a certain person or group of persons the rights to perform certain actions, as well as the process of verifying these rights when trying to perform these actions. Simply put, with the help of authorization, we can restrict access to a particular content on our site.

Let's take a look at the script directory structure to implement our login with authorization. We need to break scripts into logical parts. We placed the registration and authorization modules in a separate directory. We will also place the database connection in separate directories. MySQL, file with custom functions, style file css and our template HTML. This structure allows you to quickly navigate through scripts. Imagine that you have a big site with a bunch of modules and so on. and if there is no order, it will be very difficult to find something in such a mess.

Since we will store all data in DBMS MySQL, then let's create a small table in which we will store registration data.

First you need to create a table in the database. Let's call the table bez_reg where bez is the table prefix, and reg table name.

Table structure: bez_reg

-- -- `bez_reg` table structure -- CREATE TABLE IF NOT EXISTS `bez_reg` (`id` int(11) NOT NULL AUTO_INCREMENT, `login` varchar(200) NOT NULL, `pass` varchar(32) NOT NULL , `salt` varchar(32) NOT NULL, `active_hex` varchar(32) NOT NULL, `status` int(1) NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Now let's create the main scripts for further work.

INDEX.PHP FILE

CONFIG.PHP FILE

"); ?>

File 404.HTML

Error 404

Error 404

There was a 404 error on the page

Return

BD.PHP file

INDEX.HTML FILE

PHP MySQL user registration with activation email

FUNCT.PHP FILE

"."\n"; if(is_array($data)) ( foreach($data as $val) $err .= "

  • ".$val."
  • "."\n"; ) else $err .= "
  • ".$data."
  • "."\n"; $err .= ""."\n"; return $err; ) /**Simple MySQL query wrapper * @param string $sql */ function mysqlQuery($sql) ( $res = mysql_query($sql); /* Check result This is shows the actual query sent to MySQL as well as the error.*/ if(!$res) ( $message = "Bad query: " . mysql_error() . "\n"; $message .= "Entire query : " . $sql; die($message); ) return $res; ) /**Simple salt generator * @param string $sql */ function salt() ( $salt = substr(md5(uniqid()), - 8); return $salt; )

    Let's start writing registration. To begin with, we will need to make a registration form template so that the user can enter his data for processing. Next, we will need to write the form handler itself, which will check the correctness of the user's entered data. After the data is successfully verified, we write it to our database and send an email to the user to activate his account.

    REG.PHP FILE

    You have successfully registered! Please activate your account!!"; //Activate the account if(isset($_GET["key"])) ( //Check the key $sql = "SELECT * FROM `". BEZ_DBPREFIX ."reg` WHERE `active_hex` = "". escape_str( $_GET["key"]) ."""; $res = mysqlQuery($sql); if(mysql_num_rows($res) == 0) $err = "Activation key is invalid!"; //Check for errors and display to the user if(count($err) > 0) echo showErrorMessage($err); else ( //Get the user's address $row = mysql_fetch_assoc($res); $email = $row["login"]; //Activate the account user $sql = "UPDATE `".BEZ_DBPREFIX ."reg` SET `status` = 1 WHERE `login` = "".$email ."""; $res = mysqlQuery($sql); //Send activation email $title = "(!LANG:Your account at http://website has been successfully activated"; $message = "Поздравляю Вас, Ваш аккаунт на http://сайт успешно активирован"; sendMessageMail($email, BEZ_MAIL_AUTOR, $title, $message); /*Перенаправляем пользователя на нужную нам страницу*/ header("Location:". BEZ_HOST ."less/reg/?mode=reg&active=ok"); exit; } } /*Если нажата кнопка на регистрацию, начинаем проверку*/ if(isset($_POST["submit"])) { //Утюжим пришедшие данные if(empty($_POST["email"])) $err = "Поле Email не может быть пустым!"; else { if(!preg_match("/^!} [email protected](+\.)+(2,6)$/i", $_POST["email"])) $err = "Email entered incorrectly"."\n"; ) if(empty($_POST[ "pass"])) $err = "Password field cannot be empty"; if(empty($_POST["pass2"])) $err = "Password Confirmation field cannot be empty"; //Check for errors and display to the user if(count($err) > 0) echo showErrorMessage($err); else ( /*Continue to check the entered data Check for matching passwords*/ if($_POST["pass"] != $_POST["pass2" ]) $err = "Passwords do not match"; //Check for errors and display to the user if(count($err) > 0) echo showErrorMessage($err); else ( /*Check if we have such a user in the database* / $sql = "SELECT `login` FROM `".BEZ_DBPREFIX ."reg` WHERE `login` = "".escape_str($_POST["email"]) ."""; $res = mysqlQuery($sql); if(mysql_num_rows($res) > 0) $err = "Sorry Login: ". $_POST["email"] ." busy!"; //Check for errors and display to the user if(count($err) > 0) echo showErrorMessage($err); else ( //Get the HASH of the salt $salt = salt(); //Salt the password $pass = md5(md5($_POST["pass"]).$salt); /*If all goes well, write data to the database*/ $sql = "INSERT INTO `". BEZ_DBPREFIX ."reg` VALUES("", "" .escape_str($_POST["email"]) ."", "". $pass ."", "". $salt ."", "". md5($salt) ."", 0)"; $ res = mysqlQuery($sql); //Send activation email $url = BEZ_HOST ."less/reg/?mode=reg&key=". md5($salt); $title = "(!LANG:Registration on http:/ /site"; $message = "Для активации Вашего акаунта пройдите по ссылке ". $url .""; sendMessageMail($_POST["email"], BEZ_MAIL_AUTOR, $title, $message); //Сбрасываем параметры header("Location:". BEZ_HOST ."less/reg/?mode=reg&status=ok"); exit; } } } } ?>!}

    REG_FORM.HTML FILE

    PHP MySQL user registration with activation email

    Email *:
    Password *:
    Password confirmation *:

    Fields with an icon * required

    Since our user registration is ready, it's time to write authorization. We will create a form for user authorization, then we will write an authorization form handler and, finally, we will make a script show.php which will show us whether we are authorized in the system or not.

    AUTH.PHP FILE

    0) echo showErrorMessage($err); else ( /*Create a database fetch query to authenticate the user*/ $sql = "SELECT * FROM `". BEZ_DBPREFIX ."reg` WHERE `login` = "". escape_str($_POST["email"]) ."" AND `status` = 1"; $res = mysqlQuery($sql); //If login matches, check password if(mysql_num_rows($res) > 0) ( //Get data from table $row = mysql_fetch_assoc( $res); if(md5(md5($_POST["pass"]).$row["salt"]) == $row["pass"]) ( $_SESSION["user"] = true; // Reset parameters header("Location:". BEZ_HOST ."less/reg/?mode=auth"); exit; ) else echo showErrorMessage("Wrong password!"); ) else echo showErrorMessage("Login ". $_POST["email"] ." not found!"); ) ) ?>

    For those who have the latest version of PHP, I post this script using PDO because extension MySQL is deprecated and has been removed from the new version of PHP. Download registration and authorization php mysql pdo

    The archive was updated on February 24, 2015.

    Attention: If you are using this script on a local server like DENWER,XAMPP, then you should not wait for letters to your mailbox. Letters are in the stub sendmail. V Denver you can find them along the way Z:\tmp\!sendmail\ You can open these files in any email client.

    It is possible to use the function header() to send a message "Authentication Required" browser, forcing it to show a window for entering a username and password. Once the user has filled in the login and password, the link containing the PHP script will be called again with the predefined variables PHP_AUTH_USER , PHP_AUTH_PW , and AUTH_TYPE set to login, password and authentication type respectively. These predefined variables are stored in the $_SERVER and $HTTP_SERVER_VARS arrays. Both types are supported: "Basic" and "Digest" (as of PHP 5.1.0). See function for details. header().

    An example of a script fragment that forces the client to log in to view the page:

    Beispiel #1 Basic HTTP authentication example

    if (!isset($_SERVER [ "PHP_AUTH_USER" ])) (
    header( "WWW-Authenticate: Basic realm="My Realm"");

    echo "Text to be sent if
    if the user clicked the Cancel button"
    ;
    exit;
    ) else (
    echo
    "

    Hello ( $_SERVER [ "PHP_AUTH_USER" ]) .

    " ;
    echo "

    You have entered a password( $_SERVER [ "PHP_AUTH_PW" ]) .

    " ;
    }
    ?>

    Beispiel #2 Digest HTTP authentication example

    This is an example implementation of a simple Digest HTTP authentication script. See » RFC 2617 for details.

    $realm = "Restricted area" ;

    //user => password
    $users = array("admin" => "mypass" , "guest" => "guest" );

    if (empty($_SERVER [ "PHP_AUTH_DIGEST" ])) (
    header("HTTP/1.1 401 Unauthorized");
    header( "WWW-Authenticate: Digest realm="". $realms.
    "",qop="auth",nonce="" . uniqid(). "",opaque="" . md5 ($realm ). """);

    Die( "The text to be sent when the user clicks the Cancel button");
    }

    // parse the PHP_AUTH_DIGEST variable
    if (!($data = http_digest_parse ($_SERVER [ "PHP_AUTH_DIGEST" ])) ||
    !isset($users [ $data [ "username" ]]))
    die( "Wrong data!");

    // generate the correct response
    $A1 = md5 ($data [ "username" ] . ":" . $realm . ":" . $users [ $data [ "username" ]]);
    $A2 = md5($_SERVER [ "REQUEST_METHOD" ]. ":" . $data [ "uri" ]);
    $valid_response = md5 ($A1 . ":" . $data [ "nonce" ]. ":" . $data [ "nc" ]. ":" . $data [ "cnonce" ]. ":" . $data [ "qop" ]. ":" . $A2 );

    if ($data [ "response" ] != $valid_response )
    die( "Wrong data!");

    // ok, login and password are correct
    echo "You are logged in as: " . $data["username"];

    // http auth header parsing function
    function http_digest_parse($txt )
    {
    // protect against missing data
    $needed_parts = array("nonce" => 1 , "nc" => 1 , "cnonce" => 1 , "qop" => 1 , "username" => 1 , "uri" => 1 , "response" => 1);
    $data = array();
    $keys = implode ("|" , array_keys ($needed_parts ));

    preg_match_all ("@(" . $keys . ")=(?:([\""])([^\2]+?)\2|([^\s,]+))@", $txt , $matches , PREG_SET_ORDER );

    Foreach ($matches as $m ) (
    $data [ $m [ 1 ]] = $m [ 3 ] ? $m [ 3 ] : $m [ 4 ];
    unset($needed_parts [ $m [ 1 ]]);
    }

    Return $needed_parts ? false : $data ;
    }
    ?>

    Comment: Compatibility note

    Be especially careful when specifying HTTP headers. In order to guarantee maximum compatibility with the largest number of different clients, the word "Basic" must be capitalized "B", the region (realm) must be enclosed in double (not single!) quotes, and exactly one space must precede the code 401 in the title HTTP/1.0 401. Authentication parameters must be separated by commas, as shown in the Digest Authentication example above.

    Instead of just displaying the PHP_AUTH_USER and PHP_AUTH_PW variables on the screen, you may need to check if they are correct. To do this, use a database query or search for a user in a dbm file.

    You can observe the features of the Internet Explorer browser. It is very demanding on the parameter of transmitted headers. Header Trick WWW-Authenticate before sending status HTTP/1.0 401 so far it works for him.

    To prevent someone from writing a script that reveals the password to a page that uses external authentication, the PHP_AUTH variables are not set if that page uses external authentication and secure mode is set. Regardless, the REMOTE_USER variable can be used to authenticate an externally authenticated user. So you can always use the $_SERVER["REMOTE_USER"] variable.

    Comment: Configuration note

    PHP uses directive indication AuthType to indicate whether external authentication is used or not.

    It should be noted that all of the above does not prevent passwords for pages requiring authorization from being stolen by anyone who controls pages without authorization located on the same server.

    Both Netscape Navigator and Internet Explorer clear the current window's authentication cache for the given realm when it receives a 401 status from the server. This can be used to force the user to log out and re-display the username and password dialog box. Some developers use this to time-limit logins or to provide a logout button.

    Beispiel #3 HTTP Authentication example forcing a new login/password pair

    function authenticate()(
    header( "WWW-Authenticate: Basic realm="Test Authentication System"");
    header("HTTP/1.0 401 Unauthorized");
    echo "You must enter a valid username and password to access the resource \n";
    exit;
    }

    if (!isset($_SERVER [ "PHP_AUTH_USER" ]) ||
    ($_POST [ "SeenBefore" ] == 1 && $_POST [ "OldAuth" ] == $_SERVER [ "PHP_AUTH_USER" ])) (
    authenticate();
    ) else (
    echo "

    Welcome: ". htmlspecialchars ($_SERVER [ "PHP_AUTH_USER" ]) . "
    " ;
    echo "Previous login: ". htmlspecialchars($_REQUEST["OldAuth"]);
    echo "

    \n";
    echo "\n";
    echo ". htmlspecialchars ($_SERVER [ "PHP_AUTH_USER" ]) . "\" />\n" ;
    echo "\n";
    echo "

    \n" ;
    }
    ?>

    This behavior is not regulated by the standards HTTP Basic-authentication, therefore, you should not depend on it. Browser testing Lynx showed that Lynx does not clear the authorization cache when receiving a 401 status from the server, and by clicking "Back" and then "Forward" in sequence, it is possible to open such a page, provided that the required authorization attributes have not changed. However, the user can press the key "_" to clear the authentication cache.

    In order to get HTTP authentication working correctly in an IIS server with a CGI version of PHP, you must edit the IIS configuration setting called " Directory Security". Click on the inscription " Edit" and set the option " Anonymous Access", all other fields should be left unchecked.

    Comment: Note regarding IIS:
    In order for HTTP authentication to work correctly in IIS, the cgi.rfc2616_headers option in the PHP configuration must be set to 0 (default value).

    Comment:

    In case safe mode is used, the UID of the current script will be added to realms-header part WWW-Authenticate.

    This article is out of date.

    This article was written for the Shared Hosting service, which is deprecated as of June 1, 2019.

    The current hosting service can be ordered on our website

    HTTP authorization using PHP

    This article describes how to create an HTTP authorization using PHP, which will allow you to close any section of the site, for example, the administrative part.

    For authentication, HTTP provides a simple challenge-response mechanism that can be used by the server to challenge a client request and by the client to provide authentication information. The most common authorization scheme is the Basic Authentication Scheme.

    The "basic" authentication scheme is based on the fact that the user agent (browser) must authenticate itself with a user identifier (username) and password for each protected realm (realm). The server will honor the request if it can verify that the user ID and password for the given secure area are correct. No additional identification parameters are provided in this scheme.

    Upon receiving an identity request, the server responds with a challenge similar to the following:

    WWW-Authenticate: Basic realm="Restricted Area" HTTP/1.1 401 Unauthorized

    Where "Restricted Area" is a server-assigned string that identifies the protected area of ​​the requested URI (Request-URI). In simple terms, the name of the protected area.

    Next, to obtain access rights, the user agent (browser) sends the user ID (username) and password, separated by a single colon character (":"), inside the base64-encoded string of recommendations (credentials) to the server:

    Basic-credentials = "Basic" basic-cookies

    Here

    • basic-cookie -- base64 encoded string containing user-pass
    • user-pass -- string like "userid:password"
    • userid -- text not containing ":" characters
    • password -- text

    Note that both the username and password are case sensitive. That is, for example, User and user are two different usernames.

    HTTP Authentication and PHP

    You may have already used the Basic authorization scheme with PHP and you know that the essence of the method is to get the PHP_AUTH_USER and PHP_AUTH_PW variables from the web server, which define the username and password, respectively, and somehow process them inside PHP -script. But note that this method is only effective when PHP functions as an Apache web server module. On our hosting, PHP works in CGI/FastCGI mode and the method described above will not work, since the PHP_AUTH_USER and PHP_AUTH_PW variables will not be passed inside the script.

    However, there is a way to bypass this limitation and pass the username and password values ​​that the user enters into the PHP script. For these purposes, mod_rewrite tools are used - the module of the Apache web server. The rules we will use are as follows:

    RewriteCond %(HTTP:Authorization) ^Basic.* RewriteRule (.*) index.php?authorization=%(HTTP:Authorization)

    When requesting via HTTP to the sitename.ru/www/index.php file, this rule will send the contents of the non-empty Authorization field as a GET request to the authorization parameter. If we use PHP to look at the contents of the $_GET["authorization"] variable, we will see just the basic-credentials described above -- a line of the form:

    preg_match("/^Basic\s+(.*)$/i", $_GET["authorization"], $user_pass); list($user,$pass)=explode(":",base64_decode($user_pass));

    This will give us two variables, $user and $pass, containing the username and password respectively. Now, as mentioned above, they just need to be processed in some way - for example, compared with similar variables from a database or from a file with user accounts.

    Conclusion

    The method discussed in this article will work successfully not only on our hosting, but also wherever PHP works in CGI / FastCGI mode and Apache + mod_rewrite is used as a web server.

    You can find the source texts of working examples in the Appendix to this article.

    Appendix. Script source texts

    The source text of the .htaccess file

    RewriteEngine on RewriteBase / RewriteCond %(HTTP:Authorization) ^Basic.* RewriteRule (.*) index.php?authorization=%(HTTP:Authorization)

    PHP Script Source

    $authenticated=0; if(isset($_GET["authorization"])) ( if(preg_match("/^Basic\s+(.*)$/i", $_GET["authorization"], $user_pass)) ( list($user ,$pass)=explode(":",base64_decode($user_pass)); // Check if the entered credentials are correct if($user=="user" && $pass=="password") ( $authenticated=1; ) ) ) if($authenticated) ( // Authenticated successfully echo("user: ".$user."
    pass: ".$pass); ) else ( header("WWW-Authenticate: Basic realm="Restricted Area""); header("HTTP/1.1 401 Unauthorized"); echo("Access denied."); )

    Webmasters who use something written by themselves as an engine for the site sooner or later get tired of updating the site by editing files via FTP or working directly with the database. And then begins writing administration scripts that would allow you to manage the site interactively with a pleasant appearance and finally make the upgrade process more enjoyable.

    The first question that usually arises in this case is the question of authorization. You will not give the opportunity to everyone who has found an administrative section on the site to do everything that comes into his head. Today we will consider the process of writing a simple authorization.

    First, a few clarifying points. First, we write in PHP, as this is the most common language for writing content management systems today. And secondly, I am personally against self-written scripts responsible for entering the login password itself. Therefore, we will not reinvent the wheel, i.e. own principle of authorization, but we will use the standard features.

    So, we will use basic authentication - a password entry window, which is used, for example, on Rambler and many other sites.

    The ability to log into the secure area remains for the entire session of the browser window, but after you close it, it will be possible to log in again only by entering a username and password. That is, using your computer, it is impossible to commit illegal actions on your behalf. What else is good about this method? It does not accept any variables from third-party servers, and after entering the password incorrectly three times, you will have to refresh the page, which makes it difficult to hack the system by guessing.

    And it looks like this:

    The login entered by the user is stored in the $PHP_AUTH_USER variable, the password is stored in $PHP_AUTH_PW . By the way, pay attention to checking the existence of a user record with this name in the database - this is a critical point that is very important to consider. If there is no such check, this will lead to disastrous results - $row will be equal to zero, that is, by entering a non-existent username and an empty password, you can get into the protected zone.

    Between instructions Header("HTTP/1.0 401 Unauthorized"); and exit() ; we insert anything - from a simple phrase that you can’t go here to a proposal to go somewhere, fly, run away, crawl, and so on. Yes, I almost forgot - the $dbhost, $dbuser, $dbpasswd and $dbname variables store data that provides access to the database and the name of the database.

    Such code must be inserted on each page of the protected zone, for example, through include .

    Here you are protected. On my own behalf, I can also add that passwording in this way personally seems to me very convenient and reliable.

    Liked the article? Share with friends!
    Was this article helpful?
    Yes
    Not
    Thanks for your feedback!
    Something went wrong and your vote was not counted.
    Thank you. Your message has been sent
    Did you find an error in the text?
    Select it, click Ctrl+Enter and we'll fix it!