how to save variables after using header function php - php

After i submit a form and save the info to a database i use the header function to redirect to a more user friendly url but the variable $checkError is not saving, it gets reset after the header redirect. How can i save the variable even if the page gets refreshed?
if(isset($_GET['submit'])){
// get the post records <<
$id = '2';
$title = $_GET['title'];
$link = $_GET['link'];
// database connection
$con = mysqli_connect("localhost", "user", "password", "db_test");
$sql = "INSERT INTO test (id, title, link)
VALUES ($id, '$title', '$link')";
$rs = mysqli_query($con, $sql);
if($rs){
$checkError = '<div class="success">Success!</div>';
}else{
$checkError = '<div class="error">Not working!</div>';
}
mysqli_close($con);
//redirect to user friendly url
header("Location: /index.php?id={$id}");
}

You can write this to session data and recall it later, as one potential solution.
Modify/add in your example code block:
session_start();
if($rs){
$_SESSION['checkData'] = '<div class="success">Success!</div>';
}else{
$_SESSION['checkData'] = '<div class="error">Not working!</div>';
}
header("Location: /index.php?id={$id}");
And back on index.php, you would need to add/modify:
session_start();
if( isset( $_SESSION['checkData'] ) ){ // check whether it's set
echo $_SESSION['checkData']; // output variable
unset( $_SESSION['checkData']; // reset variable
}

You can use $GLOBALS OR $_SESSION as an array for $GLOBALS more details click here
you can use it as the below code in your header file
set value in $GLOBALS
$GLOBALS['checkError'] = '<div class="success">Success!</div>';
get value from $GLOBALS
echo $GLOBALS['checkError'];

Another way, very easy to implement is to skip $checkError variable and redirect user to a specific page:
// ...
$rs = mysqli_query($con, $sql);
mysqli_close($con);
$page = $rs ? 'success' : 'failure';
header("Location: /{$page}.php?id={$id}");

You have to store your data in cookies or sessions before the redirect.
A session is also used to store data, but I suggest you store data in cookies because the session stores data on the server-side, creating performance issues, whereas cookie stores data on the client-side.
You can check the critical difference of Cookie and Session
first.php
<?php
if($rs){
setcookie('checkError', '<div class="success">Success!</div>');
}else{
setcookie('checkError', '<div class="error">Not working!</div>');
}
?>
second.php
<?php
if(!isset($_COOKIE['checkError'])) {
echo $_COOKIE['checkError'];
}
?>
I hope this is helpful to you.

Related

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.

Multiple steps form with sessions security

Hi i'm developing a multi steps form with php using session and i've been wondering if there is a way for the user to alter session variables for example on the first page i have something like this :
<?php
session_start();
if(isset($_POST['submit'])){
$_SESSION['name'] = $_POST['name'];//and so on
}
?>
and the other page has something like :
<?php
session_start();
$name = $_SESSION['name'];
?>
my question is can the user modify the value of the session variable on the second page
Since you're populating the session variable with the value of a POST variable, they can continue to resubmit the first form as much as they want with arbitrary values.
You can use application logic to defeat this:
<?php // form1
session_start();
if (empty($_SESSION['step'])) {
$_SESSION['step'] = 1;
}
if ($_SESSION['step'] > 1) {
header("Location: form2.php");
exit; // This exit is very important, don't neglect it
}
if (isset($_POST['submit'])){
$_SESSION['name'] = $_POST['name'];//and so on
$_SESSION['step'] = 2;
}
And then
<?php // form2
session_start();
if (empty($_SESSION['step'])) {
header("Location: form1.php");
exit;
}
if ($_SESSION['step'] > 2) {
header("Location: form3.php");
exit;
}
if ($_SESSION['step'] < 2) {
header("Location: form1.php");
exit;
}
$name = $_POST['name'];
By using application logic, you can control the flow of your visitors within your application.
If you're asking if users can change $_SESSION variables outside of any code you've written, the answer is usually no. See also: this answer.

how i require session for a function

i have in my sandbox many of function, some of the function are public, and other's i want them to be only for website member's.
this is an example for a function i want it to be for website members only
function get_page ($dbc, $pg) {
// the database connection, our query
$q = "SELECT * FROM pages WHERE name = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
$page = mysqli_fetch_assoc($r);
echo '<div class=entry>';
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content_body">'.$page['body'].'</div>';
echo '</div>';
}
is there any way to do that?
"how i require session for a function"
Use the following, as an example:
if(!isset($_SESSION['session_name'])){ die(); }
and to include session_start(); inside all of the files used, and at the * top.
(* Depending on the condition).
For more information on sessions, visit the following:
http://www.php.net/manual/en/features.sessions.php
Footnotes:
Should you be faced with an headers already sent... error message later on, you can make use of ob_start(); placed above session_start().
For example:
<?php
ob_start();
session_start();
// code
Your question is really not clear.
You can use something like:
// Private function for members
function privateFunction($isMember=false){
if($isMember){
// DO your things
}
else{
callError();
}
}
Or make use of PHP Session variables directly into your function ?

Redirect after executing code

I want this PHP code to redirect to the previous page and refresh automatically...
I understand that with JavaScript I can go history back but it won't refresh.
Please help.
My code:
<?php
$con=mysqli_connect("host","user","pass","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//post result to db
$result_set = mysqli_query($con,"SELECT points FROM total WHERE id = 1");
$row = mysqli_fetch_assoc($result_set);
$old_total = $row['points'];
$new_total = $old_total + $_REQUEST['total'];
mysqli_query($con,"UPDATE total SET points = $new_total WHERE id = 1");
mysqli_close($con);
?>
Get the url in a session, when you want to redirect, just use that url and redirect the user and unset the session var
//Track this on the page you want to redirect your code
$_SESSION['prev_url'] = $_SERVER['REQUEST_URI'];
On the next page use this
//When you want to redirect to previous page
header('Location: '.$_SESSION['prev_url']);
exit;
Be sure you are declaring session_start() at the top of the page
To redirect with php:
<? header("location: http://.........."); ?>
Please note that before this instruction you mustn't print html, if some html is printed your header will not be sent
add
header("Location: " . $_SERVER['HTTP_REFERER']);
exit;
you can use javascript code :
forward: window.history.go(+1)
backward: window.history.go(-1)
or jquery code:
forward: history.go(1);
backward: history.go(-1);

How to pass variables received in GET string through a php header redirect?

I'm receiving values in a GET string from Aweber upon user's submission of a form. I take the variables they send and submit them to a SMS gateway to notify a 3rd party of the submission by text message.
Here's my problem. I need to redirect the page that performs the outgoing SMS commands in a php header to another page that finally displays the GET variables sent from Aweber.
I can retrieve the variables and their values in the first page. How do I pass them to the second page?
Here is the code I'm using on the first page (sms.php) to collect the variables sent by Aweber:
$fname = $_GET['name'];
$femail = $_GET['email'];
$fphone = $_GET['telephone'];
....etc
header('Location: confirmed.php');
exit;
First convert the $_GET HTTP variable into a query string using
$query = http_build_query($_GET);
Then append the query string variable to your redirect header
header('location: domain.com'."?".$query);
Done.
session_start();
$_SESSION['fname'] = $_GET['name'];
$_SESSION['femail'] = $_GET['email'];
$_SESSION['fphone'] = $_GET['telephone'];
....etc
header('Location: confirmed.php');
and get it on the next page like:
session_start();
$fname = $_SESSION['fname'];
$femail = $_SESSION['femail'];
$fphone = $_SESSION['fphone'];
....etc
You don't need to store them in a session, you can easily pass them with your location header:
$fname = $_GET['name'];
$femail = $_GET['email'];
$fphone = $_GET['telephone'];
//now a header with these var's:
header("Location: confirmed.php?name=".$fname."&email=".$femail."&telephone=".$fphone);
In confirmed.php you can get these variables with $_GET method.
Please for anyone reading this in future, use sessions for this kind of variable value transfer because if you rely mostly on adding variable to header then if the user in still on that form and carries out an action that changes the value of the header then your own variable value changes since it depends on the header......simply put, USE SESSIONS.
Store them in the session:
$_SESSION['fname'] = $_GET['name'];
Use session_start at the beginning of each file.
Try this. It worked perfectly for me.
if ($_GET)
{
$query = str_replace("%3D", "=", str_replace("%26", "&", strval(urlencode(http_build_query($_GET)))));
header('location: https://www.example.com'.'?'.$query);
}
else
{
header('location: https://www.example.com');
};
The best you can do is put all your POST variables to a session like this:
On page1.php put:
//Start the session
session_start();
//Dump your POST variables
$_SESSION['post-data'] = $_POST;
And on page2.php put: (If on page1.php we use a normal POST form submit with form action="page2.php")
//Start the session
session_start();
//Access your POST variables
foreach ($_POST as $key => $value) {
${$key} = $value;
$_SESSION[$key] = $value;
}
//Unset the useless session variable
unset($_SESSION['post-data']);
Or on page2.php put: (If on page1.php we use a self submit with form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?> and then use a header("Location: page2.php"); to move to the page2.php and pass our POST variables via a session)
//Start the session
session_start();
//Access your POST variables
$_POST = $_SESSION['post-data'];
foreach ($_POST as $key => $value) {
${$key} = $value;
$_SESSION[$key] = $value;
}
unset($_SESSION['post-data']);
I literally spent hours figuring that out because all the forums put it wrong or incomplete.
Now it's as easy as just calling the variables you passed from the page1.php like this for example: <b>Points: </b><?php echo $points; ?> and that's it!!
When situating the header('Location: page2.php'); in a if condition, etc. make sure that it will be in the first PHP script of the page and above any HTML output.
This works use this sentex
header('location:member_dashboard.php?id='.$id);

Categories