PHP filter_input() Function

filter_input() is a function in PHP used to validate and sanitize user input from external sources, such as form data or query parameters. It helps prevent common security vulnerabilities like SQL injection, XSS (Cross-Site Scripting), and more. This function is especially useful when working with web applications and handling user-submitted data.

Here's the basic syntax of filter_input():

filter_input($type, $variable_name, $filter, $options)

  1. type: The type of input to be filtered. This can be one of the following constants:

    • INPUT_GET: For accessing $_GET variables.
    • INPUT_POST: For accessing $_POST variables.
    • INPUT_COOKIE: For accessing $_COOKIE variables.
    • INPUT_SERVER: For accessing $_SERVER variables.
    • INPUT_ENV: For accessing $_ENV variables.
  2. variable_name: The name of the variable you want to access from the input source (e.g., $_GET['var'], $_POST['var'], etc.).

  3. filter: The ID of the filter you want to apply. This can be a predefined filter like FILTER_SANITIZE_STRING or FILTER_VALIDATE_EMAIL (there are many others), or it can be a custom filter.

  4. options (optional): Additional options that can be passed depending on the chosen filter.

It returns the filtered value on success, or false if the filter fails.

Sanitizing and Validating Input:-

Let's look at some examples using PDO (PHP Data Objects) for database interaction. We'll assume we have a MySQL database and a table called users with columns id, name, and email.

In these examples, we first establish a connection to the database using PDO. Then, we use filter_input() to sanitize and validate user input before using it in database queries. If the input is valid, we proceed with the query. If not, we handle it appropriately.

Remember, the provided examples are basic and do not include additional security measures like prepared statements, password hashing, etc. These should be implemented for production-level code to ensure maximum security.

Using filter_input with PDO:

 
 
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
 
try {
    $db = new PDO($dsn, $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Assuming you're working with a POST request
    $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
    $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    
    if ($name && $email) {
        $stmt = $db->prepare('INSERT INTO users (name, email) VALUES (?, ?)');
        $stmt->execute([
            $name,
            $email
        ]);
        echo 'User added successfully!';
    } else {
        echo 'Invalid input!';
    }
} catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage();
}
 
 

 
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
 
try {
    $db = new PDO($dsn, $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Assuming you're working with a GET request
    $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
    
    if ($id) {
        $stmt = $db->prepare('SELECT * FROM users WHERE id = ?');
        $stmt->execute([
            $id
        ]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user) {
            echo 'User ID: ' . $user['id'] . '';
            echo 'Name: ' . $user['name'] . '';
            echo 'Email: ' . $user['email'] . '';
        } else {
            echo 'User not found!';
        }
    } else {
        echo 'Invalid input!';
    }
} catch (PDOException $e) {
    echo 'Error: ' . $e->getMessage();
}