The password on page. A part 2.

As avtorizovyvat` the user through kuki (cookies)

Identification of the user through built - in in php 4 mechanism of sessions.

The password on page. A part 4. Pechenjushki


This way is applicable there where, first, it is a lot of users, and their contingent constantly varies. Second, where it is necessary to make a convenient input{entrance} - that it was possible to go in system, having entered a login and the password in the form on page.


We draw the form and we do{make} a file which receives a login and the password (protection against a selection I ude described, add her  here).

// Processing a line with a login

$login = str_repalce ("," ", $login);


$login_result = mysql_query (" SELECT id FROM user WHERE

login = ' $ login ' AND pass = ' ". md5 ($pass.) "'");


if (! mysql_error () ** @mysql_num_rows ($login_result) == 1) {


/* Delivery kuk. Names kuk and are better for defining{determining} a way in order to prevent mess

In a uniform connected file. */

setcookie ($COOKIE_LOGIN_NAME, $login, time () +3600, $COOKIE_PATH);

setcookie ($COOKIE_PASSW_NAME, $pass, time () +3600, $COOKIE_PATH);


/* At once after an input{entrance} of the user perenapravljajut on the address closed by the password. */

header (" Location:/somepath / ");

exit;

}

elseif (! mysql_error ()) {


/* A conclusion of the message on a mistake and forms for repeated input */


print (" the Wrong login or the password. ");

}

else

print (mysql_error ());



All closed pages cause a file in which correctness of the password received from kuki is checked:

$login = str_repalce ("," ", $HTTP_COOKIE_VARS [$COOKIE_LOGIN_NAME]);

$login_result = mysql_query (" SELECT id FROM user WHERE

login = ' $ login ' AND pass = ' ". md5 ($HTTP_COOKIE_VARS [$COOKIE_PASSW_NAME]). "'");


if (! mysql_error () ** @mysql_num_rows ($login_result)! =1) {


/* If such line in the table no, the user perenapravljaetsja on straicu an input{entrance}. */

header (" Location:/login.php ");

exit;

}

else


print (mysql_error ());



Names kuk will be used in several places, therefore it is better to place beforehand them in one place (for example, having declared constants) then to not correct several times.


As you can see, the password will run on the channel and to lay in a file with kukami in the open not coded kind. It is very unsafe. In absence of the owner it is possible to approach to a computer, to have a look in a file where the browser holds kuki, and to write down the password on a piece of paper (and if in a local area network all general{common} both to approach{suit} is not necessary and to pull down the password it is possible directly at the owner).


That it has not taken place, the password needs to be coded. As a comprehensible variant, khehsh md5. Here already it is impossible to see the password and to go in system, having written down it  on a piece of paper or copy-paste-nuv. By the way, so it is possible zalazit` under the password and without the knowledge of the friend in the web-interfaces building authorization at sessions. Therefore the last, that it is possible to make in this direction is to change kuku at each loading page.


Itself once did{made} such circuit: in the table of users there is a column with date of last reference{manipulation}. This date last reference{manipulation} and the password, coded through md5, the user receives at each reference{manipulation}. The system takes kuku with a login, pulls out this line from base, generates khehsh from fields last_log and passwd and compares it  with received. If they coincide, means the visitor it is possible to let. For a dense forest of safety it is possible to add check on the expiration kuki - kuka should expire the ambassador poluchasa neaktivnosti, and, sootvetsvenno, in base date of last broad gully should be less than half an hour back.

$login = str_repalce ("," ", $HTTP_COOKIE_VARS [$COOKIE_LOGIN_NAME]);

$login_result = mysql_query (" SELECT * FROM user WHERE

login = ' $ login ' AND last_log> DATE_SUB (NOW (), INTERVAL 30 MINUTE) ");


if (! mysql_error () ** @mysql_num_rows ($login_result) == 1) {

/* We receive a line of the table and it is formed khehsh from the necessary fields. */

$current_user = mysql_fetch_array ($login_result);


$hash_to_check = md5 ($current_user ["passwd"] ". Y - that nobody has guessed ".

                   $current_user [log_time]);


if ($hash_to_check == $HTTP_COOKIE_VARS [$COOKIE_HASH_NAME]) {

    $current_time = time ();

/* Updating a field of last input{entrance} and delivery new kuki. */

    mysql_query (" UPDATE user SET last_log = ' ". date (" Y-m-d H:i:s ", $current_time). " '

      WHERE login = ' $ login ' ");

    setcookie ($COOKIE_HASH_NAME, md5 (date (" Y-m-d H:i:s ", $current_time).

        " Y - that nobody has guessed ".

        $current_user ["passwd"]), $current_time + 1800, $COOKIE_PATH);

}

else {


/* In case of discrepancy khehsha the user perenapravljaetsja on straicu an input{entrance} in system. */

    header (" Location:/login.php ");


    exit;

};

}

elseif (! mysql_error () ** @mysql_num_rows ($log_result)! =1) {

header (" Location:/login.php ");

exit;

}

else

print (mysql_error ());



Certainly, " Y - that nobody has guessed " better too to allocate into a separate variable, and it is better to use instead of this line an ip-address of the visitor (or, for breaking dialapa, first two / three numbers of an ip-address).


By the way, about the IP-address. It{he} is better for checking, but not all address, but only first two (for ip, beginning on number it it is less 127) or three (accordingly, it it is more 127) numbers of the address. It will rescue users bad and breaking dialapa from necessity anew avtorizovyvats`ja after breakage of communication{connection}, and at the same time, will not give to go to the hacker who has stolen kuku. Certainly, he cannot call back and go through other provider - the address of a pool not that, but it not our problems (" in such weather the houses sit "). As not our problem and larceny of passwords inside firm. We have protected from curious comrades and illiterate hackers, and against trojanov and snifferov which can be put to a victim, anything we can not make.


On it "navoroty" have ended. It is more reliable to not make protection any more. Nobody will climb in a file kuk for khehshem and to select it . It will be easier to place between the user and the web - interface sniffer and by means of him  to find the password. It is possible to place trojana which will remember everything, that the user has entered on the keyboard, but it any more our problems. To be protected from listening the channel, it is necessary to use connections such as SSL or encryption of the data.

The password on page. A part 5. Sessions


What for I wrote a note about kuki? " I do not understand, what for to write about kuki when in php there are sessions?! " In order that at readers the flat picture was not formed before eyes. Not everywhere still costs{stands} php to 4-th version, and in third they are not supported. Moreover, not everywhere sessions so are necessary - with rare exception the algorithm of authorization checks correctness of the login / password and correctness of the data of session, and then or otfutbolivaet the client on page of an input{entrance}, or takes a file (or object) with the data on the user.


Cases when job by sessions is necessary, not too often. For example, in the game "Monopolist" I at once began to use sessions because the user can play several games and the same page can contain the different data in the same session. There it is better the data for one of games in which the user participates, to store{keep} in session and to make page for transition between games.


In general, I do not assert, that sessions to use it is not necessary. It is necessary, only to all the place. To a question of applicability of three ways of authorization - through 401-st heading ("realm"), kuki or sessions - I vernus` later. Now I shall talk about sessions.


Sessions in php is actually not a method of authorization (concept wrong, but in forums ask " as avtorizovyvat` the user through sessions? "). Built - in in php the mechanism of the user sessions only identifies these users, avtorizovyvat` - besides, job of your script.


It is a lot of about the mechanism of sessions I shall not tell - it is already told. In the most simple kind (is more correct in itself dafault-nom) this mechanism works so: the system holds a file of session which contains its{her} variables on the server. The user at start of session receives the unique identifier (usually through kuku), and at the reference{manipulation} to other pages sends her . At start of the mechanism of sessions in your script obrabotchik php checks, whether there is a file corresponding to the come identifier of session - if exists, the script can read the data from a file if no - new session will be started and the file is created. Certainly, a name of the given variable operedeleno in installations php.


Now about we use what functions.


session_start (). Starts the mechanism of sessions. From the user there should be a variable and a file corresponding to her. If there is no file, he is created, and session is started from zero. If there is no neither a file, nor a variable the variable (for example is generated, the heading with kukoj) is sent and the file is created.


session_register (imja1, imja2, imja3...). The instruction{indication}, what variables to remember in a file upon termination of job of a script. After the user will pass to other page, it is possible to start the mechanism of sessions, and after a call of the given function variables will be accessible.


session_destroy (). Deletes a file of the data of session (at use kuk it is necessary to delete them manually, having exposed empty kuku: " setcookie (session_name ()) ").


session_end (). If after authorization the data on the user to change it is not necessary, better at once " to switch off behind itself light " - to close a file and to release{exempt} access to it .


session_set_cookie_params (a life, a way, the domain). Installation of parameters kuki with the identifier of session (by default kuka it is exposed on a root of the server and for 0 seconds - before closing a browser).


While all. In detail about sessions there will be separate releases. While I shall describe the mechanism of authorization and identification of the user by means of sessions.


So, we have three files - an input{entrance} (login), check (auth) and an output{exit} (logout).

// A cutting of all undesirable symbols

$login = preg_replace (" / [^ \w_\.\-] / ", " ", $HTTP_POST_VARS ["login"]);

$pass = trim ($HTTP_POST_VARS ["pass"]);


// Check of variables

if (strlen ($login) == 0 || strlen ($pass) == 0)

$error = " Enter a login and the password ";

else {


// Check of a login and the password

$user_result = mysql_query (" SELECT * FROM user WHERE

    login = ' $ login ' AND pass = ' ". md5 ($pass.) "'");

/* If there was a mistake in base (for example, the user has put in session dli-¿-innuju

Variable which base to digest has not wanted) or one line has turned out not,

otfutbolivaem the user */

if (mysql_error ())


    die (mysql_error ());


elseif (@mysql_num_rows ($user_result)! = 1)

    $error = " the Incorrect login name or the password. ";


// If all is normal, we choose the data, we start session

else {

    $user = mysql_fetch_assoc ($user_result);


    session_set_cookie_params (1800, "/");

    session_start ();


    // We remember the data on the user

    session_register ("user");


    // And further we send it  somewhere

    if (isset ($HTTP_POST_VARS ["return"]))

      header (" Location: {$HTTP_POST_VARS ['return']} ");

    else


      header (" Location: / ");

    exit ();

};

};


/* Here the user any more has not passed authorization, but can send kuku from

The closed session. We shall clear her . */

if (isset ($HTTP_COOKIE_VARS [session_name ()]))

setcookie (session_name ());


// We draw the form further, it is not interesting.



The given script is and obrabotchikom and the form for data input. At reception of a login and the password he processes them and if they correct, stops job, having sent the user on the necessary page. If the data wrong or in general are absent, draws the form.

/* We kill a variable user that it was impossible, having drawn the form to send the data

In post-search. */


unset ($user);


// The flag " a mistake of session " - if he is switched on, job will be stopped.

$session_error = false;


// If not exists kuki with the identifier of session, to hoist the colours

if (! isset ($HTTP_COOKIE_VARS [session_name ()]))

$session_error = true;


// If exists, we start the mechanism of sessions and it is registered a variable $user.

else {

session_start ();

session_register ("user");


/* If it is casual in a file there is no login and the password, job too stops (" anything

We do not know, we to you of them allowed ") */


if (! isset ($user ["login"]) ||! isset ($user ["pass"]))

    $session_error = true;

};


/* If the user till now managed gerojski to avoid mistakes, check is done{made}

Through base the same as and on an input{entrance}. */

if (! $session_error) {

$check_result = mysql_query (" SELECT uid FROM user WHERE

    login = ' {$ user [login]} ' AND pass = ' {$ user [pass]} ' ");


if (mysql_error () || @mysql_num_rows ($user_result)! = 1)

    $session_error = true;

};


// If there was any mistake,

if ($session_error) {


// We destroy the given sessions


session_destroy ();


// We destroy kuku if she was

if (! isset ($HTTP_COOKIE_VARS [session_name ()]))

    setcookie (session_name (), "", / ");


/* We send the user on an input{entrance}, with an opportunity to return on requested */address

header (" Location:/login.php? return = $ REQUEST_URI ");


// We stop job

exit ();

};


mysql_free_result ($check_result);



The user is checked up and in a file $user - all data on him, it is possible to greet, for example, it  by name to a patronymic:

<?

include ("auth.inc");

?> <html>

<head> <title> <? print (" Hello, {$user [fname]} {$user [sname]}! ");?> </title> </head>

<body>

</html>



And an output{exit}:

if (isset ($HTTP_COOKIE_VARS [session_name ()])) {


// Start of the mechanism of sessions

session_start ();


// Removal{Distance} of a file

session_destroy ();


// Removal{Distance} kuki

setcookie (session_name ());

};


// An output{exit} from page

header (" Location:/login.php ");



Pair remarks: a part closed by the password in the given example - all server (for example, service.firm.ru), for closing a directory it is necessary to correct ways. Instead of PHPSESSID it is used session_name () that it was possible to change a name of the identifier freely. By the way, on one physical server it is possible to do{make} different names of identifiers of sessions - enough in the necessary part to put a file .htaccess with a line php_value session.name "ABRACADABRA".