Why my SESSION varis empty when I call another PHP file? [duplicate] - php

I've got a login system set up, and there are no problems with staying logged in. Both userid and username are stored as session variables (and stored in a table in the database), and I can access them for use within the html on the pages themselves just fine.
I have a form with several multiple choice questions. Any answers I put in the form are stored in the database correctly, no problems there. But when I try to put the username or id into the table, it doesn't work.
The username is displayed on survey.php (the page with the form on it) in the html, like so:
<h2><?php
echo $_SESSION['userName'];
?></h2>
Before I submit the form, the username is displayed correctly. After submitting the form, the same page reloads and the username is still displayed correctly. I'm not being logged out. $_SESSION['userName'] is not being reset and it's not empty.
The code below works perfectly as is, but if I replace
$locationMC = $_POST['locationMC'];
with
$locationMC = $_SESSION['userName']; # (the commented out line in the code below)
it redirects me to /survey.php?error=emptyfields, so $locationMC isn't being set when I try to use the session variable.
The users table and testingtable are in the same database. UserID is set as the primary key, but userName isn't indexed.
Something tells me I'm missing something super basic here -- I'm really new to this -- but after hours of searching on google, I can't figure out what the problem is. Thanks for any help!
<?php
if (isset($_POST['submit'])) {
require 'dbh.inc.php';
$locationMC = $_POST['locationMC'];
# $locationMC = $_SESSION['userName'];
$genderMC = $_POST['genderMC'];
$religionMC = $_POST['religionMC'];
if (empty($locationMC)) {
header("Location: ../survey.php?error=emptyfields");
exit();
}
else {
$sql = "INSERT INTO testingtable (locationMC, genderMC, religionMC) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../survey.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "sss", $locationMC, $genderMC, $religionMC);
mysqli_stmt_execute($stmt);
header("Location: ../survey.php");
exit();
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
header("Location: ../survey.php");
exit();
}
Below is dbh.inc.php. It's the same file that's used when signing up and logging in.
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "testingdb";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}

you need to start request session to read its content
add this code in you top header
if(!isset($_SESSION)) session_start();

Related

How to get user other data when they login in with thier username?

I'm a newbie in programming. I want to ask is there any way I can get user's data from MySQL in another page when they login in only with their username and password. What I'm facing is
I have a login page and main page
I have a user database that include user id, username, password and role_id
When the user login, I can get their username thru $SESSION, but what I really want is their role_id so I can use it as a condition to limit the user. Like Admin can get a header bar that has more button and function.
But when I tried to use sql query, it only shows table instead a single text that I can use. Any idea?
main page.php
<?php
// Initialize the session
session_start();
$user = $_SESSION['username'];
$conn = new mysqli('localhost','root','','mes');
$sql = "SELECT role_id from users where username = $user";
$result = $conn->query($sql);
echo $result;
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
// condition to limit the user
if( (isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] == true) && ($result === '202000') ){
include_once "premierHeader.php";
}
else{
include_once "header.php";
}
?>
WARNING as some people have already pointed out in the comment section, you're wide open to SQL injections (SQLI Attacks). I highly suggest you make use of parametized, prepared statements using either mysqli or PDO.
With that out of the way, I will be using mysqli prepared statements for my answer specifically.
What you need to understand is that when you get the result of your query, you will be given an object. To actually get a value, you will need to fetch(); it.
Example:
<?php
// Initialize the session
session_start();
// Username variable via session
$user = $_SESSION['username'];
// DB variables
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mes";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
// Declare the query
$sql = "SELECT role_id from users where username = ?";
// Prepare and bind
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $user);
// Execute the query
$stmt->execute();
// Bind result variable and fetch value
$stmt->bind_result($role_id);
$stmt->fetch();
// Close connection
$stmt->close();
$conn->close();
// Optionally, you can put the role id into a session variable
$_SESSION["role_id"] = $role_id;
?>

How do I use a $_SESSION['variable'] from one session in another?

