PHP MySQL Validating user input


Validating user input in PHP MySQL procedural style is an important step to ensure data integrity, prevent errors, and safeguard your application from security threats like SQL injection and cross-site scripting (XSS). Here’s how you can validate user input step-by-step.

Step-by-Step Input Validation

  1. Check if form data is set: Ensure the form is submitted before accessing the data.
  2. Sanitize the input: Remove unwanted or potentially dangerous characters.
  3. Validate specific types of data: Check that the data meets certain criteria (e.g., email format, length, etc.).
  4. Secure the data for SQL insertion: Escape any special characters to avoid SQL injection.
  5. Implement server-side validation: Even if you have client-side validation (e.g., using JavaScript), always validate on the server side as well.

Example: Validating a simple form

Here’s an example showing how to validate and insert data securely in PHP with MySQL procedural style.

1. HTML Form

<form action="insert.php" method="POST">
<label for="name">Name:</label> <input type="text" name="name" id="name" required> <label for="email">Email:</label> <input type="email" name="email" id="email" required> <input type="submit" value="Submit"> </form>

2. PHP Validation and Insertion (insert.php)

<?php
// Check if form is submitted if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Step 1: Validate and sanitize the input data // Trim and sanitize name if (isset($_POST['name']) && !empty($_POST['name'])) { $name = trim($_POST['name']); $name = filter_var($name, FILTER_SANITIZE_STRING); // Remove HTML tags, encode special characters } else { die("Name is required."); } // Validate and sanitize email if (isset($_POST['email']) && !empty($_POST['email'])) { $email = trim($_POST['email']); if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) { die("Invalid email format."); } $email = filter_var($email, FILTER_SANITIZE_EMAIL); // Remove invalid characters } else { die("Email is required."); } // Step 2: Establish connection to MySQL $servername = "localhost"; $username = "root"; $password = ""; $dbname = "test_db"; $conn = mysqli_connect($servername, $username, $password, $dbname); // Check if connection was successful if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Step 3: Escape the data to prevent SQL injection $name = mysqli_real_escape_string($conn, $name); $email = mysqli_real_escape_string($conn, $email); // Step 4: Prepare the SQL query $sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')"; // Step 5: Execute the query and handle errors if (mysqli_query($conn, $sql)) { echo "Record inserted successfully!"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } // Step 6: Close the connection mysqli_close($conn); } ?>

Explanation:

  1. Sanitization:

    • filter_var($name, FILTER_SANITIZE_STRING) removes HTML tags and encodes special characters to prevent XSS attacks.
    • filter_var($email, FILTER_SANITIZE_EMAIL) ensures the email is free from illegal characters.
  2. Validation:

    • filter_var($email, FILTER_VALIDATE_EMAIL) ensures the email format is valid.
  3. Prevent SQL Injection:

    • mysqli_real_escape_string($conn, $name) escapes special characters in the string, preventing SQL injection attacks when the data is inserted into the query.
  4. Handling Errors:

    • If any validation fails, the script stops and outputs an error message (die()).
    • The database connection is also checked and handled with error messages.

Key Validation Functions:

  • filter_var(): Use this for sanitization and validation of different types (e.g., string, email, URL).
  • trim(): Removes any extra spaces before or after the string.
  • mysqli_real_escape_string(): Escapes special characters before inserting data into a MySQL query.

Adding More Validation:

You can add additional validations based on your needs:

  • String Length: Ensure the string length is within your required range.

    if (strlen($name) < 3 || strlen($name) > 50) { die("Name must be between 3 and 50 characters."); }
  • Regular Expressions: For more complex validations (e.g., password strength, specific format requirements).