Arrays are essential tools in PHP development for managing and storing multiple sets of data. Besides custom arrays, PHP offers several built-in predefined arrays that help developers quickly access request information, server environment details, and user data. This article focuses on several commonly used predefined arrays and demonstrates their usage with examples.
$_SERVER is an array that contains information about the server and execution environment. It allows you to obtain various details such as the current script path, server IP address, and request method.
// Get the current PHP file path
echo $_SERVER['PHP_SELF'];
// Get the server IP address
echo $_SERVER['SERVER_ADDR'];
// Get the request method
echo $_SERVER['REQUEST_METHOD'];
$_GET is used to collect data passed via URL parameters using the GET method. It provides easy access to query parameters included in the URL.
// Get the value of the parameter 'id' from the URL
$id = $_GET['id'];
echo "The value of parameter id is: " . $id;
$_POST collects form data submitted through the HTTP POST method. Compared to $_GET, it does not expose data in the URL, making it more suitable for sensitive information.
// Get submitted username and password from form
$username = $_POST['username'];
$password = $_POST['password'];
echo "Username: " . $username . ", Password: " . $password;
$_SESSION stores session data to maintain state across different pages, such as keeping track of user login information.
// Store user login status
$_SESSION['user'] = 'John Doe';
// Retrieve user login status
echo "Current user: " . $_SESSION['user'];
$_FILES handles file upload information, including file name, temporary path, and error status.
// Handle file upload
if ($_FILES['file']['error'] === 0) {
$file_name = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
move_uploaded_file($file_tmp, "uploads/" . $file_name);
echo "File uploaded successfully!";
} else {
echo "File upload failed!";
}
Mastering PHP predefined arrays is crucial for efficiently processing request data and managing user sessions. Whether retrieving server details or handling form submissions, these arrays provide convenient and secure solutions. Developers are encouraged to understand and apply these arrays flexibly based on project requirements to improve PHP development efficiency and code quality.