How can PHP be used to handle user input from forms in a flexible and scalable way, especially in the context of a webshop?

When handling user input from forms in a webshop, it is important to use PHP to ensure security, validation, and flexibility. One way to achieve this is by using PHP superglobals like $_POST or $_GET to retrieve form data, sanitizing and validating the input to prevent SQL injection and XSS attacks, and storing the data in a secure way, such as in a database.

// Example PHP code snippet to handle user input from a form in a webshop

// Retrieving form data using $_POST superglobal
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];

// Sanitizing and validating input data
$username = filter_var($username, FILTER_SANITIZE_STRING);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
$password = filter_var($password, FILTER_SANITIZE_STRING);

// Storing the data securely, such as in a database
// Example using PDO to connect to a MySQL database
$dsn = 'mysql:host=localhost;dbname=webshop';
$username = 'username';
$password = 'password';

try {
    $db = new PDO($dsn, $username, $password);
    $query = "INSERT INTO users (username, email, password) VALUES (:username, :email, :password)";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':password', $password);
    $stmt->execute();
    echo "User data stored successfully!";
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}