I am working with php session as one of my experiment. Trying to learn by developing a script. But I have stacked. I am not quire sure why the php session isn't working.My log in page redirecting my page when i submitting correct email address and password. I am trying to skip log in page if session is set. But its not redirecting. here is the code. Even there has no error log output. So i became so confused what wrong with my code. I am looking for expert suggestion on my experiment.
<?php
session_start();
#Working With Session
if (isset($_SESSION['UserId'])) {
# code...
header('location:/management/index.php');
exit();
}
require_once("../configuration.php");
#Veriable collected From Login Panel
$Submitted_Email_Address=$_POST['email'];
$Submitted_Password=$_POST['password'];
$encrypt_Submitted_Password=md5($Submitted_Password);
#Lets gather Data From MySql Database
$con=new mysqli($hostname,$dbusername,$dbpass,$dbname);
if (mysqli_connect_errno($con)) {
die('The connection to the database could not be established.');
}
$query="SELECT * FROM users WHERE Email_Address='$Submitted_Email_Address'";
$result=$con->query($query);
$row=$result->fetch_array();
$SQL_Password = $row['Password'];
#LookUp Mysql Database to Get username/user id to store in session
$SQL_UserID=$row['id'];
$SQL_UserName=$row['username'];
$SQL_FirstName=$row['First_Name'];
$SQL_LastName=$row['Last_Name'];
$SQL_Role=$row['Role'];
if ($encrypt_Submitted_Password!=$SQL_Password) {
echo "Please check your email address and password again";
}
elseif ($encrypt_Submitted_Password == $SQL_Password) {
$_SESSION['UserID']=$GLOBAL['SQL_UserID'];
$_SESSION['UserName']=$GLOBAL['SQL_UserName'];
$_SESSION['FirstName']=$GLOBAL['SQL_FirstName'];
$_SESSION['LastName']=$GLOBAL['SQL_LastName'];
$_SESSION['Role']=$GLOBAL['SQL_Role'];
header('location:/management/index.php');
}
#Lets CLose All The MySql Connection
$result->free();
$con->close();
?>
After that i tried to see if the session is not set then redirect the page. but its not redirecting. I tried the following code to check if the session is not set let redirect the page. but not redirecting
session_start();
#Working With Session
if (!isset($_SESSION['UserId'])) {
# code...
header('location:/management/index.php');
exit();
}
You need to change your header call:
header('Location: /management/index.php'); // notice capitalization and spacing; they matter.
I guess you are missing something so silly. your code seems that its a php file which gather email address and password from a login page and validate it and then redirect it two another page.
I think your login page (might be login.html, access.html) is not redirecting. So your should put this following php code block in the login page. not here in the login.php which is only used to validate the inputed data. Happy coding and keep your mind calm. :)
and you have to use 'UserID' not 'UserId'
session_start();
#Working With Session
if (isset($_SESSION['UserID'])) {
# code...
header('location:/management/index.php');
exit();
}
Remove "!" from isset or put redirect in else clause:
eg:
session_start();
#Working With Session
if (**!**isset($_SESSION['UserId'])) {
# code...
header('location:/management/index.php');
exit();
}
Related
This is just about the last thing I have left to do and I will have officially created my first PHP registration/login system.
What I have is a file called checksession.php. This file checks to see if a user is logged in/has a session created. If the user does, it should let them view their account page. If it isnt, it should send them to index.php.
As it stands, it is sending the user back to index.php even after successfully logging in. I am not sure what I am doing wrong in this script.
checksession.php
<?php
include('includes/db.php');
session_start();
$userSession = $_SESSION['username'];
$sql = mysqli_query($db, "SELECT emailAddress FROM users WHERE emailAddress='$username' ");
$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);
$login_user=$row['emailAddress'];
if(!isset($userSession )) {
header("Location: index.php");
}
?>
username is referencing the username field they are filling out when logging in on the login form which is login.php.
On their account page, which in this case is account.php, I have the following:
<?php
include("includes/checksession.php");
?>
Should this be redirecting to index.php or should it be setting the session based on the username they are inputting? I did make sure the start_session(); on my login.php page as well.
Make sure its session_start(); on my login.php page not start_session();
Try to echo out the $userSession and $_SESSION['username'] to see what they actually hold
Try the statement this way
.
if(isset($_SESSION['username'])) {
//do what ever
}else{
header("Location: index.php");
}
The Variable $userSession will always be set, it may me be null or empty string but it will always be set from your code.
Change the check to:
if(!isset($_SESSION['username'])) {
header("Location: index.php");
}
Ok
I dont know if this is the best way to do this as I think I may be over complicating this but here we go:
I took the check.php code and actually dropped this into my login code in order to set the SESSION.
Right below that I have the following code:
if(mysqli_num_rows($result) == 1) {
$_SESSION['username'] = $login_user; // Initializing Session
header("location: account.php"); // Redirecting To Other Page
} else {...
Logged in and voila. I am taken to my account.php like I would expect to be. If I log out and then try to view account.php, I am bounced back over to index.php.
I have a log in script where I have been able to successfully make users, and log in. Now my issue is that whenever I try to use my method of protecting pages, being seeing if there is a SESSION for 'user' if not it directs you back to the login page.
Here is me checking for the session,
require("common.php");
if(empty($_SESSION['user']))
{
header("Location: login");
die("Redirecting to login");
}
Here is where I am setting my session, I am ONLY setting a session_start(); on login.php
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
header("Location: home?worked=1");
die("Redirecting to: home?worked=1");
session_start();
}
else
{
print("Login Failed.");
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
What this does, is I log in, and it will process and bring me to my home page, then process the header back to the login page acting as if I am not logged in. I tested a false login and it IS telling that its the correct login.
Thanks for any help, I'm pulling my hair out here!
Necro
EDIT
I moved session_start(); to the top of my common.php, and everything is perfect.
You have session_start(); after $_SESSION['user'] = $row;
Actually you have it after a die(); command. Nothing happens after that.
Put session_start(); at the top of PHP in every page (pref common.php since you have one) not just one page.
It would be better to set the session_start() on top
You need to put session_start(); on every page you want to use the session.
www.example.com/index.html on my website is a page that asks for a password, and when entered, runs through www.example.com/login.php.
<?php
if (isset($_POST['pw']) && ($_POST['pw'] == "mypassword"))
{
// Location after Logged in
header('Location: http://example.com/kareha/index.html');
}
else
{
// If not Logged in
header('Location: http://example.com/index.html');
}
?>
And then gets redirected to www.example.com/kareha/.
The problem is, anyone can just type in and directly navigate to www.example.com/kareha/.
Is there any way I can protect this index file (or anywhere else on the site) so anyone who isn't logged in is redirected to the main login page?
Also, would it help if it was protected through .htaccess? (/kareha/index.html is automatically updated according to a template, which has broken every time I mess around with it)
Edit: Maybe something along the lines of starting a session with /login.php and then having .htaccess in the /kareha/ folder check for the session?
you need to use sessions or .htpasswd. To use sessions, change your html files to php
here's the top of your login script
<?php
session_start();
// see if the form has been posted
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// check for the password
if($_POST['pw'] == "mypassword") {
// set a session
$_SESSION['loggedin'] = true;
// redirect to kareha/
header('Location: http://example.com/kareha/index.php');
}
} else {
header('Location: http://example.com/index.html');
}
// put HTML and login form here...
the very top of kareha/index.php
<?php
session_start();
if(!isset($_SESSION['loggedin'])) {
// redirect to login page
header('Location: http://example.com/index.html');
}
// put rest of page here
you can read about sessions here: http://www.php.net/manual/en/book.session.php
Edit: I misread the original question. Revised...
I have the website pages for visitors and the pages for the client manage it on /admin
I created a login system at admin/index.php and it's working fine. But, if I type the url of an admin page in the browser (e.g admin/carro_admin.php) I get access even without been loged. So I'm trying to put some session check on this page (carro_admin) to block visitors and allow just login access.
I trying to do that with:
if (isset($_SESSION)) {
header("location:carro_admin.php");
}
else {
header("location:index.php");
}
exit();
It's blocking the access and sending me to index.php (and that's right). But now the login system doesn't work. When I type my username and password I'm redirected to index.php again.
Is something wrong with my session code?
Ps.: I already read this question: How to set and check a session after login? but it didn't work too.
Add this to login process i.e is when entered username/password and clicked on submit button.
<?php session_start();
/*authenticate the username &^ password*/
if($result) {
$_SESSION['logged_in']=1;
}
?>
now on the admin page
<?php session_start();
if(isset($_SESSION['logged_in'])) {
header("location:carro_admin.php");
} else {
header("location:index.php");
}
?>
Do you have session_start () at the top of the page where your redirect is? If not, it won't set the session. I can hit the page from a non-browser, and get all of the contents of your admin page without being redirected. You need to have the script die after the redirect in the case that the user is not logged in. Also, you shouldn't use isset ($_SESSION). You should use something like #$_SESSION["loggedIn"] === TRUE.
To login I use:
<?php
session_start();
if($_POST){
$csUSER='USERNAME';
$csPASS='PASSWORD';
$user=$_POST['user'];
$pass=$_POST['pass'];
if ($user==$csUSER) {
if ($pass==$csPASS){
$_SESSION['cdb']="1";
header("Location: /");
exit;
} else {
$passerror='<span class="errormsg">Wrong Password.</span>';
} // END IF PASSWORD
} else {
$usererror='<span class="errormsg">Wrong Username.</span>';
} // END IF USERNAME
} // END IF $_POST
?>
To allow myself to do admin tasks per page (included in all pages [top of page]):
<?php
session_start();
if(isset($_SESSION['cdb'])){
$loggedn="WORD";
}
?>
This allows me to:
<?php
if ($loggedn=="WORD") { WHATEVER }
?>
And to make sure I only have access to backend pages when logged in (included in all backend pages):
<?php
// backend login check
if($loggedn!="WORD") {
header("Location: /"); // if not logged in, go to homepage
exit;
}
?>
The problem is, it works perfect on my pc, but I have another pc my wife uses for data collation and it does not stay logged in on her pc. We both use Linux (Fedora) with FF. I have been over ever line of code in each page, help!
A few things to check:
Ensure that you are starting with a clean slate. Clear cache and cookies in your browser to ensure that you don't have an old session open.
Ensure that session data is being stored on the new machine. Session data is commonly stored in /tmp
Ensure that there is no client-specific code being executed in relation to the session.
Call the exit function after redirecting to another page, otherwise the following code will be executed anyway, what can lead to strange behaviour.
if($loggedn != "WORD")
{
// redirect to login page
header("Location: login.php");
exit;
}
// the following code will be executed if exit is not called
...