What are the advantages and disadvantages of using sessions versus global variables in PHP for variable storage?
When deciding between using sessions or global variables for variable storage in PHP, sessions offer the advantage of securely storing data on the server side and allowing data to persist across multiple page loads for a specific user. However, sessions can consume server resources and may not be suitable for storing large amounts of data. Global variables, on the other hand, are easier to use and can be accessed anywhere in the script, but they are not secure and can lead to potential data leakage.
// Using sessions for variable storage
session_start();
$_SESSION['username'] = 'JohnDoe';
echo $_SESSION['username'];
```
```php
// Using global variables for variable storage
$GLOBALS['username'] = 'JohnDoe';
function getUsername() {
global $username;
return $username;
}
echo getUsername();