PHP sessions to go to user specific page [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to make a page where a user logs in and they are taken to a personalized page. What I am having problems with is, while the user is still logged in, if they type in the generic url, that they are still logged in and their personalized page is viewable. (Similar to when you are logged into Facebook and it goes straight to your feed if you type in www.facebook.com) I tried using sessions for this, but am having no luck.
<?php
if(isset($_REQUEST['user']) != true) {
?>
<html>
<head>
<title>Welcome</title>
</head>
</html>
<body bgcolor="white">
<h1>Welcome</h1><br>
If you have an existing account, log in here:<br>
<form name="loginForm" action="test.php" method="get">
User name: <input type="text" name="user" /><br>
Password: <input type="password" name="pass" /></br>
<input type="submit" value="Login" />
</form>
<br>
<hr>
<br>
Otherwise, if you'd like to create an account, please fill out the following form:<br>
<form name="createAccountForm" action="test.php" method="get">
User name: <input type="text" name="user" /><br>
Password: <input type="password" name="pass" /><br>
First name: <input type="text" name="fname" /><br>
Last name: <input type="text" name="lname" /><br>
<input type="hidden" name="create" value="true">
<input type="submit" value="Create Account" />
</form>
</body>
</html>
<?php
}
else if(isset($_REQUEST['user']) == true) {
session_start();
if(!isset($_SESSION['uname']))
{
header('location:test.php?redirect='.$_SERVER['REQUEST_URI']);
exit;
}
// personalized page code
}

EDIT:: A solution first for your own existing code. should work fine.
<?php
session_start();
if(isset($_REQUEST['user'])) {
if(isset($_SESSION['uname']))
{
header('location:test.php?redirect='.$_SERVER['REQUEST_URI']);
exit;
}
// personalized page code
} else {
?>
<html>
<head>
<title>Welcome</title>
</head>
</html>
<body bgcolor="white">
<h1>Welcome</h1><br>
If you have an existing account, log in here:<br>
<form name="loginForm" action="test.php" method="get">
User name: <input type="text" name="user" /><br>
Password: <input type="password" name="pass" /></br>
<input type="submit" value="Login" />
</form>
<br>
<hr>
<br>
Otherwise, if you'd like to create an account, please fill out the following form:<br>
<form name="createAccountForm" action="test.php" method="get">
User name: <input type="text" name="user" /><br>
Password: <input type="password" name="pass" /><br>
First name: <input type="text" name="fname" /><br>
Last name: <input type="text" name="lname" /><br>
<input type="hidden" name="create" value="true">
<input type="submit" value="Create Account" />
</form>
</body>
</html>
<?php
}
?>
Here is a login solution of my own (stripped out a bit to be generic) it also includes the code for a PDO query of the database and checking of a password with php's password_hash function. I will point out the code that is specifically relevant to your question:
Assuming that as you are building a login page, and wanting to send users to other parts of the site relevant to their status. I think the whole script is relevant. You can easily swap and change what happens as a result of the session variable values.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
//start the session before sending any other output
session_start();
require('dbconn.php');
// checks if a session eid has been set, if so, send them to the usercp.
if(isset($_SESSION['eid'])){ header("Location: usercp.php"); } else {
try{
//build a login page
$loginpage ="<html><head><title>Portal Login</title></head><body>";
$loginpage.="<div align=\"center\" id=\"box\">";
$loginpage.="<table><tr><td><img src=\"images/login.jpg\" /></td></tr>";
$loginpage.="<tr><td><div align=\"center\">";
$loginpage.="<font face=\"Courier New, Courier, monospace\">Please enter your email<br /> address and password.</font><br />";
$loginpage.="<br /><form action=\"\" method=\"post\" name=\"login\" ><div align=\"right\">";
$loginpage.="<font face=\"Courier New, Courier, monospace\">Email:</font><input type=\"text\" size=\"40\" name=\"email\" />";
$loginpage.="<br /><br /><font face=\"Courier New, Courier, monospace\">Password:</font><input type=\"password\" size =\"40\" name=\"password\" />";
$loginpage.="<br /></div><br /><input type=\"reset\" value=\"Reset\" /> ";
$loginpage.=" <input name=\"submit\" type=\"submit\" value=\"Login!\" />";
$loginpage.="</form></div></td></tr></table></div></body></html>";
//checks if somebody is trying to login
if(isset($_POST['submit']))
//checks that the username and password have both been filled out if not, show the login page
{ if(!$_POST['email'] || !$_POST['password'])
{
echo $loginpage;
echo "Please enter your login details";
} else { //otherwise search the database for the email address
$db = NEW pdo($dsn, $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$email = $_POST['email'];
$password = $_POST['password'];
$check = $db->prepare("SELECT * FROM employees WHERE email = :email");
$check->bindParam(":email", $email);
$check->execute();
//unset the session variables
unset($_SESSION['eid']);
unset($_SESSION['email']);
unset($_SESSION['userlevel']);
unset($_SESSION['fname']);
//check if the password hash matches php's hash of the password
if(($row = $check->fetch()) && (password_verify($password,$row['password']))) {
// set the session variables
$_SESSION['eid'] = $row['eid'];
$_SESSION['email'] = $row['email'];
$_SESSION['userlevel'] = $row['userlevel'];
$_SESSION['fname'] = $row['fname'];
// if the user's userlevel is higher than 1 give them the option of the admin page
if($row['userlevel'] > "1") {
echo "<center><a href='usercp.php'><h1>User Panel</h1></a><br><br><a href='admin/admincp.php'><h1>Admin Panel</h1></a></center>";
} else { //otherwise send them straight to the usercp
header("Location: usercp.php");
}
} else { //if the email is not found or password is incorrect, show the loginpage again
echo $loginpage;
echo "Login details incorrect, please contact your manager.";
}
}
} else { //if nobody has logged in already, or tried to log in just now, show the login page
echo $loginpage;
}
//pdo error reporting code
} catch (PDOException $e) {
throw $e;
}
}
?>

Related

PHP- Login to account to working

its my first time creating a login page.
I want users to login, then the page redirects to the customer account page, if they have a account. I have added echo's so i can see whats happening. I have a "Logged in successfully" alert that works perfectly when i login. The page just does not redirect.
HTML
<section class="container">
<form id="myform " class="Form" method="post" action="login.php" accept-charset="utf-8">
<!-- <div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value='' required>
<input class ="login-field" type="password" id="pass1" name="pass1" value="" placeholder="Password" maxlength="30" required>
<input type="submit" name="login" value="login" class="btn ">
<br>
</form>
PHP
<?php
session_start();
require ('./mysql.inc.php');
?>
<?php
if (isset($_POST['login']))
//database varianbles
$c_email = $_POST['email'];
$c_password = $_POST['pass1'];
// select login details
$sel_c = "SELECT * FROM Cus_Register WHERE Cus_Email='$c_email' AND Cus_Password='$c_password'";
$run_c = mysqli_query($dbc, $sel_c);
//check if customer is on databse
$check_customer = mysqli_num_rows($run_c);
if ($check_customer == 0) {
echo "<script> alert('password or email is incorrect please try again')</script>";
exit();
}
else{
$_SESSION['Cus_Email'] = $c_email;
echo "<script> alert ('Logged in successfully')</script>";
echo "<script>window.open('./customer/Cus_Account.php'.'_self') </script>";
}
?>
You may use header() to redirect
else
{
$_SESSION['Cus_Email'] = $c_email;
header('Location: customer/Cus_Account.php');
exit();
}
hope it helps:)
Do you intend window.open('./customer/Cus_Account.php'.'_self') to be window.open('./customer/Cus_Account.php', '_self')?
window.open takes a location and a target parameter and in JavaScript parameters are separated by a comma, not a full stop. In this case './customer/Cus_Account.php' is the location and '_self' is the target.

Page doesnt display on browser if i uncomment the session_start() code

These are the four pages which include the code for sessions. when i run the sign_up.php page an error comes up stating the page cannot be displayed. So the sessions are giving me an problem. I have included the session code on each page however i believe the problem is in the header(location:........); So any solutions please.
sign_up.php
<?php
//session_start();
//if (!isset($_SESSION["user_login"])) {
// header("Location: sign_up.php");
//} else {
// $username = $_SESSION["user_login"];
//}
?>
<!----------------------------------------------------------------------------------------------------->
<h1> Sign Up </h1>
<hr>
<div class = "user_type">
<form action="sign_up.php" method="POST" enctype="multipart/form-data">
<input type="radio" value="Student" id="radioOne" name="account" checked/>
<label for="radioOne" class="radio" chec>Student </label>
<input type="radio" value="Landlord" id="radioTwo" name="account" />
<label for="radioTwo" class="radio">Landlord</label>
<hr/>
<div class = "gender_options">
<input type="radio" value="Male" id="male" name="gender" checked/>
<label for="male" class="radio" chec>Male</label>
<input type="radio" value="Female" id="female" name="gender" />
<label for="female" class="radio">Female</label>
</div>
<input type="text" name="name" id="name" placeholder="Full Name" required/> <br/><br/>
<input type="email" name="email" id="name" placeholder="Email" pattern="[a-z0-9._%+-]+#aston.ac.uk" required/> <br/><br/>
<input type="text" name="password" id="name" placeholder="Password" required/><br/><br/>
<input type="text" name="password2" id="name" placeholder="Retype Password" required/><br/><br/>
By clicking Sign Up, you agree on our terms and condition. <br/><br/>
<input type="submit" name="submit" value="Sign Up"/>
</form>
</div>
<hr>
<!---- log in code--->
<?php
enter code here
if (isset($_POST["user_login"]) && isset ($_POST["user_pass"])){
// formatting field via reg replace to ensure email and password only conisists of letters and numbers preg_replace('#[^A-Za-z0-9]#i','',
$login_user = $_POST["user_login"];
$login_password = $_POST["user_pass"];
// password is encryted in DB (MD5) therefore user inputted password will not match encryted password in DB - we have to assign new var
$decrypted_password = md5($login_password);
// Query which finds user (if valid) from DB - Achieving authentication via username and password
$user_query = mysqli_query($connect, "SELECT * FROM users WHERE email = '$login_user' AND password = '$decrypted_password' AND closed = 'no' LIMIT 1");
$check_user = mysqli_num_rows($user_query); // checking to see if there is infact a user which those credentials in the DB
if ($check_user==1){
while ($row = mysqli_fetch_array($user_query)){
$id = $row['user_id'];
}
enter code here
// if the user credentials are correct, log the user in:
$_SESSION["user_login"] = $login_user;
header( "Location: profile_student.php" ); // refresh page
exit;
// if user row does not equal 1 ...
//exit;
} else {
echo "<div class='wrong_login'>
<p> Email or password is incorrect, please try again. </p>
</div>";
}
}
?>
<h1> Log In </h1>
<hr>
<div class ="login_form">
<form action="sign_up.php" method="POST">
<input type="text" name="user_login" placeholder="Email" pattern="[a-z0-9._%+-]+#aston.ac.uk" required/><br/><br/>
<input type="text" name="user_pass" placeholder="Password" required/> <br/><br/>
<input type="submit" name="login_submit" value="Log In"/>
</form>
</div>
</div>
home.php
<?php
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: profile_student.php");
} else {
$username = $_SESSION["user_login"];
}
include ("connect.php");
echo "Hello,";
echo"<br/> Would you like to logout? <a href = 'logout.php'>LogOut</a>";
?>
profile_student.php
This is the page for when the user logs in and this page will allow them to access their information etc.
<?php
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: sign_up.php");
} else {
$username = $_SESSION["user_login"];
}
include ("includes/connect.php");
?>
logout.php
this is the log out code for my website
<?php
session_start();
session_destroy();
unset($_SESSION);
session_write_close();
header( "Location: ../index.php" );
die;
?>
Instead of doing the session_start in each page, make a common.php file and include this file in all the required pages. Also, you need to make sure there is no white space before session is started, otherwise it would throw the header already sent error!
You are true, the problem is the header.
You are creating an infinite loop saying : you come on sign_up ? If $_SESSION['user_login'] doesnt exist, go to sign_up.
And it repeats over and over again. Because $_SESSION['user_login'] cant exist first time you come on sign_up.
So just do this : on your sign_up page.
<?php
session_start();
And so remove the if / else condition.

