PHP session lost after redirect
First, carry out these usual checks:
- Make sure
session_start();
is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening<?php
declaration before anything else. Also ensure there are no whitespaces/tabs before the opening<?php
declaration. - After the
header
redirect, end the current script usingexit();
(Others have also suggestedsession_write_close();
andsession_regenerate_id(true)
, you can try those as well, but I'd useexit();
) - Make sure cookies are enabled in the browser you are using to test it on.
- Ensure
register_globals
is off, you can check this on thephp.ini
file and also usingphpinfo()
. Refer to this as to how to turn it off. - Make sure you didn't delete or empty the session
- Make sure the key in your
$_SESSION
superglobal array is not overwritten anywhere - Make sure you redirect to the same domain. So redirecting from a
www.yourdomain.com
toyourdomain.com
doesn't carry the session forward. - Make sure your file extension is
.php
(it happens!)
Now, these are the most common mistakes, but if they didn't do the trick, the problem is most likely to do with your hosting company. If everything works on localhost
but not on your remote/testing server, then this is most likely the culprit. So check the knowledge base of your hosting provider (also try their forums etc). For companies like FatCow and iPage, they require you to specify session_save_path
. So like this:
session_save_path('"your home directory path"/cgi-bin/tmp');
session_start();
(replace "your home directory path" with your actual home directory path. This is usually within your control panel (or equivalent), but you can also create a test.php
file on your root directory and type:
<?php echo $_SERVER['SCRIPT_FILENAME']; ?>
The bit before 'test.php' is your home directory path. And of course, make sure that the folder actually exists within your root directory. (Some programs do not upload empty folders when synchronizing)
Laravel 7 session values not retained after redirect
I have checked your scenario and make the same thing on my laptop. The session is working fine.
Here is my implementation.
env file
BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync
Middleware
namespace App\Http\Middleware;
use Closure;
use Session;
class Locale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
dump(Session::all()); // I can see the login info here, not the locale
if (Session::has('locale')) {
\App::setLocale(Session::get('locale'));
}
return $next($request);
}
}
Kernel.php
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\Locale::class,
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
...
];
Routes
Route::get('/', function () {
return view('welcome');
});
Route::get('set-locale/{locale}', function ($locale) {
if (!in_array($locale, ['en', 'nl'])) {
// todo: return with flash
}
\Illuminate\Support\Facades\Session::put('locale', $locale);
// the session is set here
return back();
})->name('set-locale');
When I open the URL the first time it shows me the following result.
but when I open URL
set-locale/en
then the "en" is set on the session and further request gives me the following output.
Note:- You may need to clear the content of the session folder "\storage\framework\sessions" to clear the sessions things.
PHP Session Variables Not Working After Redirect
You should learn more about sessions to avoid making mistakes and not leaving your codes vulnerable!
Know that to work with sessions, you must start them right at the beginning of each script
Also, after you create your session, you don't need to use the 'echo' command and right after redirecting to the success page, in fact, it is on the success page that you should work with the 'echo' command, and create some variables to store the value of those sessions, to make it easier to work with, and to make the code cleaner!
Please try it:
Signin
<?php
session_start();
//Start the session in the top of the script
if (password_verify($rawpassword, $row["passwordHash"])) {
$_SESSION["email"] = $email;
$_SESSION["fname"] = $row["firstName"];
header("Location: home.php");
exit();
} else {
header("Location: signin.php?addlComment=3True");
exit();
}
Home
<?php
session_start();
session_regenerate_id(true); //It can help you to protect against attacks, try to learn it!
$email = $_SESSION['email'];
$first_name = $_SESSION['fname'];
//If the user try to access the page without make login, then redirect to the signin page
if(!email || !first_name)
{
header("Location: signin.php");
exit();
}
//Test the sessions variables
echo "Welcome, you're logged in! I know your first name is: {$first_name}";
Why is session variable not being saved after redirect in Chrome only?
The problem was due to multiple requests of the same page by Chrome. No other browser does this the same way so the issue only shows up for Google Chrome.
Related Topics
Display Only the Current User'S Details Using PHP and MySQL
Unset a Value in a Multi-Dimensional Array Based on One of the Values
[Php][Mysql] How to Insert Data in 2 Tables At Same Time
Regex Optionally Match a Pattern Multiple Times
Regex for Only Allowing Letters, Numbers, Space, Commas, Periods
Laravel Eloquent How to Get the Minimum Value That Is Not Null
Stop Inserting Data in the Database When Refreshing the Page
Strip Null Values of Json Object
How to Update Stock Quantity Using MySQL in PHP
How to Fetch Data After Selecting from Dropdown List
Open Modal from Another Page Laravel
PHP Parse/Syntax Errors; and How to Solve Them
How to Sanitize User Input With PHP
Pass a PHP String to a JavaScript Variable (And Escape Newlines)
Invalid Argument Supplied For Foreach()