I'm making a web app where the user logs in and is able to access the profile and take a quiz. I've got most of it working the only problem is, is that it seems to 'forget' which user is signed in. By this I mean I can't access any of the variables from when the user logs in session.
For example, I have a $_SESSION['username'] = $username; which returns unidentified variable when I try to use the variable $username in a different session or page. Also, I haven't terminated my login session.
Right now I'm trying to store the results of my quiz to a database along with the user's username but it only stores the score and not the username.
Below is my code.
authenticate.php file (This contains the variables regarding usernames)
<?php
session_start();
// Change this to your connection info.
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'phplogin';
// Try and connect using the info above.
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ( mysqli_connect_errno() ) {
// If there is an error with the connection, stop the script and display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data was submitted, isset will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
// Could not get the data that should have been sent.
die ('Username and/or password does not exist!');
}
// Prepare our SQL
if ($stmt = $con->prepare('SELECT username, password FROM users WHERE username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the st_account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($username, $password);
$stmt->fetch();
// st_account exists, now we verify the password.
if (password_verify($_POST['password'], $password)) {
// Verification success! User has loggedin!
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['username'] = $username;
include_once 'homepage.php';
// echo 'Welcome ' . $_SESSION['name'] . '!';
} else {
echo 'Incorrect username and/or password!';
}
} else {
echo 'Incorrect username and/or password!';
}
$stmt->close();
} else {
echo 'Could not prepare statement!';
}
?>
final.php file
<php include "process.php"?>
lines 24 - 44
<main>
<div class="container">
<h2>You are Done!</h2>
<p>Congrats! You have completed the test</p>
<p>Final score: <?php echo $_SESSION['score']; ?></p>
<?php echo $score; ?>
Take Test Again
<?php
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'phplogin';
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
$query = "INSERT INTO `results`(`username`,`score`) VALUES ($username, $score)";
mysqli_query($con, $query);
?>
<?php session_destroy(); ?>
</div>
I don't know if it's necessary to include process.php but I thought it might be helpful to show where the $score variable comes from.
process.php file (this isn't the whole file.)
<?php include 'database.php'; ?>
<?php session_start(); ?>
<?php
//Check to see if score is set_error_handler
if (!isset($_SESSION['score'])){
$_SESSION['score'] = 0;
}
$score = $_SESSION['score'];
}
?>
Sorry if I've made a really simple stupid error, don't hate me, I'm still pretty bad at coding.
Put your session_start(); at the very top of your code, for example, at the very top of your final.php file rather than in your process.php file.
E.g.;
<?php
session_start();
include 'database.php';
?>
A simple solution that you can try
session_start();
We have to add this on the top of php file, or else php throw exceptions like 'headers already sent' or 'can’t start the session' etc.

trying to figure of variable issues in php without using session for mysql database connection

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 .

PHP register form not connecting to database

