In PHP development, global arrays are predefined variables that can be accessed from any scope within a script. They are used to handle HTTP request data, manage session information, work with cookies, and more. These arrays are essential for building dynamic web pages. This article will explain the most common PHP global arrays and how to use them.
The $_GET array is used to receive data passed via URL parameters, typically through GET requests. Each parameter is stored as a key-value pair within the array, making it easy to retrieve specific values.
// Example URL: http://example.com?name=John&age=30
$name = $_GET['name'];
$age = $_GET['age'];
echo "Name: " . $name;
echo "Age: " . $age;
In the example above, the parameters name and age are passed via the URL and captured by the $_GET array. Their values are then outputted.
The $_POST array is used to handle data submitted via HTML forms using the POST method. Unlike GET, POST is more secure and suitable for submitting sensitive or large amounts of data.
<form action="process.php" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>
// process.php
$username = $_POST['username'];
$password = $_POST['password'];
echo "Username: " . $username;
echo "Password: " . $password;
The above example shows a login form where the data entered by the user is submitted to process.php and accessed via the $_POST array.
The $_SESSION array is used to store session data, which can be shared across multiple pages during a user's interaction with the website. This is useful for maintaining user login status, preferences, etc.
// start.php
session_start();
$_SESSION['username'] = 'John';
// profile.php
session_start();
$username = $_SESSION['username'];
echo "Username: " . $username;
In this code, the username is stored in $_SESSION on the start.php page, and it is retrieved in profile.php to display the user's name.
The $_COOKIE array is used to store and retrieve data from the client-side cookies. Cookies are often used to store user preferences or session identifiers.
// set_cookie.php
setcookie("username", "John", time()+3600); // Set cookie to expire in 1 hour
// get_cookie.php
$username = $_COOKIE['username'];
echo "Username: " . $username;
In the example, the cookie is set on the client-side in set_cookie.php, and it is retrieved in get_cookie.php to display the stored value.
PHP global arrays like $_GET, $_POST, $_SESSION, and $_COOKIE play a crucial role in web development. They provide a convenient way to handle data across different scopes and pages.
When using these global arrays, it's important to perform proper input validation and data filtering to avoid security vulnerabilities such as SQL injection and XSS. Functions like filter_input() or htmlspecialchars() can help enhance security.
Mastering the use of PHP's global arrays will help you build more secure, stable, and feature-rich web applications.