Can't access value stored in $_SESSION array in php - php

I am attempting to set a value into the $_SESSION super global in the page set.php
this the snippet :
if (isset($_POST['sales']) && $_POST['sales'] != ""){
$sales = sanitize_input(trim($_POST['sales']));
$_SESSION['nam0'] = $sales;
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'access.php';
header("Location: http://$host$uri/$extra?so=".$sales);
exit();
}
and to access the value stored in $_SESSION['nam0'] in access.php like this:
<?php
/*To check availbality of SOs for given Sales Order Number in so.php*/
// Initialize session
session_start();
$SD_ID = $_SESSION['nam0'];
However, I am hitting the following error:
Notice: Undefined index: nam0 in access.php on line 7
I don't know why. Can someone help me on this? Thanks a lot.

Session are used like this:
<?php
session_start();
echo $_SESSION['key'] ?? 'key not found';
You can always dump the contents of the session array by doing var_dump($_SESSION);.
I'm guessing that you havn't set your index (submitted the form) yet and therefore getting a "Undefined Index".

Related

How to match $_SESSION with if..else?

Here i have an if else that create cookie with name check_CookiesRW and with content randomly generated by rand(1000,999999);. I would love to check if the cookie content randomly generated and stored on $_SESSION would match and echo out Cookie is SET something like this
if(isset($_COOKIE['check_CookiesRW']) && $_COOKIE['check_CookiesRW'] === $_SESSION['cookie_content'])
how can i achieve this without it throwing out error Warning: Undefined variable $_SESSION ??
<?php
if(isset($_COOKIE['check_CookiesRW'])) {
print "<h1>Cookie is SET</h1>";
} else {
$cookie_name = "check_CookiesRW";
$cookie_content = rand(1000,999999);
$_SESSION['cookie_content'] = $cookie_content;
setcookie($cookie_name, $cookie_content, time()+30, "/");
print "<h1>Created Cookie</h1>";
}
?>

PHP-Unable get values from $_SESSION, error msg is Notice: Undefined variable: _SESSION

