|
|
|
Hello all! After viewing most of the examples of login scripts out there, I noticed that many lacked security after the initial login. A user could easily change the cookie to set admin to 1 or whatnot, which is a big security hazard. I decided to take a slightly different approach and fix this problem. In this example, a file called "check-user.php" is required at the top of every page. This file takes the cookies (user and pass) and validates them each time the user opens a page and decides whether or not the user is valid (and if they are, whether or not they have admin access). While it's not 100% safe, it is far more secure than traditional methods (and then again, are ANY php scripts 100% safe? If hackers can work their way into the ultra secure credit card company servers, you be the judge). Anyhow, this is a basic example of usage. Obviously, it would take some modifications work work on your site (you would need to change the MySql variables, possibly the MySql table name, and of course, the information contained in the cookies). As for some practical uses, pretty much any site that uses a login would be a prime canidate for this script. Anyways, enough time on the podium, now to the script itself (which is in multiple files). All files can be found in the attatched zip file. Hope this helps make your site more secure!
index.php
| <?php
require 'check-user.php'; // Require check-user.php (ALWAYS Use require For Important Files Such As This
if ($admin == '1') { // If User Is An Admin
print 'Logged in as a admin.';
print '<br /><br />';
print '<a href="logout.php">Logout</a>';
} else if ($auth == '1') { // If User Is Just A Regular User (Non-Admin)
print 'Logged in as a user.';
print '<br /><br />';
print '<a href="logout.php">Logout</a>';
} else { // If No Cookies Are Set, Cookies Are Expired, Or Cookies Contain Invalid Username And/Or Password
print 'NOT logged in.';
print '<br /><br />';
print '<a href="login.php">Login</a>';
}
?> | |
check-user.php
| <?php
$sqluser = ""; // MySql Username
$sqlpass = ""; // MySql Password
$sqlhost = "localhost"; // MySql Host Address - Default Is localhost
$sqldb = ""; // MySql Database Name
mysql_connect($sqlhost, $sqluser, $sqlpass); // Connecting To MySql
mysql_select_db($sqldb); // Selecting MySql Database
if (isset($_COOKIE['user']) && isset($_COOKIE['pass'])) { // Checking To See If Cookies Exist And If They're Good
$user = $_COOKIE['user']; // Setting The $user Variable
$pass = $_COOKIE['pass']; // Setting The $pass Variable
$logincheck2 = mysql_query("SELECT * FROM users WHERE user='$user' AND pass='$pass'"); // Run A Query To See If The Username And Password Are Valid
$logincheck = mysql_num_rows($logincheck2); // Number Of Results Of The Query
if ($logincheck > '0') { // If One Or More Users Were Found
$auth = '1'; // Valid User, Set $auth To 1
setcookie("user", $user, time()+60*60*24*30, "/", ".yoursite.com", 0); // Updating The Cookie
setcookie("pass", $pass, time()+60*60*24*30, "/", ".yoursite.com", 0); // Updating The Cookie
$admincheck2 = mysql_query("SELECT * FROM users WHERE user='$user' AND pass='$pass' AND admin='1'"); // Run A Query To See If The User Is An Admin
$admincheck = mysql_num_rows($admincheck2); // Number Of Results Of The Query
if ($admincheck > '0') { // If One Or More Users Were Found
$admin = '1'; // User Is An Admin, Set $admin To 1
} else {
$admin = '0'; // User Not An Admin, Set $admin To 0
}
} else {
$admin = '0'; // Invalid User, Set $admin To 0
$auth = '0'; // Invalid User, Set $auth To 0
}
} else {
$admin = '0'; // Invalid User, Set $admin To 0
$auth = '0'; // Invalid User, Set $auth To 0
}
mysql_close(); // Closing The Connection
?> | |
login.php
| <?php
if (!isset($_GET['subpage'])) { // If No Subpage Is Specified
if (isset($_GET['error']) && $_GET['error'] == '1') { // If An Error Is Set And Is Set To 1
?>
<font color="#FF0000"><b>ERROR: </b>Invalid username and/or password. Please try again.</font>
<? } ?>
<form method="post" action="login.php">
Username:<br />
<input type="text" name="username">
<br /><br />
Password:<br />
<input type="password" name="password">
<br /><br />
<input type="submit" name="login" value="Login">
</form>
<?
} else if (isset($_GET['subpage']) && $_GET['subpage'] == 'login') { // If A Subpage Is Specified And Set To login
$sqluser = ""; // MySql Username
$sqlpass = ""; // MySql Password
$sqlhost = "localhost"; // MySql Host Address - Default Is localhost
$sqldb = ""; // MySql Database Name
mysql_connect($sqlhost, $sqluser, $sqlpass); // Connecting To MySql
mysql_select_db($sqldb); // Selecting MySql Database
$user = $_POST['username']; // Setting The Variable (Always User Different Variable Names Than What Is In Your HTML Forms)
$pass = md5($_POST['password']); // Setting The Variable (Always User Different Variable Names Than What Is In Your HTML Forms - Password Should Also Always Be MD5 Encrypted)
$usercheck2 = mysql_query("SELECT * FROM users WHERE user='$user' AND pass='$pass'"); // Check If Any Users Match Username & Password Entered
$usercheck = mysql_num_rows($usercheck2); // Number Of Results Of The Query
if ($usercheck > '0') { // If One Or More Users Were Found
setcookie("user", $user, time()+60*60*24*30, "/", ".yoursite.com", 0); // Setting The Cookie
setcookie("pass", $pass, time()+60*60*24*30, "/", ".yoursite.com", 0); // Setting The Cookie
header("Location: index.php"); // Redirect To index.php
} else {
header("Location: login.php?error=1"); // Redirect Back To The Login Form With An Error
}
mysql_close(); // Closing The Connection
}
?> | |
logout.php
| <?php
setcookie("user", $user, time()-60*60*24*30, "/", ".yoursite.com", 0); // Unsetting The Cookie (By Setting The Time To Negative 30 Days)
setcookie("pass", $pass, time()-60*60*24*30, "/", ".yoursite.com", 0); // Unsetting The Cookie (By Setting The Time To Negative 30 Days)
header("Location: index.php"); // Redirect To index.php
?> | | |
|
| PHP4 MYSQL Authentication Script with cookie. Short & Sweet
Categories : Authentication, Apache, Cookies, PHP, MySQL | | | A very simple PHP single password cookie based login without usernames. Categories : PHP, Cookies, Security, Beginner Guides | | | Example voting script. Lets people enter suggestions and vote for existing ones. Categories : MySQL, PHP, Cookies, Complete Programs, Databases | | | A damaged image generator (class) for validating text.
CAPTCHA - Completely Automated Public Turing test to tell Computers and Humans Apart Categories : PHP, PHP Classes, Security, GD image library, Security | | | The Best Authorize Categories : PHP, MySQL, Cookies | | | A Simple Script that stores encrypted messages in databases Categories : PHP, Databases, MySQL, Security | | | bookmarker - PHP, PHPLIB, MySQL WWW based bookmark manager Categories : MySQL, PHP, MySQL, Complete Programs, Databases | | | Password protection for Phorum 3.1.x with userlevels and log. Categories : PHP, MySQL, Authentication, Security | | | This functions makes it easy to use session-variables known from ASP. With one Cookie the array "session" will save and restore from a db-record. In this version MySQL is used but it's should very easy to change Categories : PHP, Arrays, Cookies, MySQL, Databases | | | A login page that require username, password and userlevel. Categories : PHP, Security, Sessions, MySQL, Databases | | | Complete, simple working example of login screen and check on a unique page using php functions, cookies and mysql database. Categories : PHP, Cookies, MySQL, HTML and PHP, Authentication | | | Retrieve text from table and email to your e-
address in pipe delimited format. Categories : PHP, MySQL | | | Accepts a database & hostname from a user and then HTTP username and password. Uses this to connect to a MySQL database. Produces a form based on the tables it finds there to allow the user to do SELECTs, INSERTs, and DELETEs. Categories : Databases, PHP, MySQL, Complete Programs | | | A PHP function to encrypt and decrypt a number or string or a combination of the two. Categories : PHP, Encryption, Security | | | a function that builds an HTML select list from any mysql table. Categories : PHP, MySQL, HTML and PHP | |
| | | | matthew waygood wrote : 1163
BUT all a user has to do is copy/view someones cookie to find out their username and password. This seems to defeat the reason why you wrote this.
Surely holding the values in a session, which the cookie only stores the current session reference, is more secure than this. The cookie and session would expire when the user logs out or closes the browser.
| | | | bastien koert wrote : 1168
If you really want to use cookies, it could / should be set only for the username. With that cookie set, that password is irrelevant as the user is authorized. And more secure since the password cookie is never set.
Personally, like Matt suggested, session objects are really the way to handle this. Only the session cookie every gets set, which is a random generated string. Change that and you loose your session.
| | | | Joseph Crawford wrote : 1169
I too very much agree, why would you want to store all that information in a cookie tsk tsk tsk.
all you really need to do is verify the username and password and set a session variable for the auth part, you cant change session variables like you can a cookie.
another thing i wanted to mention was that this is not a very secure login script so to all the newbies, i wouldnt suggest you rely on this code.
Not only that but it seems to run a database query with every page load, if you have 10,000 people accessing your page at one time that is just way too many queries, i would suggest you query once on login and store the session in a cookie.
| | | | Nick Wilson wrote : 1170
Oops, sorry, need to think before I submit. I`ll send a modified version to the webmaster later on that fixes that.
| | | | Isaac Ross wrote :1693
very very very nice script, although one mistake, in logout.php on line 2, you need to place this before all the code REQUIRE "check-users.php"; then the entire script works just fine.
| |
|
|
|