...

View Full Version : Creating a login that redirects a user to their own page



chemman14
12-02-2010, 08:20 PM
I am trying to make a login system with php that sends a user to a specific page based upon their username. This is the code that I currently have for the login check system

<?php
session_start();

if($_SERVER['REQUEST_METHOD'] == "POST") {
mysql_connect("localhost", "root", "admin");
@mysql_select_db("members") or die( "Unable to connect to database");
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND
password=md5('$password')");

if(mysql_num_rows($result) == 1) {
$_SESSION['is_logged_in'] = 1;
}
}

if(!isset($_SESSION['is_logged_in'])) {
header("Location:login.php");
} else {
header("Location: {$result['homepage']}");
}
?>
when I login on my login page my browser just takes me to a blank page with http://localhost/xampp/site/check.php in the address bar.
Any help is greatly appreciated! Thanks in advance

Lamped
12-02-2010, 08:41 PM
I'm gonna answer your question and give you a ton of minor tips:


<?php
session_start();

if($_SERVER['REQUEST_METHOD'] == "POST") {
mysql_connect("localhost", "root", "admin");
@mysql_select_db("members") or die( "Unable to connect to database");
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND
password=md5('$password')");

if(mysql_num_rows($result) == 1) {
$_SESSION['is_logged_in'] = 1;
}
}

// You needed this line:
$row = mysql_fetch_assoc($result);

if(!isset($_SESSION['is_logged_in'])) {
header("Location:login.php");
} else {
header("Location: {$row['homepage']}"); // And have this be row, not result
}
?>

As for other tips you can ignore:

1. Assuming username is unique, the line:


if ($row = mysql_fetch_assoc($result)) {
$_SESSION['is_logged_in'] = 1;
// redirect and stuff
}


is generally a neater and faster way than checking mysql_num_rows(). Infact, mysql_num_rows() is almost never needed. If mysql_fetch_assoc() fails (out of rows), it returns false, and this is picked up by the if statement.

2. The PHP function md5() doesn't need sanitising because it's strictly hexadecimal (unless you specify binary mode...). Your query could be:


$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='".md5($_POST['password'])."'");

though, I'm delighted to see people actually sanitising everything for once. It's a rare treat.

3. You might wanna do error checking on mysql_connect() aswell as mysql_select_db().

chemman14
12-02-2010, 08:46 PM
wow, awesome man thank you!!! I am new to php coding so I will take all of the suggestions I can. :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum