Home > Article > Backend Development > How can I access all variables from a POST request in PHP?
Getting All POST Variables
Question:
How do I access all variables sent through a POST request?
Answer:
The $_POST global variable automatically stores all POST data. To view its contents:
var_dump($_POST);
Individual values can be accessed like this:
$name = $_POST["name"];
Handling Non-Standard POST Data
If the POST data is in a format other than multipart/form-data, such as JSON or XML:
$post = file_get_contents('php://input');
This will contain the raw data.
Checking Checkbox Values
To test if a checkbox is checked (assuming standard $_POST usage):
if(isset($_POST['myCheckbox']) && $_POST['myCheckbox'] == 'Yes') { ... }
Handling Checkbox Arrays
If you have an array of checkboxes:
<input type="checkbox" name="myCheckbox[]" value="A" />val1<br /> <input type="checkbox" name="myCheckbox[]" value="B" />val2<br /> <input type="checkbox" name="myCheckbox[]" value="C" />val3<br />
$_POST['myCheckbox'] will be an array containing the checked values.
Example:
$myboxes = $_POST['myCheckbox']; if(empty($myboxes)) { echo("You didn't select any boxes."); } else { $i = count($myboxes); echo("You selected $i box(es): <br>"); for($j = 0; $j < $i; $j++) { echo $myboxes[$j] . "<br>"; } }
The above is the detailed content of How can I access all variables from a POST request in PHP?. For more information, please follow other related articles on the PHP Chinese website!