PHP Form submit on condition

I have a basic form, I only want it execute when the users input matches a set one. How can I make it so the user can only get to the add books page if the supply the "Admin" username and the password "password1"?
//Admin Login
echo "<form method='post' action='addBooks.php'>
Username:<br>
<input type='text' name='Username' value='Admin'>
<br>
Password:<br>
<input type='text' name='password' value=''>
<br><br>
<input type='submit' name='sbmt' id='sbmt' value='user_value' class='user_class' onSubmit='return submit();'/>
</form>";
function submit(){
if($_POST['Username'] == 'Admin')&&($_POST['password'] == 'Password1'){
return true;
}
else{
alert("Please check Username and Password")
return false;
}
}
Edit:
To clear up the issue.
I am trying to have a form with a username and password input. When the user clicks submit on this form it currently takes the user to addbooks.php. I want to make this conditional so that the user can only access the addbooks.php page if the username they provide ="Admin" and the password the provide = "Password1". I am currently trying to execute the submit function on the button click and the submit function is supposed to check if username and password match admin and password1. if they do it should let you through to addbooks.php
You could try this (note the header("Location: addBooks.php") part MUST be at the top of your code, before any html is outputed):
if (isset($_POST["Username"]) and isset($_POST["password"]) ) {
if ( ($_POST["Username"] == "Admin") and ($_POST["password"] == "Password1") ) {
header("Location: addBooks.php");
exit;
}
else {echo "Please check Username and Password <br/>";}
}
//Admin Login
echo '<form method="post" action="'.$_SERVER['PHP_SELF'].'">
Username:
<br/>
<input type="text" name="Username" value="Admin">
<br/>
Password:
<br/>
<input type="text" name="password" value="">
<br/>
<br/>
<input type="submit" name="sbmt" id="sbmt" value="Submit" class="user_class"/>
</form>';

