What are some best practices for handling POST variables in PHP, especially in complex CMS systems?

When handling POST variables in PHP, especially in complex CMS systems, it is important to properly sanitize and validate the input data to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. One way to achieve this is by using PHP's filter_input function along with filter_input_array to sanitize and validate the POST variables before using them in your application.

// Sanitize and validate POST variables using filter_input_array
$post_data = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

// Access sanitized POST variables
$username = $post_data['username'];
$email = $post_data['email'];

// Use the sanitized POST variables in your application
// Example: save data to database
$sql = "INSERT INTO users (username, email) VALUES (:username, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':username' => $username, ':email' => $email));