Having trouble authenticating users - php

I'm having a lot of trouble with the $_SESSION variable. I'm trying to create a way for users to log in and out. I can log a user in but i don't seem to be able to maintain the session when i switch page. When the user correctly logs in they are taken to profile.php. But if i return to index.php the following error is printed:
Notice: Undefined index: login in /Applications/MAMP/htdocs/www/Shared sites/userlogreg/index.php on line 3
I'm quite new to this but from looking on SO and elsewhere i can't seem to figure it out. Any help would be appreciated.
index.php
<?php
session_start();
if ($_SESSION['login'] == 1) {
echo "<h1>Logged in!</h1>";
} else {
echo "<h1>Not logged in</h1><br/>";
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Index page</title>
</head>
<body>
<h2>Login</h2>
<form action="login.php" method="POST">
<div>
<label for="emailSignIn">Email:</label>
<input type="email" name="email" placeholder="Email" required="required" />
</div>
<div>
<label for="passwordSignIn">Password:</label>
<input type="password" name="password" placeholder="Password" required="required" />
</div>
<input type="submit" name="submit" value="Sign in" />
</form>
<h2>Register</h2>
<form action="register.php" method="POST">
<div>
<label for="firstnameRegister">First name:</label>
<input type="text" name="firstname" placeholder="First name" required="required" />
</div>
<div>
<label for="lastnameRegister">Last name:</label>
<input type="text" name="lastname" placeholder="Last name" required="required" />
</div>
<div>
<label for="emailRegister">Email:</label>
<input type="email" name="email" placeholder="Email" required="required" />
</div>
<div>
<label for="passwordRegister">Password:</label>
<input type="password" name="password" placeholder="Password" required="required">
</div>
<input type="submit" name="submit" value="Create account" />
</form>
</body>
</html>
login.php
<?php
$email = sanitize_input($_POST['email']); //echo "Sanitized email: ".$email; echo "<br/>";
$password = $_POST['password']; //echo "Inputted password: ".$password; echo "<br/>";
if ((!isset($email)) || (!isset($password))) {
// VISITOR NEEDS TO ENTER AN EMAIL AND PASSWORD
//echo "Data not provided";
} else {
// CONNECT TO MYSQL
$mysql = mysqli_connect("localhost", "root", "root");
if(!$mysql) {
//echo "Cannot connect to PHPMyAdmin.";
exit;
} else {
}
}
// SELECT THE APPROPRIATE DATABASE
$selected = mysqli_select_db($mysql, "languageapp");
if(!$selected) {
//echo "Cannot select database.";
exit;
} else {
}
// GET THE USER'S UNIQUE SALT FROM THE DATABASE
$unique_salt = mysqli_query($mysql, "select uniqueSalt from user where email = '".$email."'");
$row = mysqli_fetch_array($unique_salt);
//echo "Salt: ".$row['uniqueSalt']; echo "<br/>";
// HASH THE PASSWORD
$iterations = 10;
$hashed_password = crypt($password,$row['uniqueSalt']);
for ($i = 0; $i < $iterations; ++$i)
{
$hashed_password = crypt($hashed_password . $password,$row['uniqueSalt']);
}
//echo "Password entered by user: ".$hashed_password; echo "<br/>";
$user_db_password = mysqli_query($mysql, "select password from user where email = '".$email."'");
$row = mysqli_fetch_array($user_db_password);
//echo "User's password: ".$row['password']; echo "<br/>";
// query the database to see if there is a record which matches
$query = "select count(*) from user where email = '".$email."' and password = '".$hashed_password."'";
$result = mysqli_query($mysql, $query);
if(!$result) {
//echo "Cannot run query.";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
if ($count > 0) {
session_start();
$_SESSION['login'] = 1;
$_SESSION['email'] = $email;
$_SESSION['errors'] = "";
header("location:profile.php");
//echo "<h1>Login successful!</h1>";
//echo "<p>Welcome.</p>";
//echo "<p>This page is only visible when the correct details are provided.</p>";
} else {
session_start();
$_SESSION['login'] = '';
header("location:index.php");
//echo "<h1>Login unsuccessful!</h1>";
//echo "<p>The email and password combination entered was not recognized</p>";
}
// CLEAN THE INPUT
function sanitize_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

Change this line:
if ($_SESSION['login'] == 1) {
..to this:
if (isset($_SESSION['login']) && $_SESSION['login'] == 1) {
That way, you check if 'login' is set before you access it.

Related

Using SHA1 in PHP for Login form

I'm trying to make a simple register and login form.
I want to use SHA1 to save the encrypted password in database.
But when I try to login with the password, it seems it does not work.
There are three files - index.php, register.php ,login.php
Please help me to solve this problem.
//index.php
<form action="register.php" method="post" enctype="multipart/form-data">
<label for="email">Email:</label>
<input type="text" name="email">
<br />
<label for="password">Password:</label>
<input type="password" name="password">
<button>Register</button>
</form>
<form action="login.php" method="post">
<label for="email">Email:</label>
<input type="text" name="email">
<br />
<label for="password">Password:</label>
<input type="password" name="password">
<button>Login</button>
</form>
//register.php
<?php
$email = $_POST['email'];
$password = $_POST['password'];
$regist_day=date('d-m-Y (H:i)');
if (!empty($email) && !empty($password)) {
require_once('lib/db_connect.php');
$dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME)
or die('Error connecting database');
$sql = "INSERT INTO member(email,password,regist_day)";
$sql .= "VALUES ('$email',SHA1('$password'),'$regist_day')";
mysqli_query($dbc,$sql);
echo("
<script>
location.href='try.php'
</script>
") ;
}
else{
echo "You need to enter Email and Password";
}
?>
//login.php
<?php
$user_email = $_POST['email'];
$user_password = SHA1($_POST['password']);
if (!empty($user_email) && !empty($user_password)) {
require_once('lib/db_connect.php');
$dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME)
or die('Error connecting database');
$sql = "SELECT * FROM member WHERE email = '$user_email'";
$result = mysqli_query($dbc,$sql);
$num_match = mysqli_num_rows($result);
if (!$num_match) {
echo "No result";
}
else{
$sql = "SELECT * FROM member WHERE password = '$user_password' ";
$result = mysqli_query($dbc,$sql);
$password_match = mysqli_num_rows($result);
if (!$password_match) {
echo "SHA1 does not work";
exit;
}
else{
echo"success";
}
}
}
else{
echo "You need to enter both Email and Password";
}
?>

how to check whether old password entered is present or not in db

I m having a login page where user enters id and password.To reset the password i have to check whether the entered password is present or not whether it matches with the id i have entered.How to validate it.I m unable to validate it. If user enters any password it displays the record is updated. How to validate it. Here is the code
login.php
<label type="text" name="id" maxlength="50" size="20">ID</label><br />
<input type="text" name="id" placeholder="ID" class="input" size="20"/><br /></div>
<div class="formItem">
<label type="text" name="uid" maxlength="50" size="20">Password</label><br />
<input type="password" name="uid" placeholder="ID" class="input" size="20"/><br /></div>
<span class="field">(* Required field)</span><br /><br />
<input type="submit" name="login1" value="LOGIN" class="button"><br /><br /><br /><br />
</form>
</div>
</body>
</html>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "abc";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
if(isset($_POST['login1']))
{
$id= $_POST['id'];
$uid= $_POST['uid'];
$query= "select * from resume where id='$id'
AND uid='$uid'";
$run= mysql_query($query);
if(mysql_num_rows($run)>0){
echo "<script>window.open('resetp.php','_self')</script>";
}
else {
echo "<script>alert('Login details are incorrect!')</script>";
}
}
?>
resetp.php
<label type="text" name="uid" maxlength="50" size="20">Old Password</label><br />
<input type="text" name="uid" placeholder="id" class="input" size="20"/><br /></div>
<div class="formItem">
<label type="text" name="uid" maxlength="50" size="20">New Password</label><br />
<input type="password" name="pass" placeholder="pass" class="input" size="20"/><br /></div>
<div class="formItem">
<label type="text" name="cpas" maxlength="50" size="20">Confirm Password</label><br />
<input type="password" name="cpas" placeholder="" class="input" size="20"/><br /></div>
<div class="formItem">
<input type="submit" name="login1" value="RESET" class="formButton"><br /><br /><br /><br /></div>
</form>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$db = "resume1";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db($db,$dbhandle) or die('cannot select db');
if(isset($_POST['login1']))
{
$pass= $_POST['pass'];
$uid= $_POST['uid'];
$cpas=$_POST['cpas'];
$query = "Update `resume` SET uid='".$_POST['pass']."' where uid='".$_POST['uid']."'";
$run = mysql_query($query);
if($query)
{
echo "<script>alert('Record updated')</script>";
}
else
{
echo "<script>alert('no')</script>";
}
}
?>
How can i validated it
Try this:
This line
<label type="text" name="uid" maxlength="50" size="20">New Password</label><br />
should be
<label type="text" name="pass" maxlength="50" size="20">New Password</label><br />
I guess couldn't understand your requirement.
Why don't you validate like you are doing in login.php
$query= "select * from resume where id='$id'
AND uid='$uid'";
$run= mysql_query($query);.................
the PHP script should be at the beginning, not at the end of the code. Begin with the <?php .... ?> and then follow the <HTML> ... </HTML> otherwise the result is returned even before the script is processed.
There are a lot of security issues with your code. You can try this.
<?php
require 'db.php';
$username = isset($_POST['username']) ? htmlspecialchars(trim($_POST['username']), ENT_QUOTES, 'UTF-8') : '';
$password = isset($_POST['password']) ? htmlspecialchars($_POST['password'], ENT_QUOTES, 'UTF-8') : '';
$error = array();
$error_found = 0;
if(isset($_POST['submit']) && ($_POST['submit'] == 'Reset'))
{
//check for errors.
//check if username field is empty.
if(empty($username))
{
$error[] = 'Please provide your user-name.';
}
//check if password field is empty.
if(empty($password))
{
$error[] = 'Please provide a password.';
}
//if errors exist, put errors found as true.
if(!empty($error))
{
$error_found = 1;
}
//else no errors are found.
else
{
//proceed to reset.
//connecting to database.
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die('Unable to connect, check your connection parameters. ');
mysql_select_db(MYSQL_DB, $db) or die('Could not select database, check availability. ' . mysql_error($db));
//querying the database. Checking if user-name password combination exists.
$query = 'SELECT username FROM resume WHERE username = "' . mysql_real_escape_string($username, $db) .
'" AND password = PASSWORD("' . mysql_real_escape_string($password, $db) . '")';
$result = mysql_query($query, $db) or die(mysql_error($db));
//checking if result is true.
if(mysql_num_rows($result) > 0)
{
//the result is true and so you can now reset your password.
}
else
{
$error[] = 'The username password combination you provided does not exist.';
$error_found = 1;
}
}
}
//HTML
?>
<!DOCTYPE HTML>
<html>
<head><title> ... </title></head>
<body>
<!--Your html code here -->
<?php
//if errors are found, then errors are shown here.
if($error_found == 1)
{
echo '<fieldset><center>';
echo '<ul>';
foreach($error as $e)
{
echo '<li>' . $e . '</li>';
}
echo '</ul>';
echo '</center></fieldset>';
}
?>
<form action="nameOfThisScript.php" method="POST">
Username:<input id="username" type="text" name="username" required />
Password:<input id="password" type="password" name="password" required />
<button id="Reset" type="submit" name="submit" value="Reset">Reset</button>
</form>
</body>
</html>
create a script named db.php in the same folder as this script and put the code
<?php
define('MYSQL_HOST', 'localhost');
define('MYSQL_USER', 'root');
define('MYSQL_PASSWORD', '');
define('MYSQL_DB', 'resume1');
?>
Hope this helps.

Create session using username and password.

I need to created login/registration system. User can submit his details and its works fine , but I struggle to create session/log in user with username and password he submitted. When user put any detalis I got info: Notice: A session had already been started and results of that is anyone can get access to restricted sub page. Its seems like php code not retrieve recorded username and passwords. Thanks for any hint.
<form form action=" <?php echo $self; ?>" method="POST">
<div>
<label for="user">Username:</label>
<input type="text" name="username" />
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" />
</div>
<input type="submit" name="submit" value="submit" />
if(isset($_POST['submit'])){
if(!empty($_POST['username']) && !empty($_POST['password'])) {
$user=$_POST['username'];
$pass=$_POST['password'];
$file = fopen('filewriting.txt', 'r');
$clean = array();
while (!feof($file)) {
$clean = fgets($file);
}
fclose($file);
$clean['username'] = $user;
$clean['password'] = $pass;
if($user == $clean['username'] && $pass == $clean['password'] )
{
session_start();
$_SESSION['sess_user'] = $user;
}
} else {
echo 'Invalid username or password!';
}
} else {
echo 'All fields are required!!!';
}

Issue with php mysql login $_POST['username'] = $result['username']

I'm kinda' beginner and I've coded my own PHP login from Zero, but I still got some errors, here's the code:
<?php
include 'connection.php';
$query = " SELECT * FROM admin";
$result = mysql_query($query) or die(mysql_error());
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
if ($username = $result['username']) {
if ($password = $result['password']){
header('Location: admin.php');
} else {
echo "PASSWORD IS INCORRECT";
}
} else {
echo "USERNAME IS INCORRECT";
}
?>
So if you can fix this or got an easier way from PHP login from please tell me. :)
A few things...
Don't use mysql functions
You need to use == to compare strings, not =
You need to actually fetch the results of your query
include 'connection.php';
$query = " SELECT * FROM admin";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result); /* add this */
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
if(isset($_POST['usernameInput']) && isset($_POST['passwordInput'])){
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
}
else{
echo 'some error ...';
}
if($username == $row ['username'] && $password == $row ['password']){
header('Location: admin.php');
}
else{
echo ' username or password is wrong';
}
?>
I have to point out that you are sending the same form over and over without first checking the post. And when you send the form, you will not be able to send the header to redirect, because html is started and headers are sent already.
Mysql functions are deprecated, please use mysqli interface.
Among other several bugs like assignment = instead of is equal ==
Try it this way:
If no post exists send the form else check and if ok redirect or not ok. resend the form
<?php
if($_POST){
include 'connection.php';
$query = " SELECT * FROM admin";
$r = mysql_query($query) or die(mysql_error());
// get an associated array from query result resource.
$result = mysql_fetch_assoc($r);
$username = $_POST['usernameInput'];
$password = $_POST['passwordInput'];
if ( ($username == $result['username'])
&& ($password == $result['password'])){
header('Location: admin.php');
exit(0);
} else {
echo "PASSWORD IS INCORRECT";
}
}
?>
<form action="<?php echo $_SERVER['SELF_PHP']; ?>" method="post">
Username : <input type="text" name="usernameInput" value="" />
Password : <input type="password" name="passwordInput" value="" />
<input type="submit" value="Login" />
</form>
<?php
?>

ERROR 310: too many redirects. Occurring with php coded pages for website I am coding

I am currently coding pages for a social network (it's only going to run locally) for my senior project and I am running in to these redirect errors that I have no clue on how to solve. There are around three pages that have the 'header('location:...') code in it. I didn't know what it would do at the different levels of coding so I put all of the coding with an equal amount of indention.
index.php
<? include("inc/incfiles/header.inc.php"); ?>
<?
$reg = #$_POST['reg'];
//declaring variables to prevent errors
$fn = ""; //First Name
$ln = ""; //Last Name
$un = ""; //Username
$em = ""; //Email
$em2 = ""; //Email 2
$pswd = ""; //Password
$pswd2 = ""; //Password 2
$d = ""; //Sign up Date
$u_check = ""; //Check if username exists
//registration form
$fn = strip_tags(#$_POST['fname']);
$ln = strip_tags(#$_POST['lname']);
$un = strip_tags(#$_POST['username']);
$em = strip_tags(#$_POST['email']);
$em2 = strip_tags(#$_POST['email2']);
$pswd = strip_tags(#$_POST['password']);
$pswd2 = strip_tags(#$_POST['password2']);
$d = date("y-m-d"); // Year - Month - Day
if ($reg) {
if ($em==$em2) {
// Check if user already exists
$u_check = mysql_query("SELECT username FROM users WHERE username='$un'");
// Count the amount of rows where username = $un
$check = mysql_num_rows($u_check);
if ($check == 0) {
//check all of the fields have been filled in
if ($fn&&$ln&&$un&&$em&&$em2&&$pswd&&$pswd2) {
// check that passwords match
if ($pswd==$pswd2) {
// check the maximum length of username/first name/last name does not exceed 25 characters
if (strlen($un)>25||strlen($fn)>25||strlen($ln)>25) {
echo "The maximum limit for username/first name/last name is 25 characters!";
}
else
{
// check the length of the password is between 5 and 30 characters long
if (strlen($pswd)>30||strlen($pswd)<5) {
echo "Your password must be between 5 and 30 characters long!";
}
else
{
//encrypt password and password 2 using md5 before sending to database
$pswd = md5($pswd);
$pswd2 = md5($pswd2);
$query = mysql_query("INSERT INTO users VALUES ('','$un','$fn','$ln','$em','$pswd','d','0')");
die("<h2>Welcome to Rebel Connect</h2>Login to your account to get started.");
}
}
}
else {
echo "Your passwords don't match!";
}
}
else
{
echo "Please fill in all fields";
}
}
else
{
echo "Username already taken.";
}
}
else {
echo "Your e-mails don't match!";
}
}
?>
<?
//Login Script
if (isset($_POST["user_login"]) && isset($_POST["user_password"])) {
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["user_login"]); // filter everything but numbers and letters
$password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password_login"]); // filter everything but numbers and letters
$sql = mysql_query("SELECT id FROM users WHERE username='$user_login' AND password='$password_login' LIMIT 1"); // query the person
//Check for their existance
$userCount = mysql_num_rows($sql); //Count the number of rows returned
if ($userCount == 1) {
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["user_login"] = $user_login;
$_Session["password_login"] = $password_login;
header("location: index.php");
exit();
} else {
echo 'That information is incorrect, try again';
exit();
}
}
?>
<table class="homepageTable">
<tr>
<td width="60%" valign="top">
<h2>Already a member? Login below.</h2>
<form>
<input type="text" size="25" name="user_login" id="user_login" placeholder="username" />
<input type="password" size="25" name="user_password" id="user_password" placeholder="password" /><br />
<input type="submit" name="button" id="button" value="Login to your account!">
</form>
</td>
<td width="40%" valign="top">
<h2>Sign up below...</h2>
<form action="#" method="post">
<input type="text" size="25" name="fname" placeholder="First Name" value="<? echo $fn; ?>">
<input type="text" size="25" name="lname" placeholder="Last Name" value="<? echo $ln; ?>">
<input type="text" size="25" name="username" placeholder="Username" value="<? echo $un; ?>">
<input type="text" size="25" name="email" placeholder="Email" value="<? echo $em; ?>">
<input type="text" size="25" name="email2" placeholder="Re-enter Email" value="<? echo $em2; ?>">
<input type="password" size="25" name="password" placeholder="Password" value="<? echo $pswd; ?>">
<input type="password" size="25" name="password2" placeholder="Re-enter Password" value="<? echo $pswd2; ?>"><br />
<input type="submit" name="reg" value="Sign Up!">
</form>
</td>
</tr>
</table>
</body>
</html>
header.inc.php
<?
include ("inc/scripts/mysql_connect.inc.php");
// starts the session
session_start();
// checks whether the user is logged in or not
$user = $_SESSION["user_login"];
if (!isset($_SESSION["user_login"])) {
header("location: index.php");
exit();
}
else
{
header("location: home.php");
exit();
}
?>
<html>
<head>
<link href="css/main.css" rel="stylesheet" type="text/css">
<title>Rebel Reach - PHS Student Social Network</title>
</head>
<body>
<div class="headerMenu">
<div id="wrapper">
<div class="logo">
<img src="img/find_friends_logo.png">
</div>
<div class="search_box">
<form method="get" action="search.php" id="search">
<input name="q" type="text" size="60" placeholder="Search..." />
</form>
</div>
<div id="menu">
Home
About
Sign Up
Login
</div>
</div>
</div>
<br />
<br />
<br />
<br />
home.php
<?
session_start();
$user = $_SESSION["user_login"];
//If the user is not logged in
if (!isset($_SESSION["user_login"])) {
header('location: index.php');
exit();
}
else
{
//If the user is logged in
echo "Hi, $user, You're logged in<br />Welcome to what is soon to be your NEWSFEED";
}
?>
You've got a catch-22 in your code:
index.php includes your function library
the function library checks for the existence of that session variable.
if the variable doesn't exist, redirect to index.php
e.g. you've written a very complicated version of the classic BASIC 10 GOTO 10.

Categories