0
0
PhpHow-ToBeginner · 4 min read

How to Take Input in PHP: Simple Guide with Examples

In PHP, you can take input from users using $_GET and $_POST superglobals for web forms, or readline() for command-line input. Use $_GET to get data from URL parameters and $_POST to get data sent via form submissions.
📐

Syntax

PHP uses special arrays called superglobals to get input from users in web applications:

  • $_GET['key']: Gets input from URL query parameters.
  • $_POST['key']: Gets input from form data sent via POST method.
  • readline(): Reads input from the command line in CLI scripts.

Replace 'key' with the name of the input field or parameter.

php
<?php
// Getting input from URL: example.php?name=John
$name = $_GET['name'];

// Getting input from a form submitted via POST
$email = $_POST['email'];

// Getting input from command line
$input = readline('Enter something: ');
?>
💻

Example

This example shows how to take input from a user via a simple HTML form using $_POST and display it.

php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? 'Guest';
    echo "Hello, " . htmlspecialchars($name) . "!";
} else {
?>
<form method="post">
  <label for="name">Enter your name:</label>
  <input type="text" id="name" name="name" required>
  <button type="submit">Submit</button>
</form>
<?php
}
?>
Output
Hello, John!
⚠️

Common Pitfalls

Common mistakes when taking input in PHP include:

  • Not checking if the input exists before using it, which causes errors.
  • Not sanitizing input, leading to security risks like XSS or SQL injection.
  • Confusing $_GET and $_POST methods.
  • Using readline() in a web context, which won't work.

Always validate and sanitize user input before using it.

php
<?php
// Wrong: Using input without checking
// echo $_POST['username']; // May cause error if 'username' not set

// Right: Check if input exists
if (isset($_POST['username'])) {
    $username = htmlspecialchars($_POST['username']);
    echo "User: $username";
} else {
    echo "No username provided.";
}
?>
📊

Quick Reference

MethodDescriptionUsage Example
$_GETGets input from URL query parameters$_GET['param']
$_POSTGets input from form data sent via POST$_POST['field']
readline()Reads input from command line (CLI only)$input = readline('Prompt: ');

Key Takeaways

Use $_GET and $_POST superglobals to get user input from web forms and URLs.
Always check if input exists with isset() before using it to avoid errors.
Sanitize user input with functions like htmlspecialchars() to prevent security issues.
Use readline() only for command-line PHP scripts, not for web input.
Understand the difference between GET and POST methods for proper input handling.