PHP/ HTML login alert box issue

So essentially I have this PHP code which is a login system for a webpage not using MySQL but using pre-determined values within the PHP code. I am running php 5.5.3.
The page I have designed is a called access.php. If you enter the pre-defined username and password correctly it takes you through to a user.php page, but if either are incorrect it comes up with an alert box: “Incorrect password or username”
However the problem I am having is that when that alert box comes up it fills the same page (access.php) with grey and the alert box is located within the middle losing all of the initial web page design, and then when you accept the alert box by pressing 'ok' it takes you back to the access.php page design again. I want this alert box to come up over the page I have already designed without losing any of the initial design.
Here is the code for PHP:
<?php
session_start();
if (isset($_POST['username'])) {
// Set variables to represent data from database
$dbUsname = "adminDJ";
$dbPassword = "admin";
$uid = "1111";
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
print 'incorrect username or password.';
}
}
?>
Here is the HTML markup:
<form id="form" action="access.php" method="post"enctype="multipart/formdata">
<h2>DJ Access</h2>
<div class="lineSpacer"></div>
<p>Username <input type="text" name="username" id="userBox"/></p> <br />
<p>Password <input type="password" name="password" id="passBox"/></p> <br />
<input type="submit" value="Login to DJ Access" name="Submit" id="submit"/>
<div class="lineSpacer"></div>
</form>
Is there any way I can have it so PHP either alerts a box within the same page or uses JavaScript to alert a box?
If the above php code is on th esame page access.php then rather than a print set a variable to then use to display a message:
<?php
session_start();
$error = false;
......
} else {
$error = true;
}
then after the form:
<form id="form" action="access.php" method="post"enctype="multipart/formdata">
<h2>DJ Access</h2>
<div class="lineSpacer"></div>
<p>Username <input type="text" name="username" id="userBox"/></p> <br />
<p>Password <input type="password" name="password" id="passBox"/></p> <br />
<input type="submit" value="Login to DJ Access" name="Submit" id="submit"/>
<div class="lineSpacer"></div>
</form>
<?php if($error){ ?>
<div class="error"> There was an issue with the form")</div>
<?php } ?>
or if you want an alert
<?php if($error){ ?>
<script> alert ("There was an issue with the form")</script>
<?php } ?>
Your code does not seem like it should behave how you are describing it but here is an idea using setTimeout():
access.php
<?php
session_start();
if (isset($_POST['username'])) {
// Set variables to represent data from database
$dbUsname = "adminDJ";
$dbPassword = "admin";
$uid = "1111";
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
// use a setTimeout to display the alert after 100ms
print 'setTimeout(function(){alert(\'whatever you want\');}, 100)';
}
}
?>
<form id="form" action="access.php" method="post"enctype="multipart/formdata">
<h2>DJ Access</h2>
<div class="lineSpacer"></div>
<p>Username <input type="text" name="username" id="userBox"/></p> <br />
<p>Password <input type="password" name="password" id="passBox"/></p> <br />
<input type="submit" value="Login to DJ Access" name="Submit" id="submit"/>
<div class="lineSpacer"></div>
</form>
Just cut out of the php put in the JS and then open the php agsin. Put this where you want the box to appear in the code
?><script> alert("incorrect details"); window.history.back();</script><?php
This should work. :)

