Email verification- Blank page when logging in after verified - php

I have recently used a tutorial from http://tutsforweb.blogspot.co.uk/2012/05/registration-system-with-email.html. I have added a new field in my user table called 'com_code' as stated and defined the default as NULL.
Both confirm.php and registeraction.php work as the passkey variable is inserted into the com_code field in the database when a user registers, and when they click on the verify link in the email they have been sent, the com_code field is then set to NULL.
My problem is when this user logs in, a blank page appears ( with the url stuck at loginaction.php where I process the form). Any ideas where I have gone wrong in my loginaction.php code? I am new to PHP so as much explanation as possible would be great!!
loginaction.php
<?php require 'config/init.php';
// Get the data collected from the user and database
$email = trim($_POST["email"]);
$password = trim($_POST["password"]);
//Check for errors
if (empty($email) or empty($password)) {
$_SESSION["message"] = "Must enter Email and Password ";
header("Location: login.php"); //Redirection information
exit ;//Ends the script
}
$email = strip_tags($email);
$password = strip_tags($password);
$pwd = $_POST["password"];
$sql = "SELECT * FROM user WHERE email='$email' AND com_code is NULL";
$result = mysqli_query($mysqli,$sql)or die(mysqli_error());
if ($result->num_rows === 1) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (password_verify($pwd, $row['password'])) {
$_SESSION["authenticatedUserEmail"] = $email;
$_SESSION["unauthenticatedAdmin"] = $_SESSION['usertype'] == '0';
//We could also use information drawn from the database eg ID
$_SESSION['id'] = $row['id'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['last_name'] = $row['last_name'];
$_SESSION['password'] = $row['password'];
$_SESSION['username'] = $row['username'];
$_SESSION['usertype'] = $row['usertype'];
$_SESSION['email'] = $row['email'];
if ($_SESSION['usertype'] == '1') {
header("Location: admin.php");
} else {
header("Location: profile.php");
}
}
else {
//Login was unsuccessful
$_SESSION["message"] = "Could not login as $email";
header("Location: login.php"); //Go back to the login pages
}
}//End else
?>

Related

Redirecting user to dashboard with their user role from same login page

I have directed user according to the user's role in the dashboard from the same login page.
But with this the user can go to user dashboard just by simple providing the admins url.
How can I prevent a user from getting in the admin dashboard after login?
The login code is as follow.
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
//if the user try to enter without typing anything.
if($username !="" && $password !==""){
/*$password = sha1($password);*/
$sql = "SELECT * FROM users WHERE username ='$username'AND password='$password'";
$result=mysqli_query($conn, $sql) or die('Error');
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$user_id = $row['user_id'];
$fullname = $row['fullname'];
$username = $row['username'];
$phone_number = $row['phone_number'];
$state = $row['state'];
$city = $row['city'];
$street = $row['street'];
$email = $row['email'];
$user_role = $row['user_role'];
//Starting the session for the user
$_SESSION['user_id'] = $user_id;
$_SESSION['fullname'] = $fullname;
$_SESSION['username'] = $username;
$_SESSION['phone_number'] = $phone_number;
$_SESSION['state'] = $state;
$_SESSION['city'] = $city;
$_SESSION['street'] = $street;
$_SESSION['email'] = $email;
$_SESSION['user_role'] = $user_role;
if($user_role == admin){
header('Location:admin/admindashboard.php');
}else{
header('Location:user/userdashboard.php');
}
}
}else{
$error="Username or Password is incorrect!!";
}
}else{
$error = "Please Enter Username and Password";
}
}
You need to make sure that certain conditions match for each user so that they do not navigate by typing into URL.
From your coding assuming that you have already redirected the users to the relevant page. Make sure you have validation checks in following files.
Add this to the header of admindashboard.php
if( $_SESSION['user_role'] != "admin")
{
session_destroy();
header("location: login.php");
}
Add this to the header of userdashboard.php
if( $_SESSION['user_role'] != "user")
{
session_destroy();
header("location: login.php");
}
With the above codes, you will block other different types of users accessing different parts of the website.
How can I prevent a user from getting in the admin dashboard after login?
By performing the same check on that page (on admindashboard.php). Whatever $user_role and admin are, you would examine the same logic on any page which requires that permission. If the check fails, redirect (possibly to the login page, prompting the user to login with an account which can access that page).
For example:
if($_SESSION['user_role'] != admin) {
header('Location:login.php');
}
You can't prevent a user from requesting any page. You can respond to that request accordingly.

Session data not being passed through to the next page

I have a login system that has two pages, it's quite simple but it doesn't appear that the data is being passed through as I am being redirected back. I have tried a couple solutions. Adding exit; and die; after the inital redirect from the login. I have also printed the session_id which worked fine.
Login page:
session_start();
if(isset($_POST['login'])){
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$username = stripslashes($username);
$password = stripslashes($password);
$password = md5($password);
$sql = "SELECT * FROM table WHERE username = :username LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":username", $username);
$stmt->execute();
foreach($stmt as $row) {
$id = $row['id'];
$db_password = $row['password'];
}
if($password == $db_password){
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
header("Location: admin.php");
exit;
}else{
echo "You did not enter the correct details.";
}
}
This is the admin page. It just redirects back to login and doesn't get any further down the page
session_start();
if(!isset($_SESSION['id'])){
header("Location: login.php");
}
execute()
Returns TRUE on success or FALSE on failure.
You need to fetch data form result set as
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);// fetch data
$id = $row['id'];
$db_password = $row['password'];
if($password == $db_password){// then compair
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
header("Location: admin.php");
exit;
}else{
echo "You did not enter the correct details.";
}

