Hello,
I am familiar with PHP and MySQL and teaching myself how to create a login script, I am not sure if I am simple missing something or something is worong with the code. I am able to signup a user and submit the data to the MySQL table, It connects to the database ok too, but when I try to login and fetch the data from the table when I click on submit it does not validate correctly, I am using Sessions and cookies. All it does is go to login_process.php, it does not redirect me to index.php. What am I doing wrong? I appreciate all the help.
Thank You
Pete
www.pgiammarco.com
HTML Code:
index.php
<? include("header.php"); ?>
<div id="content">
<div id="header">
<span class="email">
<? echo('<p>' . $error_msg . '</p>'); ?>
<? include("login.php"); ?>
</span>
</div>
<? include("footer.php"); ?>
login.php
<form action="login_process.php" method="post" class="login">
Username: <input type="text" name="username" id="username" value="<?echo $_COOKIE["user"];?>" /><br />
Password: <input type="password" name="password" id="password" /><br />
<input type="submit" value="Submit" />
</form>
login_process.php
//Start session
session_start();
//Include database connection details
require_once('config.php');
if(!isset($_SESSION['user']) )
{
if(isset($_POST['submit']))
{
$error_msg = "";
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$dbc = mysql_select_db(DB_DATABASE);
if(!$dbc)
{
die("Unable to select database");
}
$username = $_POST['username'];
$password = $_POST['password'];
if(!empty($username) && !empty($password))
{
$query = "SELECT * FROM tuser WHERE username = '$username' AND password = SHA('$password')";
$result = mysql_query($query);
if($result)
{
if ( mysqli_num_rows($result) == 1 )
{
$row = mysql_fecth_assoc($result);
$_SESSION['user_id'] = $row['userid'];
$_SESSION['user'] = $row['username'];
$_SESSION['fname'] = $row['firstname'];
$_SESSION['lname'] = $row['lastname'];
setcookie('user', $row['username'], "/")
session_write_close();
header("Location: index.php");
exit();
else
{
$error_msg = "Please enter a valid username or password";
header("Location: index.php");
}
}
else
{
die("Query failed");
}
}
else
{
$error_msg = "Please enter a username or password";
header("Location: index.php");
}
}
}
MySQL:
CREATE TABLE IF NOT EXISTS `tuser` (
`userid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`firstname` varchar(50) NOT NULL,
`lastname` varchar(100) NOT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(40) NOT NULL,
`join_date` date NOT NULL,
PRIMARY KEY (`userid`)
)
INSERT INTO `tuser` (`userid`, `username`, `firstname`, `lastname`, `email`, `password`, `join_date`) VALUES
(19, 'pgmarco', 'peter', 'giammarco', 'strike411@aol.com', '8cb2237d0679ca88db6464eac60da96345513964', '2012-06-09');