This is in continuation of the tutorial on making a membership based web site. Please see the previous page for more details.
Download the code
You can download the whole source code for the registration/login system from the link below:
The ReadMe.txt file in the download contains detailed instructions.
The login form
Here is the HTML code for the login form.
Logging in
We verify the username and the password we received and then look up those in the database. Here is the code:
function Login() { if(empty($_POST["username"])) { $this->HandleError("UserName is empty!"); return false; } if(empty($_POST["password"])) { $this->HandleError("Password is empty!"); return false; } $username = trim($_POST["username"]); $password = trim($_POST["password"]); if(!$this->CheckLoginInDB($username,$password)) { return false; } session_start(); $_SESSION[$this->GetLoginSessionVar()] = $username; return true; }
In order to identify a user as authorized, we are going to check the database for his combination of username/password, and if a correct combination was entered, we set a session variable.
Here is the code to look up the username and password.
function CheckLoginInDB($username,$password) { if(!$this->DBLogin()) { $this->HandleError("Database login failed!"); return false; } $username = $this->SanitizeForSQL($username); $pwdmd5 = md5($password); $qry = "Select name, email from $this->tablename ". " where username="$username" and password="$pwdmd5" ". " and confirmcode="y""; $result = mysql_query($qry,$this->connection); if(!$result || mysql_num_rows($result) <= 0) { $this->HandleError("Error logging in. ". "The username or password does not match"); return false; } return true; }
Please notice that we must compare the value for the password from the database with the MD5 encrypted value of the password entered by the user. If the query returns a result, we set an “authorized” session variable, and then redirect to the protected content. If there are no rows with the entered data, we just redirect the user to the login form again.
Access controlled pages
For those pages that can only be accessed by registered members, we need to put a check on the top of the page.
Notice that we are setting an “authorized” session variable in the login code above. On top of pages we want to protect, we check for that session variable. If user is authorized, we show him the protected content, otherwise we direct him to the login form.
Include this sample piece of code on top of your protected pages:
CheckLogin()) { $fgmembersite->RedirectToURL("login.php"); exit; } ?>
See the file: access-controlled.php in the downloaded code for an example.
Here is the CheckLogin() function code.
function CheckLogin() { session_start(); $sessionvar = $this->GetLoginSessionVar(); if(empty($_SESSION[$sessionvar])) { return false; } return true; }
These are the basics of creating a membership site. Now that you have the basic knowledge, you can experiment with it and add new features, such as a “Forgot password” page to allow the user to retrieve or change his password if he forgets it.
Updates
9th Jan 2012
Reset Password/Change Password features are added.
The code is now shared at GitHub .
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.
HTML теги, определяющие HTML формы на сайте
Создаем сайты и отдельные страницы в сети интернет для общения с посетителями.
HTML формы используются для регистрации посетителей на сайте, для интерактивных опросов и голосований, позволяют отправлять сообщения, совершать покупки и так далее. HTML Форма создается с одной целью: сбор и последующая передача информации на обработку программному сценарию или по электронной почте.
Пример HTML формы | Вход на сайт
Теги, атрибуты и значения
- - определяют форму.
- name="" - определяет имя формы.
- method="" - определяет способ отправки данных из формы. Значения: "get" (по умолчанию) и "post" . Чаше используется метод "post" , так как позволяет передавать большие объемы данных.
- action="" - определяет url по которому данные отправляются на обработку. В нашем случае - enter_data.php ..
- - определяют такие элементы формы как кнопки, переключатели, текстовые поля для ввода данных.
- type="text" - определяет текстовое поле для ввода данных.
- type="password" - определяет поле для ввода пароля, при этом текст отображается в виде звездочек или кружочков.
- type="checkbox" - определяет переключатель.
- type="hidden" - определяет скрытый элемент формы - используется для передачи дополнительной информации на сервер.
- size="25" - длина текстового поля в символах.
- maxlength="30" - максимально допустимое количество вводимых символов.
- value="" - определяет значение, которое будет отправлено на обработку если относится к радиобутонам или переключателям. Значение данного атрибута в составе текстового поля или кнопки будет показано как, например, Вася или Вход в примере выше.
Пример HTML формы | Комментарии на сайте
|