Session doesn't save when headering to another page - php

I've got a 'shoppingcart' page and if they modify any values there and then click on 'order' i want the session to actually store the information before i header to the next page, however it seems that the $_SESSION variable does not save it before starting.
I have tried the following:
Solution 1:
$_SESSION['winkelwagen'] = $winkelwagen;
session_write_close();
header("Location: checkout.php");
Solution 2:
$_SESSION['winkelwagen'] = $winkelwagen;
header("Location: checkout.php");
exit();
However, neither of these seem to work for me, i have tried looking at the following stackoverflow topics too:
PHP: session isn't saving before header redirect
Header Not Working With Sessions
however neither of these work, this is my code:
$header = false;
if(isset($_POST['moveForward'])) {
foreach($winkelwagen as $key => $val) {
if (isset($_POST['aantal' . $val['artnr']])) {
if (isset($_POST['verpakking' . $val['artnr']])) {
$verpakking = $_POST['verpakking' . $val['artnr']];
$aantal = intval($_POST['aantal' . $val['artnr']]);
if ($val['amount'] !== $aantal) {
$val['amount'] = $aantal;
$winkelwagen[$key]['amount'] = $aantal;
}
if ($val['verpakking'] !== $verpakking) {
$val['verpakking'] = $verpakking;
$winkelwagen[$key]['verpakking'] = $verpakking;
}
$header = true;
}
}
}
$_SESSION['winkelwagen'] = $winkelwagen;
session_write_close();
if($header) {
header("Location: checkout.php");
exit();
}
}
Any help would be appreciated!

Related

Cannot Redirect Using $_SERVER Variables, PHP

