Skip to content

Importing user input

In PHP, importing or receiving user input typically involves capturing data from form submissions or URL parameters. This can be done using PHP’s superglobal arrays such as $_GET, $_POST, and $_REQUEST. Here’s a step-by-step guide on handling user input in PHP securely and efficiently.

1. Using Forms to Collect User Input

To gather data from a user, you generally create an HTML form with input fields. For example:

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

Here, when the form is submitted, it sends data to process.php using the POST method.

2. Retrieving User Input with PHP Superglobals

Once the form is submitted, PHP can capture this data using the superglobal arrays:

  • $_POST: Used to access data sent via the POST method. This method is often used for sensitive data (e.g., passwords) because it is more secure than GET.
  • $_GET: Used to access data sent via the GET method, which is appended to the URL and can be visible to users. Useful for non-sensitive data, like search queries or page numbers.
  • $_REQUEST: Contains data from both $_GET and $_POST, as well as cookies. It’s a catch-all for input but is less specific, so it’s often better to use $_POST or $_GET directly.

// Accessing user input in process.php if ($_SERVER[“REQUEST_METHOD”] == “POST”) { $name = $_POST[‘name’]; $email = $_POST[’email’]; echo “Name: ” . $name . “<br>”; echo “Email: ” . $email; }

3. Validating User Input

Validation is essential to ensure that the data provided is in the expected format and safe to use.

  • Empty Check: Check if required fields are filled.
  • Data Type Validation: Use specific checks, like filter_var() for emails.
  • Custom Validations: Use regular expressions for specific patterns, like phone numbers.

if (empty($_POST[‘name’])) { echo “Name is required.”; } elseif (!filter_var($_POST[’email’], FILTER_VALIDATE_EMAIL)) { echo “Invalid email format.”; } else { // Process data if valid echo “Valid input.”; }

4. Sanitizing User Input

Sanitization ensures that potentially harmful data is neutralized before being used, helping to prevent security issues like XSS (Cross-Site Scripting).

  • htmlspecialchars(): Converts HTML characters to entities, preventing code injection.
  • filter_var(): Use for sanitizing email, URL, and other inputs.

$name = htmlspecialchars($_POST[‘name’]); $email = filter_var($_POST[’email’], FILTER_SANITIZE_EMAIL);

5. Using Prepared Statements for Database Input

If user input will be used in database queries, it’s important to use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL syntax from data, making it safer to include user input in queries.

$pdo = new PDO(“mysql:host=localhost;dbname=testdb”, “username”, “password”); $stmt = $pdo->prepare(“INSERT INTO users (name, email) VALUES (:name, :email)”); $stmt->bindParam(‘:name’, $name); $stmt->bindParam(‘:email’, $email); $stmt->execute();

6. Example: Complete User Input Handling Process

Here’s a full example of a PHP script handling form input with validation, sanitization, and data usage.

// process.php if ($_SERVER[“REQUEST_METHOD”] == “POST”) { $name = trim($_POST[‘name’]); $email = trim($_POST[’email’]); // Validation if (empty($name)) { echo “Name is required.”; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { echo “Invalid email format.”; } else { // Sanitization $name = htmlspecialchars($name); $email = filter_var($email, FILTER_SANITIZE_EMAIL); // Processing (e.g., saving to a database) echo “Name: ” . $name . “<br>”; echo “Email: ” . $email; } }

Summary

  • Capture user input with $_POST or $_GET.
  • Validate to ensure required fields are correctly formatted.
  • Sanitize to prevent security issues.
  • Use prepared statements when inserting into databases. Following these steps ensures safe and efficient handling of user input in PHP.