Pass the login details to another page using session PHP
Solution 1
First of all make sure that you place session_start()
at the very beginning of any script you use it in. There can be no output to the browser before you call session_start()
and that includes spaces or new-lines before the opening <?php
tag.
So:
<?php
session_start();
...
Second, make sure you terminate your script after a redirect, for example:
header("location:edit_user.php");
exit();
That makes sure that no code after the redirect gets executed, so sessions won't get unset or session variables changed by accident.
Solution 2
session_register()
is a deprecated function. Just use $_SESSION["bar"] = "foo"
to store something.
Solution 3
for future references, please post parts of your code when you are asking questions. It helps everyone to give you an answer in more specific cases.
<?php
session_start();
if(!isset($_SESSION['Foo']))
{
$_SESSION['Foo'] = "Bar";
}
?>
Source : http://php.net/manual/en/features.sessions.php
Maggi
Updated on July 26, 2022Comments
-
Maggi almost 2 years
I need the login details in another page for retrieving the data from the database. Basically, I need to display the editable form with the details of the user logged in. I tried
session_register()
for storing the username in login.php page. But for some reason I am not able to display the username using$_SESSION[]
in my edit.php page. I am doing this after the functionsession_start()
as well.I am new to php, so don't know whether I misunderstood session! Or is there any other way to pass the login details?
Thanks in advance
My code:
**Login.php** <?php $userName = $_POST['username']; $password = $_POST['password']; //Connect to the database //query the database if($rows==1) { session_start(); $_SESSION['user']=$userName; header("location:edit_user.php"); } else { echo 'Data Does Not Match <br /> Re-Enter UserName and Password'; } ?> **In edit.php** <?php session_start(); if(!isset($_SESSION['user'])) { header("location:login_form.php"); } else { echo $_SESSION['user']; } ?>
-
Maggi over 11 yearsI need to store $_SESSION['xyz']=$userName where $userName=$_POST['username']. Am I wrong with the syntax?
-
Pramodh over 11 yearsYou can directly assign $_SESSION['xyz']=$_POST['username'] but for that you need the username data field from a form. You can take that data while user is logging in after verifying his login.