I have a PHP application (a request form) that first checks for an active $_SESSION before a user can access the site. Because of the timeout period set for this form there is rarely an active session. Here's the check:
if (isset($_SESSION['samlUserdata'])) {
$attributes = $_SESSION['samlUserdata'];
$user_department = $attributes['department'];
$user_email = $attributes['email'];
$user_employee_id = $attributes['employee_id'];
$user_full_name = $attributes['full_name'];
}
...and here is the else {} that I use to grab the REQUEST_URI:
else {
if (isset($_SERVER['REQUEST_URI'])) {
$referer = $_SERVER['REQUEST_URI'];
$redirect = "https://myinternalwebsite.net$referer";
}
header("Location: https://myinternalwebiste.net/confirm_auth.php?sso");
}
...and last, here is what I do with the $_GET
if (isset($_GET['sso'])) {
if (isset($redirect)) {
$auth->login($redirect);
} else {
$auth->login("https://myinternalwebsite.net/");
}
}
However, once my session is killed I am never properly routed back to the URL set in the ['REQUEST_URI'], I am always just dumped onto the internal site's front page. I have troubleshooted this on and off for some time over the last week, to no avail. I've tried other variables in the $_SERVER array as well, such as ['REDIRECT_URL'].
I'm at a loss, and I'm sure this fairly simple for anyone with more experience than myself... so I am all ears and eager to learn.
EDIT:
Thank you for the comments below. Per your advice I will add the entirety of my code here, removing only the unnecessary parts. (And yes, I appreciate the tip to flip the initial (isset()) to (!isset(). Thank you for that.)
<?php
session_start();
$auth = new OneLogin\Saml2\Auth($saml_settings);
if (isset($_SESSION['samlUserdata'])) {
$attributes = $_SESSION['samlUserdata'];
$user_department = $attributes['department'];
$user_email = $attributes['email'];
$user_employee_id = $attributes['employee_id'];
$user_full_name = $attributes['full_name'];
} else {
if (isset($_SERVER['REQUEST_URI'])) {
$referer = $_SERVER['REQUEST_URI'];
$redirect = "https://example.net$referer";
}
header("Location: https://example.net/confirm_auth.php?sso");
}
if (isset($_GET['sso'])) {
if (isset($redirect)) {
$auth->login($redirect);
} else {
$auth->login("https://example.net/");
}
} else if (isset($_GET['slo'])) {
$auth->logout();
} else if (isset($_GET['acs'])) {
$auth->processResponse();
$errors = $auth->getErrors();
if (!empty($errors)) {
echo '<p>', implode(', ', $errors), '</p>';
}
if (!$auth->isAuthenticated()) {
echo "<p>Not authenticated!</p>";
exit();
}
$_SESSION['samlUserdata'] = $auth->getAttributes();
if (isset($_POST['RelayState']) &&
OneLogin\Saml2\Utils::getSelfURL() != $_POST['RelayState']) {
$auth->redirectTo($_POST['RelayState']);
}
} else if (isset($_GET['sls'])) {
$auth->processSLO();
$errors = $auth->getErrors();
if (empty($errors)) {
echo '<p>Sucessfully logged out!</p>';
} else {
echo '<p>', implode(', ', $errors), '</p>';
}
}
?>

Two redirects after each other in PHP

I have a form on frontend page that after submiting should redirect to a page that API returns but I must redirect first to a thank you page and then after some seconds should redirect to the page that the API returns.
this is so far what I have tried but it only waits for the second refresh.
if(isset($result_array['status']) && $result_array['status'] == true)
{
$autologin_url = $result_array['data'] . PHP_EOL;
$signup_result = true;
header("refresh: 5; url = fakeurl.com/thanks.php");
header("refresh: 15; url = $autologin_url");
}
else
{
echo $result;
$signup_result = false;
header('location: fakeurl.com/?report=signup_error');
}
This is what brombeer meant by the redirect:
if(isset($result_array['status']) && $result_array['status'] == true)
{
$autologin_url = $result_array['data'] . PHP_EOL;
$signup_result = true;
header("refresh: 5; url = fakeurl.com/thanks.php");
}
else
{
echo $result;
$signup_result = false;
header('location: fakeurl.com/?report=signup_error');
}
And Paste this in your thanks.php Script:
header("refresh: 15; url = $autologin_url");

How can I redirect without infinite loop in PHP code?

I have two WordPress sites using the multi-site function, the URLs are below:
A: sample.com
B: sample.com/en
I tried to write a code in PHP following these conditions, but when I access the RUL of A:sample.com, a browser(chrome) shows an error.
So would you mind telling me how should I solve this problem?
Thank you in advance.
the conditions for access
The first access is only to [A: sample.com]
Users whose browser language is set to Japanese access to [A:
sample.com]
All users whose browser language setting is not set to Japanese
access [B: sample.com/en]
The errors messages in the browser(chrome)
This page isn’t working
sample.com redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
The code for adding in functions.php
<?php
$uri = $_SERVER['REQUEST_URI'];
$BASE_LANG = 'en';
if (!preg_match('/^[!-~][a-zA-Z]{2}[!-~]/', $uri)) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$lang = $BASE_LANG;
if (isset($languages)) {
$browser_lamguage = $languages[0];
$base_languages = array('ja', 'en');
foreach ($base_languages as $base_language) {
if (preg_match("/^$base_language/i", $browser_lamguage)) {
$lang = $base_language;
break;
}
}
}
$url = get_site_url()."/$lang/";
if ($lang == 'ja') {
$url = get_site_url();
}
header("Location: $url");
exit();
}
?>
Development environment
CentOS (7 x86_64)
Apache (2.4.6 CentOS)
PHP (7.1.33)
wordpress(5.2.5)
Just make below change in your code:
if ($lang != 'ja') {
header("Location: $url");
exit();
}
Edited:
$uri = $_SERVER['REQUEST_URI'];
$BASE_LANG = 'en';
if (!preg_match('/^[!-~][a-zA-Z]{2}[!-~]/', $uri)) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$lang = $BASE_LANG;
if (isset($languages)) {
$browser_lamguage = $languages[0];
$base_languages = array('ja', 'en');
foreach ($base_languages as $base_language) {
if (preg_match("/^$base_language/i", $browser_lamguage)) {
$lang = $base_language;
break;
}
}
}
$url = get_site_url()."/$lang/";
if ($lang != 'ja') {
header("Location: $url");
exit();
}
}

