How to Access user input in PHP ? See Example

Accessing user input is one of the most essential tasks in PHP development—whether it’s capturing form data, URL parameters, cookies, or session values. PHP makes this easy using Superglobal Arrays, which are available in all scopes without requiring special initialization.


How PHP Receives User Input

PHP collects user input through predefined superglobal arrays such as:

1. $_GET – Accessing Data Sent Through URL

Used when data is sent via URL query strings.

Example URL:

example.com/form.php?name=Sagar&age=23

PHP Code:

$name = $_GET['name'];
$age  = $_GET['age'];

echo "Name: $name, Age: $age";

2. $_POST – Accessing Data Sent Through HTML Forms

Used when forms are submitted using the POST method.

HTML Form:

<form method="POST" action="submit.php">
  <input type="text" name="username">
  <button type="submit">Submit</button>
</form>

submit.php:

$username = $_POST['username'];
echo "Username: $username";

POST is more secure than GET because values are not visible in the URL.


3. $_REQUEST – Combines GET, POST, and COOKIE

Useful when you don’t know the method used.

$user = $_REQUEST['user'];

However, using $_REQUEST is less secure and less predictable—use only when necessary.


4. $_FILES – Accessing Uploaded Files

Handles file uploads securely.

$fileName = $_FILES['upload']['name'];
$temp     = $_FILES['upload']['tmp_name'];
move_uploaded_file($temp, "uploads/".$fileName);

5. $_COOKIE – Accessing User Cookies

echo $_COOKIE["userToken"];

6. $_SESSION – Accessing Session Data

session_start();
echo $_SESSION["username"];

Validating User Input

Always validate input to avoid security issues like SQL injection and XSS.

Example:

$name = htmlspecialchars($_POST['name']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

Final Summary

PHP makes accessing user input simple using its built-in superglobal variables. Forms, URLs, cookies, and sessions can all be processed easily and securely when combined with proper validation and sanitization.

Citations

🔗 View other articles about PHP:
http://savanka.com/category/learn/php/

🔗 External PHP Documentation:
https://www.php.net/manual/en/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *