Help - Search - Members - Calendar
Full Version: [PHP] - [Admin Control Panel w/ sessions] - [Gio]
Pixel2Life Forum > Member Tutorials and Requests > Forum Tutorial Archives > PHP Tutorials
Gio
This tutorial will show you how to create a simple way to protect your admin control pages, using sql to store the users info to which you want to give access to. When the user tries to login to this admin panel the information they enter will be checked by your database and if it is correct it will redirect them to your index page, otherwise it will send them back to the login page! Ok enough talk, lets get the login form done!

Login.html
CODE
<form action="login.php" method="post">
<b>Username</b>:<input type="text" name="username" size="20"><br>
<b>Password</b>:<input type="password" name="pw" size="20"><br>
<input type="submit" value="Login"></form>


Simple enough, this gives inputs for a username, password, and the submit button, it then sends the info to login.php where the magic works!!!

Login.php
CODE
<?php
session_start();

include "connect.php";

$q="SELECT * from login where username='$username' and pw='$pw'";
$result= mysql_query($q, $connection) or die
("Could not execute query : $q." . mysql_error());

if (mysql_num_rows($result) == 0)
{

echo "<div align=center><b>Oops! Your login is wrong. Please click back and try again.</b></div>";

}
else
{
$r=mysql_fetch_array($result);
$login_username=$r["username"];
session_register("login_username");
Header("Location: protected.php");
}
?>


Ok so you use session_start(); which will create the session that you will store on the users computer, then you select all the information from the database and check for the information the user submitted. If it is wrong, an error message is echoed, you can change this to whatever you want it to say. So after that we have the else statement which is if the information is found then it redirects the user to the page you choose, in this case protected.php. This will be your admin page. Now to make a protected page!!

Protected.php
CODE
<?
session_start();
if($login_username=="") {
Header("Location: login.html");
} else {

<!-- rest of your HTML code here for protected pages -->
}


Ok so this code checks if the session is valid, and if not, it redirects the user to login.html. But if the information is true it shows the code you have for the admin page!


Basically I wrote this because alot of people were asking about user protected pages, and securing information from prying eyes. If you branch this off into other ideas you could come up with some real origional ideas. I hope you had fun with this one, because I know I sure did. Enjoy!

~Gio~
Snudge
Looks Good Gio Gj Man

Regards

Snudge ph34r.gif
Gio
Thank you, I had not written a tutorial in awhile, so I decided it was about time to get one posted! Glad you enjoyed it.
Apache
You could replace if (mysql_num_rows($result) == 0) with if(!$result).

Works just as well and saves some time bigwink.gif
FFX
what about connect.php ?

because in login.php it says include connect.php
jasperguy
QUOTE(GR3Z @ Mar 31 2005, 05:55 PM)
what about connect.php ?

because in login.php it says include connect.php

I need to know about this one too.

huh.gif
adam123
Now I don't actually know, but from the given code it will probably be:

CODE
<?php

$user = "mysqluser"; //Change to your mysql username
$pass = "pass"; //Change to your mysql pass
$host = "localhost"; //Almost always localhost, ask your hosting provider
$db = "dbname"; //Change to your db name

$connection = mysql_connect($host,$user,$pass) or die("Could not conn. because:<br />" . mysql_error());

mysql_select_db($db) or die("Cannot select database!" . mysql_error());
?>


That should work as the connect file.
adrian
Thanks for this tutorial, its really useful, i am using it for a basic mysql news script. All my users each have a unique 'id' in the mysql table, when I post some news how would I determine the user id from the above script, and then write it as a variable or whatever.

-Adrian
Epete05
Thanks for the great tutorial, however, isn't it a little unorthodox to store the admin's username in plain-text in the database? A simple crypt() in the validation code or a password() in the sql syntax would make things a bit more secure.

=)
Eric Peterson
Jynxis
You JUST SAVED me a headache. THANK YOU.

I've been creating a portal site for this gaming clan im going to revive once this script is complete, and for some reason it would allow me to login but whenever i clicked the link again to goto my console page, it just has me login again.

Good to know i was only missing Session_register()... sumhow i thought i stuck it in there... guess not
MalDON
I would double check the sessions instead of jsut checking to see if they are empty. And if your are going to be running a site with multiple user ranks, I would also have it check each time to make sure that user is an admin.
Jynxis
it only displays certain links if your of a certain rank... and it checks to see if your banned or not.
binki39
It is a nice script, but the login process can be easily passed if the user knows the location and name of the protected page. For example, in this case the protected page is named protected.php and lets say it's stored in the folder admin under your domain. So the file can be acessed at www.yourdomain.com/admin/protected.php, the code says that if the $login_username is empty then block the access. Basically, you can access the protected page by giving $login_username any value.

