$_SESSION variable not saving between pages PHP [duplicate] - php

This question already has answers here:
Session variables not working php
(12 answers)
Closed 4 years ago.
Im trying to save my username to the SESSION variable using a login system however it doesn't save.
I tried printing the session variable straight away in the same page and that works however when i go to another page, it won't save.
I'm very new this stuff so im sorry if it's something obvious :)
Any help will be much appreciated :)
PHP CODE 1:
$app->post('/api/customer/login/{Username}/{PassW}', function(Request $request, Response $response){
$Username = $request->getParam('Username');
$PassW = $request->getParam('PassW');
$PassW = md5($PassW);//FIND NEW WAY OF HASHING AS MD5 IS DEPRECIATED
$sql = "SELECT * FROM login WHERE Username= '$Username' AND PassW='$PassW' LIMIT 1";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($result) == 1){
session_start();
$_SESSION['Username'] = $Username;
echo "<script type='text/javascript'>alert('Correct!');
window.location='http://localhost/testing/dashboard.php';
</script>";
exit();
PHP CODE 2 (The next page):
This page is simply a HTML page with other stuff but has the below PHP code in its body to test if its saved the variable.
<?php
session_start();
print_r($_SESSION);
?>

This code is missing the session_start(): PHP CODE 2 (The next page)
It should have been:
<?php
session_start();
print_r($_SESSION);
?>

whenever you use session on the page so you must start the session on that page so your code on code 2 page should be like this
<?php
session_start();
print_r($_SESSION);
?>
also, add the same line on a login page
session_start();
if everything seems fine to you then try to remove the cache from your browser as you are using javascript to redirect the page and there might be a chance that browser is loading the page from cache.

Related

i am try to create session but always session empty

I want to try to make a session but always session Empty.Use this code rate this product this link send an email open email and click link Active than code working session empty please help me...
<?php
session_start();
include("myhomeportal/setting/config.php");
$conform = $_GET['conform'];
$query = mysqli_query($conn, "SELECT * FROM item_users where com_code='$conform'");
$row = mysqli_fetch_array($query);
if ($row) {
// now update `com_code`
$sql = "UPDATE item_users SET com_code='active', user_type='user' WHERE com_code='$conform'";
$result = mysqli_query($conn, $sql) or die(mysqli_error());
$inventory_id = $row['inventory_id'];
$active = $row['com_code'];
$_SESSION['sess_active'] = $active;
header("Location: category.php?inventory_id=$inventory_id");
} else {
// confirm code not found, show error
}
?>
Try to debug first.
Echo this $row['com_code']; then $_SESSION['sess_active'].
If they print something then go ahead.
There ir an error in your test page.
"sir other page is not working session just simple test code – Pankaj"
Instead you are only testing, you must start the session always with session_start() in every .php you want to use session.
Solving testing page.
"<h1>welcome <?php session_start(); echo $_SESSION['sess_active'];?> </h1> – Panka"
Note from w3schools:
The session_start() function must be the very first thing in your document. Before any HTML tags.
you are writting some html code before start the session, you should do that way:
<? php session_start(); ?>
<h1>welcome <?= $_SESSION['sess_active']; ?> </h1>
You can read more about this https://www.w3schools.com/php/php_sessions.asp

PHP Session won't start [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm having problem with starting a session in PHP. By looking around I wrote some code that should work but it doesnt. Can you please help me out because I don't know what's wrong here. This is my loging.php page
<?php
$host = "localhost";
$user = "usern";
$password = "gtest123";
$db = "test";
$errore = "Login info are wrong!`enter code here`";
mysql_connect($host,$user,$password);
mysql_select_db($db);
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "select * from utenti where username = '".$username."' AND Password = '".$password."' limit 1";
$result = mysql_query($sql);
if(mysql_num_rows($result)==1){
$_SESSION['username'] = $username;
header("location:index.php");
}
else{
echo "" .$errore;
}`enter code here`
}
?>
I than have my db with users on phpmyamin and the login it's working. The problem is when I load the index.php page.
<?php
session_start();
echo "Welcome" .$_SESSION[''];
?>
<html>
all the html code
I start this session because I want to be able to see which user do certian function in the website. However I get this error message:
Notice: Undefined index:
I know what the error means but I don't know how to fix it, any help?
So, firstly, I see you're using mysql_connect, which is a deprecated function because it's not secure at all, and it's replaced by mysqli_connect http://php.net/manual/en/book.mysqli.php for documentation. For even better security, and to protect against sql injection, you should use PDO, or prepared statements. In this example though, I have stuck to using mysqli because it's less of a learning curve.
Secondly, $_SESSION will only work if you first initialise the session using session_start(). This will have to be done on every page that you wish to read or write session data from.
<?php
//Since this page writes to a session, initialise it here
session_start();
//The values to connect to the database with
$host = "localhost";
$user = "usern";
$password = "gtest123";
$db = "test";
//Create a new mysqli connection to the database
$conn = mysqli_connect($host, $user, $password, $db);
//This is the error message that's displayed on unsuccessful login
$error = "Login info are wrong!`enter code here`";
//This is the error message if the username is not specified
$errorNoUsername = "You have not specified a username";
/**
* Now that we're using mysqli_connect(), we don't need this code.
* mysql_connect($host,$user,$password);
* mysql_select_db($db);
**/
//See if the user has submitted the form with the username parameter
if(isset($_POST['username'])){
//If they have, shortname the variable for username and password
$userUsername = $_POST['username'];
$userPassword = $_POST['password'];
//Build your select query. In production, you should use PDO or Prepared Statements to protect against injection
//I've removed your LIMIT 1 from the query, because I see you're checking for a distinct match later on with mysqli_num_rows==1
$sql = "SELECT * FROM utenti WHERE username='".$userUsername."' AND Password = '".$userPassword."'";
//run the query on the connection created earlier
$result = mysqli_query($conn, $sql);
//Check if there's a distinct match
if(mysqli_num_rows($result)==1){
//There is, good, initialise session with the user data
$_SESSION['username'] = $userUsername;
//Reload to your index.php page
header("location:index.php");
} else {
//Display the error message
echo $error;
}
} else {
echo $errorNoUsername;
}
?>
So now that we've done that, assuming a successful login, we have redirected the user back to index.php, since we are reading from session data, we need to initialise the session again, using session_start();, which you've already done, but your key $_SESSION[''] doesn't exist, so there is an error. Here, I have corrected.
<?php
session_start();
echo "Welcome, " . $_SESSION['username']; //Added keyname
?>
<html>
all the html code
</html>
Use session_start() in every page where you want to work with sessions and as you are setting $_SESSION['username'] in loging.php page so you need to change
echo "Welcome" .$_SESSION[''];
with
echo "Welcome" .$_SESSION['username'];
In this way, you will be able to get the session of username in index.php which you have set in loging.php page

Updating user information

I know I can't use two session start codes in a same php page but for the sake of updating user account, I need the below code and I need to use session_start twice. One, to check if the user is not logged in, then redirect them and banned them from seeing the update info page and also the other session start has to be there so that my session variables could be set automatically in the update info page if the user is logged in.
anyways, I am getting this error can you guys please show me a work around way? if there's any?
thanks.
Notice: A session had already been started - ignoring session_start() in ....
<?php session_start();
if(isset($_SESSION['userid'])) {
} else {
header('Location: login.php');
}
?>
<?php
$user = $_SESSION['userid'];
$myquery = "SELECT * FROM our_users WHERE `userid`='$user'";
$result = mysqli_query($conn, $thequery);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
session_start(); /* Basically this right here gets ignored. */
$_SESSION["user_first_name"] = $row['fn'];
$_SESSION["user_last_name"] = $row['ln'];
$_SESSION["user_email"] = $row['em'];
$_SESSION["user_password"] = $row['pw'];
?>

PHP session not persisting between screens

I have come across an issue that has confused me a lot.
I am working on a login screen using PHP and MySQL. I manage to validate the username and password against an existing user in the database and after this, I initiate a session, and set the session variable username to the username provided in the login screen.
$username = html($_POST['username']);
$password = html($_POST['password']);
$result = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
$result->bindValue(':username', $username);
$result->bindValue(':password', $password);
$result->execute();
foreach($result as $user)
{
$count = $count + 1;
}
if ($count == 1)
{
session_start();
$_SESSION['username'] = $username;
` //if I do an echo $_SESSION['username'] it displays the correct user
header('Location: .');
exit();`
}
However when it transfers me to the index.php page the $_SESSION['username'] variable has disappeared and I do not understand why. This is the code I use in index.php to check for the username:
<p>View all tasks</p>
<p>Add your own task</p>
<p>Welcome, <?php echo $_SESSION['username']; ?></p>
however I get the following error: Notice: Undefined variable: _SESSION in C:\xampp\htdocs\abcabcabc\index.php on line 16
All advice will be greatly appreciated guys
Add sesssion_start() to all of your scripts that use the session
You must use session_start(); at the beginning of index.php file.
The first 2 answers are correct. You must start session on each page. I usually just put it in a file that is "included" in every page already (like a header file) so I don't have to think about it.

Session variables not transferring between pages [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
I am making a simple login page however my $_SESSION variables are not transferring between pages. I've read numerous other posts about session_start() at the beginning of each page, folder writing priveleges, session_write_close(), etc., but none have worked. The session_write_close() doesn't make a difference withor without so I just left it in. All of the code below works fine as I have left out code below and above such as where $login_fail comes from.
Currently I set the the $_SESSION variables as shown in the code below:
if($login_fail == "")
{
$query = "SELECT first_name, last_name, email_address,password FROM user_info WHERE email_address = '$email_address' AND password = '$password'";
$result = mysql_query($query);
if(!$result) die ("Database access : " .mysql_error());
elseif (mysql_num_rows($result))
{
$row = mysql_fetch_row($result);
$token = "$email_address";
$token1 = "$password";
echo "token: $token, token1: $token1, row[1]: $row[1], row2: $row[2] </ br>";
if($token == $row[2] && $token1 == $row[3])
{
session_start();
$_SESSION['first_name'] = $row[0];
$_SESSION['last_name'] = $row[1];
$_SESSION['email_address'] = $row[2];
$_SESSION['password'] = $row[3];
$_SESSION['check'] = md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']);
//print_r($_SESSION);
session_write_close();
header("Location: http://127.0.0.1/websiteproject/test.php");
}
else die("Invalid username/password combination");
}
}
else
{
echo "Login failed. Please try again.";
}
I have done print_r($_SESSION) and it prints all the correct information.
The session variables are then called again in my test.php just to see what happens in really simply code.
session_start();
print_r($_SESSION);
The result is an empty array.
When I go to the easyphp temp file where my sessions are written I always find two files: the original one with all the correct information and a new one with no information. It seems as if when I call the second session_start() it is literally starting a new session and not recalling the current session.
I try to do my research to give as much info as possible and not waist people's time. Any ideas are greatly appreciated. Odd is that this was working a few days ago and then I started making changes to files deeper into the program and this happened. So I made the test.php just to find out more about the transfer problems.
You cannot call session_start() once any data or whitespace has been output to the browser.
In the code you posted, you are calling echo "token: $token, token1: $token1, row[1]: $row[1], row2: $row[2] "; prior to calling session_start() which will not start the session.
Add error_reporting(E_ALL); ini_set('display_errors', 1); to the beginning of your script and you should see a warning about not being able to start the session because output has already been sent.
Try moving the session_start(); call to the very beginning of the file.

Categories