I have a simple user registration form and external connection script with some strange results.
The page register.php shows the form fine, however seems to display my entire connection string before the form?
It then throws up errors in relation to my connection variable '$dbcon' (I have commented the line at which this happens) Here is my register.php code:
<?php
session_start();
require "connect.php";
if (isset($_SESSION['username'])){
header("location: members.php");
}
if (isset($_POST['submit']))
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
if ($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill all fields";
}
else
{
if ($pass != $rpass)
{
echo "Passwords do not match";
}
else
{
//This is where the errors are found
$query = mysqli_query($dbcon, "SELECT * FROM users WHERE username = '$user' ") or die ("Cannot query table");
$row = mysqli_num_rows($query);
if($row == 1)
{
echo "This username is already taken";
}
else
{
$add = mysqli_query($dbcon, "INSERT INTO users (id, firstname, lastname, username, password, admin) VALUES
(null, '$fname', '$lname', '$user', '$pass', '$admin') ") or die ("Cant insert data");
echo "Successfully added user!";
}
}
}
}
?>
And here is my connection file 'connect.php' (the $dbcon string is the one that prints out??)
$server = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'bodgett';
$dbcon = mysqli_connect($server, $user, $pass, $dbname)or die("Can not connect to Server.");
Specifically, the error is 'Notice: Undefined variable: dbcon in C:\webserver...\register2.php'
Can anyone suggest why is doesn't recognize this variable?
Probably a wrong filename (maybe file isn't called connect.php) OR wrong file extension? (html instead of .php)
I just copied all your code, and it works for me. Aswell I don't see php start and closing Tags.
I agree with #Xatenev. Also, you may want to consider using PDO for your database interactions, it's the most secure way. I found this very helpful: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Sorry if this seems irrelevant, just trying to help.
The connection file 'connect.php' is not enclosed within tags, hence not usable and explains why the text was simply printing out at the top of the page.
Check if mysqli extension is enabled
the code that generates $dbcon is inside a class or inside some function?
If yes, maybe you need to return or call it properly.

PHP MySQLi authentication using if_num_rows not matching database information

I am new to PHP / MySql programming. I have purchased a book to help learn the language and I have done well so far except when I tried to create an authentication system.
I want to be able to match the record to the database using MD5 encryption and if found send to the website. If the username and password are incorrect then send them to the login page again.
At one point it would only match the first record. Now it won't match any. I can type exactly what is in the database and the result still goes to 0 or back to the login page.
Also I am wanting to set a session variable for the username and auth_level so that I can call on it throughout my website/application.
I am using XAMPP on Mac if that helps.
Auth Script:
if ((!isset($_POST['username'])) || (!isset($_POST['password']))) {
header('Location: login.html');
exit;
}
$mysqli = mysqli_connect('localhost', 'username', 'password', 'testDB')
or die(mysql_error($mysqli));
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$password = mysqli_real_escape_string($mysqli, $_POST['password']);
$auth_sql ="SELECT username , auth_level FROM auth_users WHERE
username ='".$username."' AND password =MD5('".$password."')";
$auth_sql_res = mysqli_query($mysqli, $auth_sql) or die(mysqli_error($mysqli));
if (mysqli_num_rows($auth_sql_res) == 1) {
$_SESSION['username'] = $username;
header('Location: homebeta.php');
} else {
header("Location:index.php");
exit;
}
PHP v5.3.1
Thank you everyone that takes the time to look, analyze, and/or help. I really appreciate your time.
You forgot an exit after the first call to header:
header('Location: homebeta.php');
exit;
Are you checking PHP errors? Read How to get useful error messages in PHP? to know more.
I think your script may output something at the beginning, that prevents headers or session information to be sent.
Try this:
if ((!isset($_POST['username'])) || (!isset($_POST['password']))) {
header('Location: http://www.replacethis.com/login.html');
} else {
$mysqli = mysqli_connect('localhost', 'username', 'password', 'testDB')
or die(mysql_error($mysqli));
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$password = mysqli_real_escape_string($mysqli, $_POST['password']);
$auth_sql = "SELECT `username`, `auth_level`
FROM `auth_users`
WHERE `username` = '$username' AND `password` = MD5('$password')";
$auth_sql_res = mysqli_query($mysqli, $auth_sql)
or die(mysqli_error($mysqli));
if (mysqli_num_rows($auth_sql_res) > 0) {
$_SESSION['username'] = $username;
header('Location: http://www.replacethis.com/homebeta.php');
} else {
header("Location: http://www.replacethis.com/index.php");
exit;
}
}
Else statement added.
Backticks in your SQL query (Just to be on the safe side)
Absolute URL in the header location.
And try removing the MD5 hashing from your query and copy n paste both username AND password in your HTML-form and then login.
Well, you may not getting your error messages, since you are using mysql_error instead of mysqli like everything else, and specifically on connect, there is mysqli_connect_error().
Also, according to the manual, inside the parentheses should be void for mysqli_connect_error:
$mysqli = mysqli_connect('localhost', 'username', 'password', 'testDB')
or die(mysqli_connect_error());

Categories