How to redirect to different page after form is submitted using header()?

I've looked at lots of answers to redirect to a different page after submitting a form, but haven't been able to get it to work thus far, probably because I have no idea where to actually put the code. Can anyone help? The rest of this code is working fine, i just need to know where to place header():
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//connects to database, checks username & password against database to see is user exists
if($username && $password)
{
include ("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows !==0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
//if username and password are correct
if($username==$dbusername&&md5($password)==$dbpassword)
{
echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
}
//if password is incorrect
else
echo "Your password is incorrect.";
}
//if username is incorrect
else
die("Username does not exist.");
}
//if no information is submitted
else
die("Please enter your login details.");
//prevents errors from displaying on page
error_reporting(0);
?>
I also need to know where it goes for this page:
<?php
//Check if register button was pressed
$button = $_POST['button'];
//if button was pressed,
if ($button)
{
//get data from form,
$username = $_POST['username'];
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
}
//check if all information has been entered,
if ($username && $password && $retype_password && $first_name && $last_name)
{
//check if password and retype_password are the same
if($password==$retype_password)
{
//check if username already exists
include("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username = '$username'");
$numrows = mysql_num_rows($query);
if($numrows == 0)
{
//encrypt password
$password = md5($password);
//sends data from form to database - creates new user
$register = mysql_query("INSERT INTO users VALUES ('', '$username', '$password', '$first_name', '$last_name')");
echo "You are now registered. <a href='main.php'>Continue to site.</a>";
}
else
echo "Username is unavailable.";
}
else
echo "Password did not match.";
}
//prevents errors from displaying on page
error_reporting(0);
?>
Thanks in advance!
if($username==$dbusername&&md5($password)==$dbpassword)
{
$_SESSION['username'] = $username;
header( 'Location: http://www.yoursite.com/new_page.html' ) ;
}
You should put it once the job is done : that is after
//echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
header('Location: your url');
exit;
Don't forget the "exit" or what follow will be executed.
That said, you cannot echo something before a doing redirection, that's logical because the echo can't be seen.
So, either you do not echo :
$_SESSION['username'] = $username;
header('Location: your url');
exit;
Or you do a HTML (or javascript) redirection, with a 5 seconds delay:
echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
exit;
In which case you have to put it in the < head > section, to do the HTML redirection:
<meta http-equiv="refresh" content="0; url=http://example.com/main.php" />
Also
error_reporting(0);
Should be put at the beginning of the page, unless you want errors for previous lines to be shown.
BUT : error_reporting(0); should NEVER be used on a development site (and always on a production site).
You should turn on display_errors('on') and error_reporting(E_ALL) to see errors - errors are very useful for a developer.

Login page and profile page redirection the system do not display the right page

I have a login page that allow user to submit a registered email and password and if the data is correct then the system redirect to the profile page and here i face the problem .
when I try to submit the write data the system do not redirect me to the profile page .
but if I echo a confirm message that the data are correct the browser display this message
how to fixx this problem ???
login.php
<?php
session_start();
error_reporting(E_ALL);
require_once('include/connect.php');
$message = "";
if(!empty($_POST['email']))
{
$email = $_POST['email'];
$pass = $_POST['pass'];
$email = strip_tags($email);
$pass = strip_tags($pass);
$email = mysql_real_escape_string($email);
$pass = mysql_real_escape_string($pass);
//$pass = md5($pass);
$sql=mysql_query( "SELECT user_id, email_address, first_name FROM user WHERE email_address='$email'AND password='$pass'LIMIT 1") or die("error in user table");
$login_check = mysql_num_rows($sql);
if($login_check > 0)
{
$row = mysql_fetch_array($sql);
$id = $row['user_id'];
$_SESSION['user_id'] = $id;
$firstname = $row['first_name'];
$_SESSION['first_name']= $firstname;
$email = $row['email_address'];
$_SESSION['email_address']= $email;
mysql_query("UPDATE user SET last_log_date=now() WHERE user_id='$id'");
//$message = "correct email and passworddd!!";
header("Location: profile.php");
}//close if
else
{
$message = "incorrect Email or Password!!";
//exit();
}
}//close if
?>
profile.php
<?php
session_start();
require_once('include/connect.php');
if(isset($_GET['user_id']))
{
$id=$_GET['user_id'];
var_dump($id);
}
elseif(isset($_SESSION['user_id']))
{
$id= $_SESSION['user_id'];
}
else
{
print "Important data are missing";
print_r($_SESSION);
exit();
}
$sql = mysql_query("SELECT * FROM user WHERE user_id='$id'") or die(mysql_error());
$row = mysql_fetch_array($sql);
$firstname=$row['first_name'];
$lastname=$row['last_name'];
$birth_date=$row['birth_date'];
$registered_date=$row['registered_date'];
//***************for upload img*****************//
$check_pic="members/$id/image01.jpg";
$default_pic="members/0/image01.jpg";
if(file_exists($check_pic))
{
$user_pic="<img src=\"$check_pic\"width=\"100px\"/>";
}
else
{
$user_pic="<img src=\"$default_pic\">";
}
echo $id, $firstname, $birth_date;
?>
Easy :) Just put all this code on the top of content and be sure that there is no any content on the page where header("Location: profile.php"); is working, because if there is something it can't be loaded. I also recommend to use exit; after header("Location: profile.php");

PHP Session not holding values

After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;

Categories