Home > Article > Backend Development > 4 ways to get parameters as arrays in PHP
In PHP, we often need to get parameters from different sources. These parameters can come from GET requests, POST requests, COOKIE, SESSION, etc. When processing these parameters, we often need to save them as arrays for easier operation.
The following introduces several methods for PHP to obtain parameters as arrays:
The parameters in GET requests can be passed directly $_GET array acquisition. For example, if we have the following request: http://www.example.com/index.php?name=john&age=18 In PHP, we can get the parameters like this:
$name = $_GET['name']; $age = $_GET['age'];
If we want to add all The parameters are saved as an array, and you can use the following method:
$params = $_GET;
The parameters in the POST request can be obtained through the $_POST array. For example, if we have the following request:
<form method="POST" action="handler.php"> <input type="text" name="name"> <input type="text" name="age"> <input type="submit" value="提交"> </form>
In PHP, we can get the parameters like this:
$name = $_POST['name']; $age = $_POST['age'];
If we want to save all parameters as an array, we can use the following method :
$params = $_POST;
The parameters in COOKIE can be obtained through the $_COOKIE array. For example, if we have the following COOKIE:
setcookie('name', 'john', time()+3600); setcookie('age', '18', time()+3600);
In PHP, we can get the parameters like this:
$name = $_COOKIE['name']; $age = $_COOKIE['age'];
If we want to save all parameters as an array, we can use the following method :
$params = $_COOKIE;
The parameters in SESSION can be obtained through the $_SESSION array. For example, if we save the user information in SESSION after successful login:
$_SESSION['user'] = array( 'name' => 'john', 'age' => 18 );
In PHP, we can get the parameters like this:
$name = $_SESSION['user']['name']; $age = $_SESSION['user']['age'];
If we want to save all parameters as For an array, you can use the following method:
$params = $_SESSION['user'];
Summary:
Through the above methods, we can save parameters from different sources as arrays to facilitate our subsequent operations. At the same time, it should be noted that parameters in GET and POST requests need to be security filtered to prevent attacks such as XSS and SQL injection. In actual development, you can use PHP's built-in functions such as htmlspecialchars and mysqli_real_escape_string for filtering.
The above is the detailed content of 4 ways to get parameters as arrays in PHP. For more information, please follow other related articles on the PHP Chinese website!