PHP $_GET Array 🎯

beginner
25 min

PHP $_GET Array 🎯

Welcome to our comprehensive guide on the PHP $_GET array! This tutorial is designed to help you understand and master the $_GET array, a powerful tool in PHP for handling data passed to a script via URL. Let's get started!

What is the $_GET Array? πŸ“

The $_GET array in PHP is used to collect data that is passed to a PHP script from an HTML form using the URL. This is part of PHP's superglobal arrays and is accessible in any PHP script without the need to declare it.

How to Access $_GET Data? πŸ’‘

To access data from the $_GET array, you can use the variable name that you used in your HTML form as an index for the array.

php
<?php $name = $_GET['name']; $email = $_GET['email']; // ... and so on for other form fields ?>

In the example above, we are accessing the name and email fields from the form data passed via URL.

URL Encoding πŸ’‘

Before sending form data via URL, it needs to be URL-encoded. URL encoding is the process of converting special characters into a format that can be sent via URL. PHP automatically handles URL encoding when you use the method="get" attribute in your HTML form.

html
<form action="receive.php" method="get"> <!-- ... Your form fields here ... --> </form>

Practical Example 🎯

Let's create a simple login form and handle the login using the $_GET array.

  1. Create a login form: login.html
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <form action="check_login.php" method="get"> Username: <input type="text" name="username" required> Password: <input type="password" name="password" required> <button type="submit">Login</button> </form> </body> </html>
  1. Create the PHP script to check the login: check_login.php
php
<?php $username = $_GET['username']; $password = $_GET['password']; // ... (Here you can add your login check logic) if ($username && $password) { echo "Login successful!"; } else { echo "Invalid username or password."; } ?>

Security Considerations πŸ’‘

While the $_GET array is a powerful tool, it's essential to be aware of potential security issues. Never trust user-supplied data directly, as it may contain malicious code. Always sanitize and validate user input to ensure the security of your application.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What is the purpose of the `$_GET` array in PHP?

We hope you found this tutorial helpful! Stay tuned for more PHP tutorials on CodeYourCraft. Happy coding! πŸš€