For example:
www.yourdomain.com/admin/protected.php?login_username=anythinghere

grants you access. However, I'm assuming too much here. Haha, that is only if the user knows the location and name of the protected page and the name of the variable that the function is checking.
Jynxis
BUT... WUT IF THE LINKS are ONLY active IF the certain measures are met..?
Timo™
what do we put into the sql data base ?
fiv3isaliv3
id, username and password... what else would you put in it?
MaRmAR
Okey, Gio:
1) your MySQL query has bad syntax. Valid syntax of your query would be:
CODE
SELECT * FROM `login` WHERE ((username='$username') AND (pw='$pw'));
or even better by putting LIMIT at the end:
CODE
SELECT * FROM `login` WHERE ((username='$username') AND (pw='$pw')) LIMIT 1;


2) What about security? I know, this is just sample tutorial, but this is an admin sample, so it should be more secure. Try passing $username and $pw thru strip_tags() and mysql_escape_string() before you are calling mysql_query(). Just for case of some "hackers"... This would kill them. bigwink.gif (i had self experienced 'hackers' and this saved me from headache; they did not break the login system)

3) In file protected.php youd should not use
CODE
if ($login_username=="") { ... }
but
CODE
if ($_SESSION["login_username"]=="") { ... }
- the first 'simple' case may not work on some servers which has register_globals turned off. (this problem i experienced about two weeks ago).
Hmm...wouldn't it work better using this
CODE
if (!isset($_SESSION["login_username"])) { ... }
? ... bigwink.gif
Jamie Huskisson
old gio has left us, he couldn't hack it anymore

but very valid points tongue.gif
Hyprkookeez
How would you end the session? Incase you wanted to log off?
HaloprO
This looks like a very easy manipulated php script, It could be vulnerable to many security flaws, if you put up an example I could show you what I mean.
And to answer Hyprkookeez question, just make a logout.php and put this
CODE
<?php
session_start();
session_destroy();
header("Location: file.php");
?>
nygorn
what about mysql code?

I havent use mysql so often and when i do its only copy and paste codes.. bigwink.gif
jjams
Ok say I am newbie at mysql and php (cause I am) now would setup the database for this or does it use one? blink.gif
brent
thank you, thank you, thank you for this tut...it will definately help me out with my php experience....
ashanti
$q="SELECT * from login where username='$username' and pw='$pw'";

this means what ? ohmy.gif what should i insert here ...
Shifty
try,

CODE
CREATE TABLE `login` (
`id` MEDIUMINT( 5 ) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR NOT NULL ,
`pw` VARCHAR( 50 ) NOT NULL ,
PRIMARY KEY ( `id` )
) TYPE = MYISAM;


If iam wrong iam sure someone will post tongue.gif

EDIT: fixed
nygorn
well, i just love this tutorial, but if i want diffrent access levels ?
Like:
1 = News poster
2= Tutorial Writer
3= Moderator
4= Movie maker
Etc.
And on level 10 its admin, that has access to all tongue.gif
I mean, If you got level 4 you get access to 1,2,3 and 4.
If you have 1 you only got access to level 1..
You know what i mean ?
nmy
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /hsphere/local/home/c10300/chill-works.com/scripts/test/protected.php:2) in /hsphere/local/home/c10300/chill-works.com/scripts/test/protected.php on line 4


Whats wrong?
mikem
QUOTE(Shifty @ Oct 22 2005, 11:01 PM) *
try,

CODE
CREATE TABLE `login` (
`id` MEDIUMINT( 5 ) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR NOT NULL ,
`pw` VARCHAR( 50 ) NOT NULL ,
PRIMARY KEY ( `id` )
) TYPE = MYISAM;


If iam wrong iam sure someone will post tongue.gif

EDIT: fixed

Actually Shifty, I hae just been working on it, and it seems to be the right SQL Inserts. So yes folks, this sql works as well.
Below is the SQL file you can just upload using your phpmyadmin.
If you look at the codes correctly people, you can easily tell whats what incase you want to make extra tables.
QUOTE
Kai Sellgren
QUOTE(Apache @ Mar 24 2005, 01:17 AM) *
You could replace if (mysql_num_rows($result) == 0) with if(!$result).

Works just as well and saves some time bigwink.gif

Actually it does not work the same way.
Egemen Sarica
CODE
CREATE TABLE `login` (
  `id` bigint(255) NOT NULL auto_increment,
  `username` longtext NOT NULL,
  `pw` longtext NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM;

INSERT INTO `login` VALUES (2, 'admin', 'admin');


It's true?
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.