What are the best practices for storing and retrieving data in PHP, especially when dealing with user input and session management?

When storing and retrieving data in PHP, especially when dealing with user input and session management, it is important to sanitize and validate user input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. Additionally, using prepared statements when interacting with a database can help prevent SQL injection attacks. When managing sessions, always regenerate the session ID after a user logs in or performs a sensitive action to prevent session fixation attacks.

// Sanitize and validate user input
$clean_input = filter_var($_POST['user_input'], FILTER_SANITIZE_STRING);

// Using prepared statements to interact with a database
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $clean_input);
$stmt->execute();
$user = $stmt->fetch();

// Regenerate session ID after login
session_regenerate_id(true);