I have a few session variables that I am trying to use in my application, however, I am unable to get them to show up on the pages I need them to.
This is the code that sets them (I have manually assigned them values as well, so it isn't the database pull that is the problem):
if ($name != ""){
$_SESSION['name'] = $name;
$_SESSION['id'] = $user_id;
}
I start that page with a session_start();, as I do on all the pages that will be using the session variables.
When I try to call the session variables on another page, they no longer exist, even if that is the page the one that assigns the values redirects to.
This is how I am trying to call the session variables:
$name = $_SESSION['name'];
$user_id = $_SESSION['id'];
why would it be doing this?
EDIT: To help I'm including the rest of my code for that page. The database connection portions work fine, they are identical to what I use eveyrwhere else.
<?php
session_start();
define('DB_SERVER', '<server>');
define('DB_USER','<db>');
define('DB_PASSWORD' , '<password>');
define('DB_NAME' , '<db-name>');
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database');
$stmt = "Select User.user_id, User.name from User where User.username = '" .
$_POST["username"] . "' AND User.password = '" . $_POST["pwd"] . "';";
if(!$result = $conn->query($stmt)){
die('there was an error retrieving the information');
}
$row = $result->fetch_assoc();
$name = $row['name'];
$user_id = $row['user_id'];
$_SESSION["name"] = $name;
$_SESSION["id"] = $user_id;
if ($name != ""){
$conn->close();
?>
<script type="text/javascript">
<!--
window.location = "store.php"
//-->
</script>
<?php
}
else{
?>
<script type="text/javascript">
<!--
window.location = "register.php"
//-->
</script>
<?php
}
?>
There is only two probabilities:
You did not started session before any output.
The $name is already empty or null.
You have to do the following to debug:
echo $name before the if conditional.
error_reporting(E_ALL); or checkout this question: How to get useful error messages in PHP?
As a debugging technique, try setting the session values ON the page that you're trying to call them. For example, set them on the top of the page and then try outputting them somewhere else below on the page and see if that works. If it does, then it's obvious that the variables aren't being set on the previous page(s).
In PHP you must need to start session using session_start() then only you can user session variables.
And also try to debug, Does your if condition satisfied or not. In your case if your if condition does not satisfied then it is not possible your below code will execute.
$_SESSION['name'] = $name;
$_SESSION['id'] = $user_id;
Related
I will describe my problem in two parts (previous problem and current problem).
Previous Problem:
Initially, on page3.php, I wasn't able to retrieve the username using the session variable and hiding //require('../myDBFolder/db.php'); solved the problem and I was able to see the username on that page.
Current Problem:
Since, I have commented out the line //require('../myDBFolder/db.php');, I am not able to access the other variables defined in db.php like $connection variable and hence I am trying to figure out how to make sure I have $connection variable available in page3.php.
A Quick explanation of the working of files is in the following order:
User submits username from page1.html, page2.php does the authorization work with db.php as required file and upon successful authorization, it directs the user to page3.php.
Please consider my files below:
page1.html
<form method="post" action= "page2.php" name="lform">
<span class="style1">User Name :</span>
<input type="text" name="user" size="25">
<input type="submit" value="login">
</form>
db.php
<?php
session_start();
$user = $_POST["user"];
$_SESSION['username']=$user;
$db_server = "localhost";
$db_name = "PracticeDB";
$db_user = $user;
$table_name_data = "collegestudents";
$connection = mysqli_connect($db_server,$db_user,$db_password) or trigger_error("Could Not Connect to the Database : ". mysqli_connect_error(), E_USER_ERROR);
$db = mysqli_select_db($connection , $db_name) or trigger_error("Could Not Select the Database : " . $db_name . ':' .mysqli_error($connection));
?>
page2.php
<?php
session_start();
require('../myDBFolder/db.php');
$user = $_POST["user"];
$_SESSION['username'] = $user;
$sql="SELECT * FROM $table_name_users WHERE username = \"$user\"";
$result=mysqli_query($connection,$sql) or trigger_error("Couldn't Execute Query in page2.php: ". mysqli_error($sql));
$num = mysqli_num_rows($result);
if ($num != 0) {
print "<script>";
print "self.location='page3.php';";
print "</script>";
} else {
echo "<p>you're not authorized";
}
?>
page3.php
<?php
session_start();
//require('../myDBFolder/db.php');
$user = $_SESSION['username'];
$sql = "SELECT * FROM $table_name_data WHERE username = '$user'";
$result = mysqli_query($connection,$sql) or trigger_error("Could Not Execute the Query ! : ". mysqli_error($connection));
?>
Troubleshooting Steps:
1) I have tried to include require('../myDBFolder/db.php'); in page3.php file and it solves the problem of $connection parameter but I don't see username coming onto that page via session for some reason and also by including //require('../myDBFolder/db.php'); in page3.php I will be making db connection twice as I have already done that in page2.php and haven't closed it.
2) Another thing, I was looking at some of the threads discussed before like this one, it seems like storing $connection in a session variable is not a good idea.
Just to point in a direction:
Change this
$user = $_POST["user"];
$_SESSION['username'] = $user;
to
if(isset($_POST["user"])){
$user = $_POST["user"];
$_SESSION['username'] = $user;
}
So, only update the SESSION if POST is given.
By the way, it is not good practise to give each user an db user account.
Your SQL check if a user is in the database, but your connectin also uses this username!? Rething that..
If you only use one db_user you can move the session username setting stuff completly from the db.php and move it to a better place (e.g. session.php).
the error of you dont see the username if you require db.php is :
in your db.php first thing to do is to put the username in the session so when you call it from the page3 you the code put blank in the session
this code
$user = $_POST["user"];
$_SESSION['username'] = $user;
There is two solution for that :
1 - put connection in one file and the session put in the other file
$user = $_POST["user"];
$_SESSION['username'] = $user;
in different file of connection
2 - the second is you put if condition before this code like this
if(!empty($_POST["user"])) {
$user = $_POST["user"];
$_SESSION['username'] = $user;
}
try it .
Even though I have searched and forums I am failing to get a Session Variable to continue to the next page.
Every page has session_start(). Each Header has exit() after it.
If I add a new member the SESSION Variable is fine. But when I log on the SESSION Variable gets lost after login.
Here is the code for the Login Page. Everything works except for the SESSION variable wont parse to the next page. What am I missing? oh and the code is a bit messy a bit like my workstation.
<?php
session_start();
//Connection to DB in the usual way with check to DB
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
//hacking protection in the usual way
$sql = "SELECT * FROM table WHERE `u_password` = '$mypassword' AND `user` = '$myusername' ";
$result = mysqli_query($mdb, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
$ls = "Online";
$datenow = date("Y-m-d H:i:s");
$id = $row['id'];
$usql = "UPDATE addnewmbr SET loggedstatus = '$ls', logindate = '$datenow' WHERE id = '$id'";
if (mysqli_query($mdb, $usql)) {
$_SESSION["user_id"] = $row['id']; //this variable is lost on next page
$_SESSION["user"] = $row['user']; //this variable is lost on next page
$_SESSION["gender"] = $row['gender']; //this variable is lost on next page
if ($_SESSION['gender'] == "man") {
header('Location: newpage.php');
exit(); // the redirection $_SESSION['gender'] works so the variable is set
} else {
header('Location: anotherpage.php');
exit();
}
} else {
header('Location: back to indexpage.html');
exit();
}
?>
anotherpage.php
<?php
session_start();
echo $_SESSION["user"];
?>
result on this page after Vardump on test page
array(0) { }
Apart from you being vulnerable for SQL injections (preventable by preparing your statements, binding your values and executing it)
Why do you set $_SESSION["user"] equal to $row['user'] and not to $myusername?
In this case, they are the same since you fetch the row where user = $myusername
Not sure if that solves anything.
It was an easy fix after all.... For all that get stuck with SESSION variables being lost!
on the header just be careful..... remove the www from the header
e.g.
SESSION problem
header('Location: http://www.website.php');
SESSION fix
header('Location: http://website.php');
That's all there is to it.
I have got this strange problem. I wanted to make a page which uses a Username to identify which content should be displayed. It seems to work fine, except for one thing. The wrong value is read from the session on one specific page. I have checked the session value in my browser, but there the value seems to be correct. I'll show you the code:
this is my login function, using php:
<?php
//CONNECT TO DATABASE
$db = mysqli_connect("localhost","root","MyPassword","MyDBName");
if($db->connect_errno){
die('connection error: ' . $db->connect_errno);
}
//CHECK IF LOGIN DATA IS SUBMITTED AND IS CORRECT
if(isset($_POST['action'])){
switch($_POST['action']){
case "login":
$pw = $_POST['pw'];
$loginUn = $db->real_escape_string($_POST['loginUn']);
$result = mysqli_query($db,"SELECT `Password` FROM `accounts` WHERE `Username`='" .$loginUn. "'");
if(mysqli_num_rows($result) != 0){
$dbpw = $result->fetch_object();
$VI = explode("-",$dbpw->Password);
$dbpw = openssl_decrypt($VI[1],"blowfish","",0,$VI[0]);
if($pw == $dbpw){
$login = true;
$_SESSION['login'] = true;
$_SESSION['Username'] = $_POST['loginUn'];
$un = $_POST['loginUn'];
}
}
break;
case "logout":
$_SESSION['login'] = false;
$_SESSION['Username'] = "";
break;
}
}else{
if(isset($_SESSION['login'])){
$login = $_SESSION['login'];
$un = $_SESSION['Username'];
}
}
?>
it seems to work fine, since it works in the page it is used.
I have made some dummy accounts in the database, with these usernames: Admin and User.
Here is the code of the page it went wrong:
PHP:
//THIS IS NOT THE SAME PAGE AS THE PREVIOUS PHP CODE
$login = false; //CHECK IF USER HAS LOGGED IN
$un = "";
if(isset($_SESSION['login'])){
$login = $_SESSION['login']; //IF LOGGED IN SET TO SESSION VALUE
$un = $_SESSION['Username']; //SET $UN TO USERNAME IN SESSION
}
Then I used javascript and php to alert the values which the variables contain:
<script type="text/javascript">
alert("$un = <?php echo $un;?>");
</script>
With the login variable seemed to be no problem, since it had the good value, but the variable $un was wrong. When I wasn't logged in, it had no value, which is correct, but when I was logged in, it contained the value Admin, even when I wasn't logged in with Admin. In the browser options the cookie value seemed correct. I've checked the cookie on every page, and it worked just fine, just not on this page. What am I doing wrong that makes the browser(which is firefox by the way) think that it is always Admin that is logged in?
As mentioned earlier in the comments, there are many security risks in your script.
You should take a look at PHP's sessions to build your login. Using sessions, there will be only one cookie storing an ID and all the data will be stored on your server and can't be modified by the user.
Your problem with 'Admin' staying as cookie value could be a caching problem.
I just found out what I did wrong. A piece of code which I found irrelevant, missed a = so the variable wasn't compared, but set to this wrong value.
I've tried looking for information on what I'm trying to do, but the results are not what I'm need to get done. I'm pretty sure there's an answer out there to my issue, but I have no idea how search for it with the correct wording. Anyways what I'm trying to do is: Here I have created a session variable
<?php
// Session started
session_start();
// Connecting to the database
$host = "localhost";
$username = "username";
$password = "password";
$db_name = "potholio";
$tbl_name = "userTbl";
$conn = mysql_connect( $host, $username, $password );
if (! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db( $db_name );
// Submitting query and retrieving result)
$myusername = $_GET['myusername'];
$mypassword = $_GET['mypassword'];
$sql = "SELECT * FROM $tbl_name WHERE usrName='". $myusername ."' and pwd='". $mypassword ."'";
$result = mysql_query( $sql );
// Checking results
$count = mysql_num_rows( $result );
// Directing user based on result
if ( $count == 1 )
{
Now down below is where I have actually set the session variable that I want to access later on.
$userID = mysql_fetch_assoc( $result );
$_SESSION['user'] = $userID['msgID'];
header('Location: http://potholio.csproject.org/map.html');
}
else
{
echo "<script>alert('Incorrect username or password');</script>";
header('Location: http://potholio.csproject.org/');
}
// Close Database Connection
mysql_close();
?>
Now what I'm trying to access that session variable that I have set in a different file called map.html using the following code:
<?php
// Initiate session
session_start();
// Store session data
echo $_SESSION['user'];
?>
The issue is that when I echo to see whether it was being set, the echo actually doesn't return anything, so I'm not sure what's going one since I know the variable is getting set in the other file, which is login.php. Any help with this probably would be great. I'm a complete beginner with Sessions and Session variables.
You are connecting in localhost , but your header redirect is header('Location: http://potholio.csproject.org/map.html');
It seems you are redirect to map.html from a different remote host, so how do you expect it keeps your localhost session?
Okay so I just figured out what my issue was. I found out that all the code I had was indeed correct and there was not any issues with what I had, except for how I was redirecting pages.
Thanks #Robert Rozas.
My problem was actually a really dumb and easy fix that I over looked. The PHP script on my map.html file was never being executed, because it was an HTML file and not a PHP file. Once I realized that and renamed the file so it had a .php file extension everything ran correctly. Sorry for the trouble guys, I should have seen that.
use var_dump($_SESSION['user']) instead of echo $_SESSION['user'] for better detailed output.
i have created a session after my login page and wanted to redirect to a secure page with session i created earlier.. but my session data is not pass.. may i know wat is the problem..
php session:
$em = $_POST['email'];
$pw = $_POST['password'];
$em = mysql_real_escape_string($em);
$pw = mysql_real_escape_string($pw);
$query = "SELECT * FROM Register WHERE email = '$em' AND pass = '$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
if (mysql_num_rows($result) > 0) {
session_start();
// store session data
$_SESSION['login']=$em;
//echo 'Connected';
// Jump to secured page
echo "<script>window.location='http://example.com/secure.php'</script>";
}
the page i redirected to:
<?php session_start(); $_SESSION['login']; ?>
<p>Welcome
<?php
//retrieve session data
echo $_SESSION['login'];
?>
to M-Cloud</b>
Firstly.
Make sure that the session_start is at the top of the pages. That is the best practice.
Make sure the $em has a value when the SESSION is being set.
Check that the web hosting you use supports SESSIONS.
And at the top of the second page, you don't need to have the $_SESSION['login']; bit
To test that $em definitely has a value. echo it out on that page to check.
If this does not work, please paste more of the code so we can find the problem.
You can remove the first $_SESSION['login']; on the second page, then show the whole $_SESSION array with print_r($_SESSION); to see if the value is correct or not.