Session variable loses value after redirection - php

I have three files.
File 1: index.php
which redirects to second.php and sends id=$var to second.php.
code:
$var=52013;
window.open('second.php?id=$var','name','width=1000,height=700,scrollbars=yes');
File 2: second.php
In this file I have received $var, when I print it in logs it displays value of $var.
<?php
session_start();
$_SESSION['id'] = $_REQUEST['id'];
$GLOBALS["log"]->fatal("Get id of order = ".$_SESSION['id']);
//Here it redirects to third file for some varification online.
//This condition is true first time when this page is called but after
//redirection from third.php this condition becomes false.So code below
//this if statement will be executed after redirection from third file.
if(condition==true)
{
header("Location: http://third.php");
}
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
//After redirection from third.php i want to write document using value stored
//in session variable which we get at top.($_SESSION['id'])
$val = $_SESSION['id'];
//Write a file
$file_open = fopen("modules/doc/views/document.txt","wb");
$content = $val;
fwrite($file_open,$content);
fclose($file_open);
File 3: Third.php
This file do some varification online and then redirect to second.php in order to write session id in document.txt
So the problem is that when third.php redirects to second.php file the session variable loses its value. I want to write the value of session variable in document.txt after redirection from third.php but at that time $_SESSION['id'] contains nothing.
But the process should be same, I don't want to change it. It's the requirement.
i.e index.php -> second.php -> third.php -> second.php -> write session value.
Thanks

at the begining of the second.php you do this:
session_start();
$_SESSION['id'] = $_REQUEST['id'];
which is clears the session, and puts into $_SESSION['id'] whatever was received in $_REQUEST['id']. That is why you have nothing in $_SESSION['id'] when commint from third.php. Note that when you do this:
window.open('second.php?id=$var' ...
you just send string '$var' in id

Related

Using $_SESSION to carry a php variable from one page to the next?

I created an app to receive and tally votes. I am trying to make the voter's selection carry over to a confirmation page so that I can display the name of the candidate for whom they voted on the confirmation page.
I am trying to use $_SESSION on the variable of the selected candidate from the voter's submission, and then call the variable on the confirmation page, however I continue to get undefined variable error.
voterSubmit.php:
<?php
$selectedCandidate = $_POST['candidateid'];
session_start();
$selection = $_SESSION[$selectedCandidate];
//Redirect to results page
header("Location: views/confirmation.php");
confirmation.php
<?php
session_start();
$_SESSION[$selectedCandidate] = $selection;
include "views/confirmation.php";
confirmation view:
<?php include "../partials/header.php"; ?>
<h1>Thanks For Your Vote!!</h1><br>
//This is where the error occurs (on my selection variable):
<h2>You voted for <?=$selection?>
View Results
<?php include "../partials/footer.php"; ?>
I want the name of the selected candidate to appear on the confirmation page by way of the $selection variable. However, all I receive on the front end is an "undefined variable" error. I also would like to note that instead of using the $selectedCandidate variable in my session, I have also tried grabbing the name directly by just using the name of the radio button selection as such:
$_SESSION['candidateid'] = $selection
I also would like to mention that i have tried the reverse:
on confirmation.php:
session_start();
$selection = $_SESSION[$selectedCandidate];
on voteSubmit.php:
session_start();
$_SESSION[$selectedCandidate] = $selection;
Your using the $_SESSION variable incorrectly.
Try:
voterSubmit.php:
<?php
$selectedCandidate = $_POST['candidateid'];
session_start();
$_SESSION['selectedCandidate'] = $selectedCandidate;
//Redirect to results page
header("Location: views/confirmation.php");
confirmation.php
<?php
session_start();
$selection = $_SESSION['selectedCandidate'];
include "views/confirmation.php";
voterSubmit.php looks ok... but I don't understand why you have include "views/confirmation.php"; in the confirmation.php file.
<?php
session_start();
$_SESSION[$selectedCandidate] = $selection;
include "views/confirmation.php";
Try coding your HTML/PHP this way:
<?php
/* confirmation.php */
session_start();
$_SESSION[$selectedCandidate] = $selection;
require_once("../partials/header.php");
//This is where the error occurs (on my selection variable):
echo <<<_STRT
<h1>Thanks For Your Vote!!</h1><br>
<h2>You voted for $selection</h2>
<p>View Results</p>
_STRT;
require_once("../partials/footer.php");
?>
I essentially eliminated a lot of start/stop code. The start of your PHP recalls the session and variable. Then I go into the HTML portion to provide the results to your site visitor. Give it a shot. Comment on it if it doesn't resolve your issue so we can rethink it.
I think session_start() needs to be the first line after the php tag.
$_SESSION is an array. So you need to assign it values like:
$_SESSION['keyname'] = $value;
voterSubmit.php:
<?php
session_start();
$_SESSION['selectedCandidate'] = $_POST['candidateid'];
//Redirect to results page
header("Location: views/confirmation.php");
confirmation.php
<?php
session_start();
$selection = $_SESSION['selectedCandidate'];
include "views/confirmation.php";
There are 2 issues in your code :
session_start() defined in the wrong place.
Wrong way of assigning value to your session variable.
Answer :
session_start() should be the first thing defined after your php
tag.
Correct way to declare session variables is : $_SESSION["selectedCandidate"] = $selectedCandidate; where, $selectedCandidate is the value to be assigned to your session variable, named selectedCandidate.
You have done 2 mistakes in your code:
1. Session should be defined in starting of page it means you have to define it like this:
<?php
session_start();
//php code goes here.
?>
2.wrong initialization of session variable .you should do it like this:
<?php
$_SESSION['selectedCandidate']=$selectedCandidate;
?>

PHP session not working page by page

I have two different page with below code. I trim whole code because more than 1000 lines and therefore trim what I did.
In the first page I remove session and fill with new array.
firstpage.php
session_start();
unset($_SESSION);
$_SESSION['new'] = 'test';
print_r($_SESSION); // Session Working fine here at the bottom of page.
secondpage.php
session_start();
print_r($_SESSION);
But in second page show empty array()! I don't have any idea why such this happen
First page header:
PHPSESSID e73jddq9fqhaeeav346h724js7 xxx.ttt.com 35B / Session
Second page header:
PHPSESSID e73jddq9fqhaeeav346h724js7 xxx.ttt.com 35B / Session
both is same.
The script works fine on windows PHP but in cpanel(linux base) doesn't work!
Please test this code :
firstpage.php
<?php
session_start();
$_SESSION['name'] = "john doe";
echo $_SESSION['name'];
?>
secondpage.php
<?php
session_start();
echo $_SESSION['name'];
?>

setcookie(); does not set cookies

I have following problem, I am trying to set cookies without any success. setcookie(); function returns true so it looks like it setting cookie however when I am trying to access it on the same or following page I get error 'Undefined Index....'
<?
session_start();
ob_start();
echo setcookie("order",$_SESSION['cart'],time()+3600,'/',NULL);
//added to see if Cookie is set
echo "<br/>";
var_dump($_COOKIE);
exit();
if($_GET['paypal'] == 1){
header("Location: /paypal-express-checkout/process.php");
}else{
header("Location: /insert_order.php");
}
ob_end_flush();
exit();
?>
next page follows like this
<?php
session_start();
include_once("../includes/inc_config.php");
include_once("../order.php");
include_once("config.php");
include_once("paypal.class.php");
#region POST
if(!isset($_GET['token'])) //Post Data received from product list page.
{
//Mainly we need 4 variables from an item, Item Name, Item Price, Item Number and Item Quantity.
if(!isset($_COOKIE['order'])){
exit();
}
$paypal_data = '';
$ItemTotalPrice = 0;
$order = unserialize($_COOKIE['order']);
print_r($order);
exit;
You are setting the domain value to NULL. Try leaving the NULL away:
echo setcookie("order",$_SESSION['cart'],time()+3600,'/');
OR set it to your domain:
echo setcookie("order",$_SESSION['cart'],time()+3600,'/',".yourdomain.com");
I would var_dump or print_r the $_COOKIE variable before I make a decision that it's not getting passed through. Holding that thought once you setcookie something gets registered into the $_COOKIE variable for sure.
I agree with the statements above since you only can access $_COOKIE on the next refresh but there is another way to do it to make your form or page more interactive.
I would register the cookie and use a php page refresh (display a working... div while thats happening) then come back to the page and try to do what you originally tried doing. Very basic but pretty much straight forward.

How do I redirect to referring page/url after successful login?

I'm aware that this topic has been covered before here on Stack, and I have looked at some answers, but I'm still a bit stuck, being fairly new to PHP. Every page on my website requires a login, and so users are redirected to a login page on page load. At the top of each page then I have:
<?
require("log.php");
include_once("config.php");
include_once("functions.php");
?>
This redirects the user to log.php (with new code added):
<?
session_name("MyLogin");
session_start();
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php"; // default page for
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","",""); // your MySQL connection data
$db = mysql_select_db(""); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM users WHERE login='$name'");
if (!$q_user) {
die(mysql_error());
}
if(mysql_num_rows($q_user) == 1) {
$query = mysql_query("SELECT * FROM users WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) {
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/$url"); // success page. put the URL you want
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}
// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}
?>
The login form is contained in login.php. The code for login.pho relevant to the PHP/log.php is:
<?
session_start();
if($_GET['login'] == "failed") {
print $_GET['cause'];
}
?>
and
<form name="login_form" id="form" method="post" action="log.php?action=login">
The answer that I came across stated that I should add:
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
to the top of each page, which I did, at the top of the page (above "require("log.php");"), and then add:
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php"; // default page for
to my login page, and use the following URL for redirect on successful login:
header("Location: http://example.com/$url"); // perform correct redirect.
I am not 100% where the code which stores the referring URL should go, at the top of log.php or login.php.
I have tried adding it to both, but the login page is just looping once I have entered the username and password.
I wonder if someone could help me get this working?
Thanks,
Nick
It appears that I don't have the privilege to comment on your post, so I'll do the best that I can to answer. I apologize for all of the scenarios, I'm just doing the best I can to answer on a whim.
SCENARIO 1:
If you've truly not selected a database in your code, as demonstrated here, could that potentially be your issue? Please do note, that the code below, is the code you've posted.
$db = mysql_select_db(""); //put your database name in here
SCENARIO 2:
The code below is not something I've ever used in anything I've built, might I suggest that you try replacing that line of code with the line below it?
if(session_is_registered("name") == false) { // Current
if(isset($_SESSION['name']) == false) { // Potential Replacement
SCENARIO 3:
If you're logic for the following, exists on the login.php file as well... That could potentially be your problem. Upon visiting your site, I noticed your form appears on login.php, yet your logic is posting to log.php. I'm hoping this bit of code can help rule out that "jump", as login.php might be saving itself and overwriting the $_SESSION variable you've established
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
If it's too complex to take it out of the login.php file, if you even have it there, I've put together some code that you can use to create "internal" breadcrumbs, so you can go 2 pages back in your history.
if(!isset($_SESSION['internal_breadcrumbs']))
$_SESSION['internal_breadcrumbs'] = array();
$_SESSION['internal_breadcrumbs'][] = $_SERVER['REQUEST_URI'];
$max_breadcrumbs = 5;
while(count($_SESSION['internal_breadcrumbs']) > $max_breadcrumbs)
array_shift($_SESSION['internal_breadcrumbs']);
That will create an array with a max of $max_breadcrumbs elements, with your most recent page at the end, like the following
Array
(
[internal_breadcrumbs] => Array
(
[0] => /other_page.php
[1] => /other_page.php
[2] => /other_page.php
[3] => /user_page.php <-- desired page
[4] => /login.php <-- most recent page
)
)
So now... you can setup your url to be something more like the following...
// I'm doing - 2 to accommodate for zero indexing, to get 1 from the current page
if(isset($_SESSION['internal_breadcrumbs']))
$url = $_SESSION['internal_breadcrumbs'][count($_SESSION['internal_breadcrumbs']) - 2];
else
$url = "index.php"; // default page for
All the best, and I certainly hope this has helped in some way.
IN SCENARIO 4
From the client test the login/password which ajax XMLHttpRequest with javascript code to a dedicated script for validation (do it on mode https for secure)
If response is right send the login password to your script server.
Stips : Encoding password is better secure !
Using header() function it's a bad idea.
Manual specification say ;
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
So in your case, i suggest that to use cookies with an ID generate only for the session, at the first connection its generate, and the duration of the cookie maybe for only from 2 to 10 minutes.
Regenerate cookie each time the loging.PHP is called !
Have a nice day

I can't echo session username, am I storing session username and id correctly?

I am setting up a login form.
Expected Result:
Echo session username on page after successful login.
Actual Result:
Login is successful. Session username does not echo. Appears as though session username either does not exist or it is not persisting to the next page.
Is there something wrong with the code below?
LOGIN.PHP
...
session_start();
if (mysql_num_rows($result) ==1)
{
session_regenerate_id();
$row = mysql_fetch_assoc($result);
$profileid = $row['userid'];
$profile = $row['username'];
//Set session
$_SESSION['profileid'] = $profileid;
//Put name in session
$_SESSION['profile'] = $profile;
//Close session writing
session_write_close();
//Redirect to user's page
header("location: index.php?msg=userpage");
exit();
}
...
INDEX.PHP
...
<?php
session_start();
if($_GET['msg']=="userpage")
{
echo $_SESSION['profile'];
}
...
Edited:
Put session_start in php tags.
Changed HTML to INDEX.PHP.
"If" brace closed.
Changed while to if in LOGIN.PHP.
Changed username to userpage
You don't need to be opening/closing sessions, it's not worth the extra lines of code. I also don't know why you're regenerating the session ID.
But, one thing is your HTML file is badly constructed, and it almost looks like the session_start() isn't inside any PHP tags, so it's not even being treated as code.
first of all your HTML is yet PHP as it involves PHP tags only.
Replace while with if coz you only want to set the $_SESSION variables once.
And for the last part what you are looking for is this
<?php
session_start(); //at the beginning of your script
if($_GET['msg']=="username")
{
echo $_SESSION['profile'];
}
?>
Make sure you eliminate all the whitespaces before the opening of your first <?php tag on your script as that gives potential header errors.
close the if loop in html file
EDITED:
I did this simple code in my page and as per session concept is concerened The code is working fine...make corrections accordingly
p1.php
<?php
session_start();
//Put name in session
$_SESSION['profile'] = "Pranav";
//Close session writing
//Redirect to user's page
header("location: p2.php?msg=userpage");
exit();
?>
p2.php
<?php
session_start();
if($_GET['msg']=="userpage")
{
echo $_SESSION['profile'];
}
?>
FOR NEW SESSION ID
USE THIS
$a = session_id();

Categories