Skip to content
PHP Logo

What is the recommended method for creating and registering variables in a PHP session?

To create and register variables in a PHP session, you can use the `$_SESSION` superglobal array. This array allows you to store variables that persist across multiple pages for a single user session. To create a session variable, simply assign a value to a key in the `$_SESSION` array. To register the session, you need to call `session_start()` at the beginning of each PHP page where you want to access or modify session variables.

php
<?php
// Start the session
session_start();

// Create and register a session variable
$_SESSION['username'] = 'JohnDoe';

// Access the session variable on another page
echo $_SESSION['username'];
?>