First let me explain my code.
It comprises of three php files.
inc_fn_header_and_menu.php, contains the HTML and CSS header details
and it initializes the session via session_start();
This is later included in project_status.php] .
In project_status.php] , I have included another file
project_status_app.php which contains a HTML form.
project_status.php:
<?php
include 'inc_fn_header_and_menu.php';
function includeFile($file,$variable) {
$var = $variable;
include($file);
}
if (isset($_GET['id']) && $_GET['id']!="") {
$pid = $_GET['id'];
$_SESSION['pidForApproval'] = $_GET['id'];
$query = 'SELECT * FROM `profile` WHERE pid ='.'\''.$pid.'\'';
$result=mysqli_query($db,$queryToRetrievePP) or die("There are no records to display ... \n".
mysqli_error());
foreach ($result as $row) {
$status = $row['status'];
?>
project_status_app.php
In project_status_app.php I am attempting to retrieve pidForApproval from the $_SESSION array.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include '../../inc/fastlogin.php';
$sql = "UPDATE pp SET customer_purchase_remarks ='{$_POST['remarkstxt']}' WHERE pp.pid='{$_SESSION['pidForApproval']}'";
$result = mysqli_query ( $fastdb, $sql ) ;
if (mysqli_affected_rows($fastdb) != 1) {
$_SESSION['err_cpa_rmks'] = "<p>Error while updating WHERE id='{$_SESSION['pidForApproval']}'</p>";
} else {
$_SESSION['suc_cpa_rmks'] = "<p>Records was updated successfully.</p>";
}
header ("location: project_status.php?id="$_SESSION['pidForApproval']);
exit();
}
?>
When I load project_status.php, project_status_app.php is supposed to display the form. Once the user fills in the form the and the submit button has been pressed, the UPDATE statement is supposed to run and then it is supposed to navigate back to project_status.php?id=FA142. But the update is failing and the when the project_status.php is loaded back, the url looks like this http://localhost/fast/project_status.php?id= . The id is empty. It is supposed to be something like this http://localhost/fast/project_status.php?id=FA142. With the id being populated at the
header ("location: project_status.php?id=".$_SESSION['pidForApproval']);
I suspected that my $_SESSION['pidForApproval'] is not being populated in project_status.php but I echoed back $_SESSION['pidForApproval'] in that file itself and I can see it is being populated. Hence, I suspect that the $_SESSION['pidForApproval'] is not being passed to project_status_app.php. I have already attempted to include session_start(); clause in project_status_app.php but that gives an error, stating that the session has already started, in inc_fn_header_and_menu.php. Can someone help me as to why the $_SESSION['pidForApproval'] is not being passed on to the project_status_app.php file. Thank you.

How to pass two value from one page to another in php, passing using session

How to pass two value from one page to another in PHP using session.
$account=$_SESSION["account_no"];
$account1=$_SESSION["account_no"];
Session will be available through out the application (in all pages) until you destroy it.
To set a session,
<?php
session_start();
$_SESSION['variable_name_1'] = "value_1"; // or $_POST['accountno_1'];
$_SESSION['variable_name_2'] = "value_2"; // or $_POST['accountno_2'];
?>
In the other page, to get the values
<?php
session_start();
echo $_SESSION['variable_name_1'];
echo $_SESSION['variable_name_2'];
?>
FILE-1: WHERE YOU NEED TO SAVE THE ACCOUNT TO SESSION
<?php // NOTICE THAT THERE IS NO SPACE BEFORE <?php [THIS IS IMPORTANT!!!]
// FILE-NAME: file_1.php WHERE YOU HAVE TO SET THE SESSION VARIABLE
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
$_SESSION["account_no"] = $account;
FILE-2: WHERE YOU NEED TO GET THE ACCOUNT FROM SESSION
<?php // NOTICE THAT THERE IS NO SPACE BEFORE <?php [THIS IS IMPORTANT!!!]
// FILE-NAME: file_2.php WHERE YOU NEED TO READ THE SESSION VARIABLE
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
// READ THE ACCOUNT NUMBER FROM SESSION DATA...
$account = $_SESSION["account_no"];
On the first page:
session_start();
$_SESSION['value1'] = 'First value';
$_SESSION['value2'] = 'Second value';
On the second page:
session_start();
$value1 = $_SESSION['value1'];
$value2 = $_SESSION['value2'];
File:1 where data will be store Session
<?php
session_start(); //before HTML tag
$_SESSION['one'] = $account_no1;
$_SESSION['two'] = $account_no2;
?>
File2: where you like to retrieve session
<?php
session_start();
echo $_SESSION['one'];
echo $_SESSION['two'];
?>
Sessions is a global variable in PHP.
Just create two session variables as use anywhere
<?php
session_start(); // should be at top of page or before any output to browser
$_SESSION['account'] = $account;
$_SESSION['account1'] = $account1;
Now access these session variables anywhere in any page but should start session before use, like:
<?php
session_start();
echo $_SESSION['account'];

Undefined index (hid is not being identified)

On running the following code I'm getting the following error:
Notice: Undefined index: hid in E:\Program Files\xampp\htdocs\cont.php
echo "<table align='right'><tr><td><a href='cont.php?hid=101'><input type='button' value='Account Settings'></a></td></tr></table>";
cont.php code:
$con = mysql_connect("localhost","Rahul","");
mysql_select_db("ebusiness", $con);
if($_SESSION['id']==1)
{
include 'business.php';
}
else if($_GET['hid']==101)
{
session_start();
include 'edprofile.php';
}
You are directly checking on $_GET['hid'] without checking if it is set or not.
else if(isset($_GET['hid']) && $_GET['hid'] == 101)
Try this code :
added : $hid = isset($_GET['hid'])?$_GET['hid']:"";
edited : $_GET['hid'] to else if($hid==101)
$con = mysql_connect("localhost","Rahul","");
mysql_select_db("ebusiness", $con);
$hid = isset($_GET['hid'])?$_GET['hid']:"";
if($_SESSION['id']==1)
{
include 'business.php';
}
else if($hid==101)
{
session_start();
include 'edprofile.php';
}
Change this line:
else if($_GET['hid']==101)
to:
else if(isset($_GET['hid']) && $_GET['hid']==101)
Remember that when you are using GET or POST on your page, there is no guarantee that a certain variable has been sent, as the HTTP protocol is stateless by default.
It is there for important to checn that a variable exists, and also that the variable is validated. To this end the isset() method is quite useful. I would recommend you do a
isset($_GET['hid'])
in your code in an if statement.
you are also missing to pass hid variable in you get request ( in URL). check it out. It shuld content ?hid=101 or &hid=101 some where.
and replace your else if condition with
else if(isset($_GET['hid']) && $_GET['hid']==101)

PHP session variables not carrying over

I have a controller/controller.php file that starts a session and sets some session variables. I then 'include' a model/model.php file and call a function to load it.
When I try and use the session variables from the controller.php file in the model.php file, I am getting many: Undefined variable: _SESSION errors.
Here is an example of setting a session variable in the controller.php file:
$_SESSION['userName'] = 'some data'
In the model.php file I am trying to retrieve it by this code:
print($_SESSION['userName']);
What am I doing wrong?
EDIT
my controller.php file code:
<?PHP
session_start();
if (isset($_POST['Login'])) {
$_SESSION['pointsForQuestion'] = '1';
$_SESSION['userName'] = $_POST['txtUsername'];
if(!is_file($_SESSION['userName'].".txt"))
{
writeUserDetails($_SESSION['userName'],"1","0");
$_SESSION['currentLevel'] = "1";
$_SESSION['score'] = "0";
} else {
readUserDetails($_SESSION['userName']);
}
print('logged in');
include('../model/model.php');
print page_load();
}
function writeUserDetails($username,$level,$score) {
$fh = fopen($username.".txt", 'w') or die("can't open file");
fwrite($fh, $level.",".$score);
fclose($fh);
}
function readUserDetails($username) {
$userDetails = explode(',', file_get_contents($username.".txt"));
$_SESSION['currentLevel'] = $userDetails[0];
$_SESSION['score'] = $userDetails[1];
}
?>
Start your session before defining the session variables on top ie session_start();
Edited
You have not set anything for these session variable that's why it is giving that error
$_SESSION['userName'];
$_SESSION['currentLevel'];
$_SESSION['score'];
You can delete these session variables if u dont want to set anything...
$_SESSION is a superglobal available in all scopes.
So, you must have forgotten session_start().

Categories