POST REDIRECT GET in form that submits to itself duplicate entries in database

I am having the hardest time of my life for not understanding the basics of the POST REDIRECT GET pattern in forms that submit to themselves.
The main problem is that when the user goes back or refreshes the page, I get duplicate entries in the database
So basically I have a page that contains two forms, each one submits to itself.
I have some code implemented regarding the PRG pattern but it doesn't seem to work.
I'll post a brief example where I'll try to explain what I am doing.
<?php
function saveUser1($UserName_1)
{
include 'db_conn.php';
//MySQL code etc...
if($result) return 1; //registro correcto
else return -2; //error
header('Location: samepage.php' , true, 303);
exit();
}
function saveUser2($UserName_2)
{
include 'db_conn.php';
//MySQL code etc...
if($result) return 1; //registro correcto
else return -2; //error
header('Location: samepage.php' , true, 303);
exit();
}
$error1 = 0;
$error2 = 0;
if(isset($_POST['userForm1']))
{
$error1 = saveUser1(clean_form($_POST['txtUserName_1']);
}
if(isset($_POST['userForm2']))
{
$error2 = saveUser2(clean_form($_POST['txtUserName_2']);
}
?>
Now the HTML
<form action="" name="userForm1" method="POST">
<label for="data">Some Data</label>
<input type="text" value="some test data to post" name="txtUserName_1" id="txtUserName_1" /><br />
<input type="submit" name="userForm1" id="userForm1"/>
</form>
<form action="" name="userForm2" method="POST">
<label for="data">Some Data</label>
<input type="text" value="some test data to post" name="txtUserName_2" id="txtUserName_2" /><br />
<input type="submit" name="userForm2" id="userForm2"/>
</form>
I just created this code in example of what I am trying to accomplish, but I haven't had any luck with the PGR pattern.
Could you guys tell me where the error is? Or redirect me (no kidding) to some good tutorial regarding this subject?
I have been looking to a lot of questions / answers, blogs but I can't find anything really solid (from my point of view).
Thanks in advance.
Below is sample code if you want try.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
Password: <input type="password" name="password">
<input type="submit" value="submit" name="send">
</form>
PHP Code and common.php is database connection file
<?php
require_once "common.php";
if(isset($_REQUEST['send']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$check = "SELECT * FROM user WHERE name = '".$name."' AND email = '".$email."' AND password = '".$password."'";
$check_result = mysql_query($check) or die(mysql_error());
if(mysql_num_rows($check_result) > 0)
{
header('Location : post.php');
}
else
{
$sql = "INSERT INTO user (name,email,password) VALUES ('$name','$email','$password')";
$result = mysql_query($sql) or die(mysql_error());
}
}
?>
Instead of checking for the form name itself check for a unique field within the form. E.g. If(isset($_POST[txtUserName_1'']))
The form name itself won't exist in the post.
To see what gets posted try:
print_r($_POST);
exit;
Maybe you have to set the post action to the same page.
And your form should not have the same name as your submit buttons(not sure about that).
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
<label for="data">Some Data</label>
<input type="text" value="some test data to post" name="data" id="data" /><br />
<input type="submit" name="submit1" id="userForm1"/>
</form>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" name="form2" method="POST">
<label for="data">Some Data</label>
<input type="text" value="some test data to post" name="data" id="data" /><br />
<input type="submit" name="submit2" id="userForm2"/>
</form>
For the php:
if(isset($_POST['submit1']))
{
$error1 = saveUser1(clean_form($_POST['txtUserName_1']);
}
if(isset($_POST['submit2']))
{
$error1 = saveUser1(clean_form($_POST['txtUserName_2']);
}
you can add a hidden field for checking if its executed:
<input type="hidden" name="executed" value="0"/>
then you can set it to 0 when you have executed the mysql query
function saveUser1($UserName_1)
{
if($_POST['executed'] == 0)
{
include 'db_conn.php';
//MySQL code etc...
if($result) $_POST['executed'] = 1; //registro correcto
header('Location: samepage.php' , true, 303);
exit();
}
}

Categories