Skip to content
PHP Logo

What role does the header() function play in maintaining session variables during a language change process in PHP?

When changing the language in a PHP application, session variables need to be maintained to preserve user data across different language versions. The header() function in PHP is used to send a raw HTTP header, which can be utilized to pass session variables during a language change process. By setting the appropriate headers before changing the language, session variables can be retained and accessed in the new language version.

php
<?php
session_start();

// Set session variables
$_SESSION['username'] = 'JohnDoe';
$_SESSION['language'] = 'english';

// Change language
$_SESSION['language'] = 'spanish';

// Send headers to maintain session variables
header("Location: ".$_SERVER['REQUEST_URI']);
exit();
?>