# Using PHP sessions

> Use PHP sessions to keep visitor data between page loads for logins and shopping carts, and keep them secure.

Source: https://helpcenter.ruachost.com/developers/php/using-php-sessions/

**PHP sessions** allow you to store and manage information about visitors as they navigate your website. Since HTTP is a stateless protocol, sessions provide a way to maintain data across multiple page requests. On **ruachost.com**, sessions are supported by default and can be used to build shopping carts, login systems, and other dynamic applications.

## What Are PHP Sessions?

- HTTP does not remember users between page loads.
- Sessions solve this by assigning each visitor a **unique session identifier**.
- Data is stored on the server and linked to the visitor’s session ID.
- Common use cases: shopping carts, authentication, hit counters, and user preferences.

## Starting a Session

To begin a session, use the `session_start()` function at the top of your PHP script:

```
<?php
session_start();
?>
```

- Must be called **before any HTML output**.
- Generates a session ID and creates a file in the server’s session storage directory (default: `/tmp`).

## Working with Session Variables

Session data is stored in the `$_SESSION` superglobal array:

```
<?php
session_start();
$_SESSION['username'] = "timothy";
echo "Welcome, " . $_SESSION['username'];
?>
```

- Values persist across multiple pages until the session ends.
- You can store strings, numbers, arrays, or objects.

## Ending a Session

To destroy a session and clear its data:

```
<?php
session_start();
session_destroy();
?>
```

- Useful for logout functionality.
- Removes all session variables and deletes the session file.

## Configuring Sessions in php.ini

You can adjust session behavior in the `php.ini` configuration file:

- `session.cookie_lifetime` → controls how long a session cookie remains valid.
- `session.auto_start` → automatically starts sessions without calling `session_start()`.
- `session.save_path` → specifies where session files are stored.

## Security Considerations

- Protect against **session hijacking** and **fixation attacks**.
- Use HTTPS to encrypt session cookies.
- Regenerate session IDs after login for added security.