Using PHP function for shortening repeating code

My code in PHP is pretty long and I want to make it shorter with creating one function with different values and than I would just write one line with function name instead of many lines of code, but it doesn't seem to work.
This is that repeating code:
if (!isset($_POST['ID_user']) || empty($_POST['ID_user'])) {
$_SESSION['ID_user_missing'] = "error";
header("location: index.php");
} else {
$ID_user = $_POST['ID_user'];
}
if (!isset($_POST['meta_name']) || empty($_POST['meta_name'])) {
$_SESSION['meta_name_missing'] = "error";
header("location: index.php");
} else {
$meta_name = $_POST['ID_user'];
}
if (!isset($_POST['meta_value']) || empty($_POST['meta_value'])) {
$_SESSION['meta_value_missing'] = "error";
header("location: index.php");
} else {
$meta_value = $_POST['meta_value'];
}
And this was the plan, instead of that code up ther, I would just have this down below:
function ifIssetPost($value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
} else {
$$value = $_POST[$value];
}
}
ifIssetPost('ID_user');
ifIssetPost('meta_name');
ifIssetPost('meta_value');
But it just doesn't work, when you try to echo for example variable $meta_name it shows that it's empty. Can you help me ? Thank you very much.
NOTE: when I doesn't that function and do it the long way, everything works just fine, but the problem comes when I use that function.
The variable is in the scope of function. That's why you cannot access to it outside the function. You could return the value:
function ifIssetPost($value) {
if (empty($_POST[$value])) { // Only empty is needed (as pointed out by #AbraCadaver)
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
exit; // add exit to stop the execution of the script.
}
return $_POST[$value]; // return value
}
$ID_user = ifIssetPost('ID_user');
$meta_name = ifIssetPost('meta_name');
$meta_value = ifIssetPost('meta_value');
You can also follow your specification, using $$value:
function ifIssetPost($value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value.'_chybi'] = "error";
header("location: index.php");
} else {
return $_POST[$value];
}
}
$value = 'ID_user';
$$value = ifIssetPost($value);
echo $ID_user;
$value = 'meta_name';
$$value = ifIssetPost($value);
echo $meta_name;
You can use an array to iterate over the $_POST vars. If you want to declare a variable using a string or another variable containing an string, you need to use {}. like ${$value}
$postValues = ["ID_user", "meta_name", "meta_value"];
foreach ($postValues as $value) {
if (!isset($_POST[$value]) || empty($_POST[$value])) {
$_SESSION[$value."_missing"] = "error";
header("location: index.php");
} else {
${$value} = $_POST[$value];
}
}

PHP function getting confused with a second parameter/argument

At the end of all of my scripts, I run a function closeConnection, i.e.:
closeConnection("success");
function closeConnection($note) {
if ($note === "success") { $append = "?success"; }
if ($note === "blank") { $append = "?blank"; }
mysql_close();
header("Location: index.php" . $append . "");
exit();
}
This runs smoothly.
However, I now want my closeConnection() function to take two arguments, so that I can choose a different page to redirect to. This is how it looks the second time around:
closeConnection("updated", "view");
function closeConnection($note, $header) {
$header = $header; // Not sure if needed, doesn't work with or without.
if ($note === "updated") { $append = "?updated"; }
if ($note === "blank") { $append = "?blank"; }
mysql_close();
header("Location: " . $header . ".php" . $append . "");
exit();
}
Desired result: Redirect to view.php?updated
Actual result: Redirect to .php?blank
In my experience, you are calling closeConnection("updated"); somewhere before the closeConnection("updated", "view"); and you forgot to remove it or something.
Make sure you didn't forget previous commands, and that you are in fact saving the right file.

Categories