PHP Sessions Disappearing - php

I come from a classic ASP programming background and boy PHP is really frustrating. What's the deal with PHP Sessions? In Classic ASP you Simply put:
<% Session("Name") = "XYZ" %>
And that Session is always available unless you kill it or it times out. With PHP I get a Session to work from one page to another but when I refresh the page I lose my session. Here is the code I have:
Page: modules.php
// Start the session
session_start();
Page: index.php
include 'modules/modules.php';
$_SESSION['username'] = "MyName";
if (isset($_SESSION['username']) && !empty($_SESSION['username']) {
header('Location: main.php');
}
Page: main.php
include 'modules/modules.php';
echo "My username: ".$_SESSION['username'];
exit();
Now because I gave Session Username a default value it will redirect to main.php and it shows the username fine. But if I refresh the page it disappears. I ran this to see if there was any errors in the modules.php page right below the start session:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
None were returned. But I can't figure out why my PHP Sessions just disappear. I am trying to create a login page where the user will login and his/hers info will be carried along each page so I can have there ID info and to make sure they are logged in. So could someone please tell me what I am doing wrong?
My Modules Page:
// Start the session
session_start();
/* Database Connection Settings */
$_SESSION['servername'] = "localhost";
$_SESSION['mysql_username'] = "xxxxxxx";
$_SESSION['mysql_password'] = "xxxxxxx";
$_SESSION['dbname'] = "mydb";
//Turn on Error Report. True = On / False = Off
ErrorReporting(true);
//Display Error.
function ErrorReporting($ErrOn){
if ($ErrOn == true) {
//Show Error
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
}
}
function db_conn($servername, $mysql_username, $mysql_password, $dbname) {
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
}
/**************************************
Close Database Connection Function.
***************************************/
function db_disconn() {
$conn = null;
}
/***************************************
Employee Login Check:
****************************************/
function CheckLogin($strUserName, $strPassword) {
if (isset($strUserName) && !empty($strUserName) && isset($strPassword) && !empty($strPassword)) {
$conn = new mysqli($_SESSION['servername'], $_SESSION['mysql_username'], $_SESSION['mysql_password'], $_SESSION['dbname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname, user_name, password FROM tbl_employees WHERE user_name='$strUserName' AND password='$strPassword' AND account_disabled='';";
$result = $conn->query($sql);
//Check and see if there are records avaiable.
if ($result->num_rows > 0) {
// output data of each row with a loop.
while($row = $result->fetch_assoc()) {
//Store the info into a session variable.
$_SESSION['eid'] = $row["id"];
$_SESSION['firstname'] = $row["firstname"];
$_SESSION['lastname'] = $row["lastname"];
return $_SESSION["eid"];
//break; //Stop the loop process.
}
} else {
//No records found prompt the user.
return "User name or Password was Incorrect! Please try again!";
}
db_disconn(); /*Close db*/
}
}

You're calling $_SESSION as if it were a function - $_SESSION("username") - while it's actually an array.
You should use $_SESSION["username"] to get the variable value.
You should be getting a Fatal error: Can't use function return value in write context ... but you probably did something wrong with turning on error reporting and you're not getting any errors.
The correct working code would look like this:
<?php
session_start();
if (isset($_SESSION["username"]) && !empty($_SESSION["username"])) {
echo "My username: ".$_SESSION["username"];
} else {
echo "Not set";
$_SESSION["username"] = "MyName";
}

Related

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.

how to call a function $_SESSION[usr]->logout() inside <a>

I have a class named User which has a function named logout(). I create an instance of this class in index.php and i pass it's value to $_SESSION[usr] before i call memberspage.php . In memberspage.php i have a link named logout which when clicked i want the logout() function to run and also send the user to index.php. For this purpose i've done something like this.
Log out
I know that -> causes the problem but i don't know how to fix it. thnx for your time.
The following code worked for me
Log out
but there is a problem. If i go to the page(memberspage.php) where the above code is and i press the back arrow (not logout link) the logOut() function will still be used(the session is destroyed and i will have to log in again to access memberpage.php) . I don't get it because i thought that the only way to call the logOut() function was to click on Log out link.
If $_SESSION[usr]->logout() is working for you as you said in your comment. I don't know how.
But here is just for calling a php function inside anchor tag.It's totally depend on your function response.
<?php
function usr(){
return "abc";
}
?>
Log out
First i suggest that you change your use of session you can create a page for example session.php where all your session is place, it can also be the re directory page of your login page.
like this one named login.php
create in your form make action redirect to session.php
i also suggest that all your php codes of login are inside the session.php then make this one.
<?php
session_start();
$host = "localhost";
$uname = "root";
$pass = "";
$db = "mydb;
//database connection
$conn = mysqli_connect($host, $uname, $pass, $db);
mysqli_select_db($conn, $db);
if(!$conn){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
//$username = mysqli_real_escape_string($username);
//$password = mysqli_real_escape_string($password);
$sql = "SELECT * FROM table WHERE username = '" .$username. "' AND password = '".$password."' LIMIT 1";
$res = mysqli_query($conn, $sql);
if(mysqli_num_rows($res) > 0){
if($data = mysqli_fetch_assoc($res))
{
$_SESSION['type'] = $data['type'];
if(isset($_SESSION["login_user"]))
{
if($data['type'] == 'admin'){
header('location: admin.php');
}
else if($data['type'] == 'customer'){
header('location: customerhome.php');
}//header('location: uservalidation.php');
}
}
}
else{
//header('location: #');
echo '<script>';
echo 'alert("Invalid no?")';
echo '</script>';
header('location: logind.php');
}
}
?>
then create another page which is logout.php
put this code inside:
<?php
session_start();
header('location: index.php');
session_destroy();
?>
then save put the a link your page for logout.php
Add file logout.php and put into them your logout implementation:
<?php
header('Content-Type: application/json');
$_SESSION[usr]->logout();
echo json_encode(['message' => 'ok']);
And call this file with AJAX:
<script>
function logout() {
$.ajax({
url: '/logout.php'
}).then(function (res) {
window.location.href = '/';
});
}
</script>
Log out

Login issue with mySQL no database selected

I'm a beginner of PHP coding which I face this problem and I tried to fix it.
I have search through stackoverflow for answers but it stills no good.
This is my Login form.php file
<form name = 'LoginForm' method = 'POST' action = 'verifyUser.php'>
<br />
E-MAIL: <input type = "Textbox" Name = "App_Email"><br><br>
PASSWORD: <input type = "password" Name = "App_Password"><br><br>
<input type = 'Submit' name = 'Login' value = 'Log in'><br><br>
</form>
This form will goes to verifyUser.php and these are codes
include ('DBconnect.php');
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if($username=='' || $pass=='') {
header("Location:login.php?id=Some fields are empty");
}
$result = mysql_query("SELECT * FROM applicant_acct ");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if ($username==$row['App_Email']) {
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.html?id=$username");
} else {
header("Location:login.php?id=username or your password is incorrect. Please try again");
}
}
}
And final DBconnect.php
<?
$dbc = mysql_connect('localhost','root','root') OR die('Wrong Connection!!!!!!!');
mysql_select_db('onlinerecruitment') OR die ('Cannot connect to DB.');
?>
I really have no idea why it shows "Query Failed: No database selected"
I think the problem is in verifyUser.php but have no idea where.
And another thing, after I logged in how can I generate the text "Welcome - "Username"" and provide them the logout button?
Please help.
Thank you.
Generally you may want to research a graphical user interface such as XAMPP or MySQL workbench until you are more comfortable with Database systems.
Here it seems like most of the improvements can be made in you DBConnect.php file. You are beginning and I can appreciate that. Consider something along the following lines that incorporates additional the security of PDO:: static calls.
<?php
public function _dbconnect($hostpath, $database, $username, $password){
try {
$this->conn = new PDO("mysql:host = {$hostpath};
dbname - {$database};
charset = utf8",
$username,
$password);
} else { exit(); }
?>
If this particular code block doesn't help I would highly recommend that you continue by investigating PDO:: calls.
<?php
include ('DBconnect.php');
if(isset($_POST['Login'])){
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if(empty($username) || empty($pass) || ctype_space($username) || ctype_space($pass)){
header("Location:login.php?error=1");
} else {
$result = mysql_query("SELECT * FROM applicant_acct");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.php?id=$username");
} else {
header("Location:login.php?error=0");
}
}
?>
I have a lot to say about your code.
Use isset function . This function check if something was done.
Check your database details again. Maybe you wrote something
wrong (misclick or something)
Use $_GET['error'] to get errors. I set 1 = for empty characters and 0 for 0 match between database and inputs.
Use sessions for after login message. You can also use Session to handle your errors.
EDIT: I recommend you to start to learn MySQLi or PDO.

PHP redirect with header not working

Here is my code:
<?php
$url = $_GET["id"];
$servername = "XXXX";
$username = "XXXX";
$password = "XXXX";
$dbname = "XXX";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM Table WHERE id='".$url."'";
if ($conn->query($sql) === TRUE) {
echo 'Row deleted successfully';
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
header('Location:index.php');
exit;
?>
But header redirect is not working...
Here is the error log:
Strict Standards: header(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EST/-5.0/no DST' instead in /homepages/5/d394578306/htdocs/XXXXX/XXXXXX/delete.php on line 24
Warning: Cannot modify header information - headers already sent by (output started at /homepages/5/d394578306/htdocs/XXXXX/XXXXXX/delete.php:1) in /homepages/5/d394578306/htdocs/XXXXXX/XXXXXX/delete.php on line 24
<?php
Delete the whitespace before the PHP tag - that counts as output and will stop the header() call from working.
You're also doing some echo calls, both of which will also stop the redirect from working as echo will output content/headers to the browser.
It appears to me that the timezone warning of the header causes the output, which in turn makes the function itself not work. Try doing this:
#header('Location:index.php')
The # will suppress error output for that particular function call.
Also, as Bulk correctly pointed out, you should disable your echo calls in lines 17 and 19, or move them below the header method call.
Based on the timezone error, try this:
<?php
date_default_timezone_set("--HERE YOUR TIMEZONE---");
$url = $_GET["id"];
$servername = "XXXX";
$username = "XXXX";
$password = "XXXX";
$dbname = "XXX";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "DELETE FROM Table WHERE id='".$url."'";
if ($conn->query($sql) === TRUE) {
echo 'Row deleted successfully';
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
header('Location:index.php');
exit;
?>
Now replace the "--HERE YOUR TIMEZONE---".
Here you can find the correct timezone for your country: http://php.net/manual/en/timezones.php

Check whether a mysql_connect() failed or not?

Hey i'm trying to find out whether my sql query failed or not. I want it so if it does fail redirect to form page using the code below:
$checkconnection = mysql_connect('localhost', $dbuser, $dbpass)
or die();
if(!$checkconnection)
{
$_SESSION['errormsg'] = "<div style='padding-left: 50px;color:#FF0000'>Cannot connect to specfied database!</div>";
header("Location: install.php");
}else{
echo('Connection Successful!');
}
using that all it says is this:
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'nzcraftn_admin'#'localhost' (using password: YES) in /home/nzcraftn/public_html/phishnet/install/install_submit.php on line 17
Try this one
$checkconnection = #mysql_connect('localhost', $dbuser, $dbpass)
it will hide default error and trigger your own
The return value of mysql_connect being false only indicates failure. If it returns FALSE, the or die() expression will exit the php script. That's the reason why you don't sea any of it's output.
Remove the or die() command, and display the actual error in your if( !$checkconnection ) clause. The reported error can be retrieved using mysql_error().
It's only displaying the warning because your or die() isn't outputting anything (empty parameter list). Try this instead:
<?php
//Start the session
session_start();
//Do the conntection
$checkconnection = #mysql_connect('localhost', $dbuser, $dbpass);
//Check if it's valid
if(!$checkconnection) {
//Add it up to the session, and redirect
$_SESSION['errormsg'] = "<div style='padding-left: 50px;color:#FF0000'>Cannot connect to specfied database!</div>";
session_write_close();
header("Location: install.php");
exit();
} else{
//Yay
echo('Connection Successful!');
}
?>
The answer by genesis just supresses the warning, but still might work
If you want it 'clean' you can try/catch the error:
(directly from the comments on php.net/mysql_connect:
// Assign variables
global $db_connection, $db_server, $db_database, $db_username, $db_password;
$db_server = $server;
$db_database = $database;
$db_username = $username;
$db_password = $password;
// Attempt connection
try
{
// Create connection to MYSQL database
// Fourth true parameter will allow for multiple connections to be made
$db_connection = mysql_connect ($server, $username, $password, true);
mysql_select_db ($database);
if (!$db_connection)
{
throw new Exception('MySQL Connection Database Error: ' . mysql_error());
}
else
{
$CONNECTED = true;
}
}
catch (Exception $e)
{
echo $e->getMessage();
}

Categories