In PHP, the $_GET superglobal is used to collect form data and retrieve values from the URL query string. It is commonly used in search forms, navigation links, and API requests.
🔹 How Does $_GET Work?
When a user visits a URL like:
https://example.com/page-get.php?name=John&age=25
PHP can access the values using $_GET like this:
in page-get.php
<?php $name = $_GET['name']; // Retrieves "John" $age = $_GET['age']; // Retrieves "25" echo "Hello, $name! You are $age years old."; ?>
Output: Hello, John! You are 25 years old.
🔹 Using $_GET with HTML Forms
When using a form with method="get", data is sent as a query string in the URL.
<form action="welcome.php" method="get">
Name: <input type="text" name="name"> <br>
Age: <input type="number" name="age"> <br>
<input type="submit" value="Submit">
</form>
When the user submits the form, the URL changes to:
https://example.com/welcome.php?name=Alice&age=30
Then, in welcome.php:
<?php
if (isset($_GET['name']) && isset($_GET['age'])) {
echo "Welcome, " . $_GET['name'] . "! You are " . $_GET['age'] . " years old.";
} else {
echo "Please enter your details.";
}
?>
🔹 Handling Missing or Undefined $_GET Variables
Always check if the key exists using isset() to avoid errors.
<?php $name = isset($_GET['name']) ? $_GET['name'] : "Guest"; echo "Hello, $name!"; ?>
Output: If no name is provided in the URL, it defaults to “Guest”.
🔹 Security Concerns with $_GET
- 🚨 Never use `$_GET` to send sensitive data (like passwords) since it’s visible in the URL.
- 🛡 Always sanitize input to prevent XSS (Cross-Site Scripting) and SQL injection.
Use htmlspecialchars() to prevent malicious input:
<?php $name = isset($_GET['name']) ? htmlspecialchars($_GET['name']) : "Guest"; echo "Welcome, $name!"; ?>
🎯 Key Takeaways
$_GETretrieves values from the URL query string.- Used in links, forms, and APIs to send data.
- Always check with
isset()before using to prevent errors. - Use
htmlspecialchars()to prevent XSS attacks.
📝 Practice Time!
Modify the examples and create a **funny character generator** that accepts a name and favorite color via $_GET!