Reputation: 561
I have an html form that depending on the checkbox my java-script change it from GET to POST. This piece of code is currently working.
My question is I have a variable on the server side that I need to get. The html variable is sent either as POST or GET, but not sure how to retrieve that variable regardless or what method the html uses. I know how to get the variable as either POST or GET manually, but Not sure how to go about accomplishing this automatically. Any suggestions?
$myVariable = $_GET['htmlVariable'] or $myVariable = $_POST['htmlVariable']
Upvotes: 0
Views: 1008
Reputation: 21
If you are building any page that may require either input type, instead of trying to determine what is being provided, just use $_REQUEST.
if (isset($_REQUEST['htmlVariable'] && $_REQUEST['htmlVariable'] != '') {
$htmlVariable = $_REQUEST['htmlVariable'];
}
Upvotes: 0
Reputation: 166
1) Use $_GET if you know that data is coming via URL parameter
if (isset($_GET['htmlVariable'] && $_GET['htmlVariable'] != '') {
$htmlVariable = $_GET['htmlVariable'];
}
2) Use $_POST if you know that data is coming via HTTP POST method
if (isset($_POST['htmlVariable'] && $_POST['htmlVariable'] != '') {
$htmlVariable = $_GET['htmlVariable'];
}
3) If you don't know use $_REQUEST
if (isset($_REQUEST['htmlVariable'] && $_REQUEST['htmlVariable'] != '') {
$htmlVariable = $_GET['htmlVariable'];
}
Upvotes: 1
Reputation: 42304
It sounds like you're looking to check if one of the two methods is found. If it is, use that method, and if not, use the other method. To achieve this you can use isset()
, and note that you'll also want to check that the string isn't empty:
if (isset($_GET['htmlVariable'] && $_GET['htmlVariable'] != '') {
$myVariable = $_GET['htmlVariable'];
}
else if (isset($_POST['htmlVariable'] && $_POST['htmlVariable'] != '') {
$myVariable = $_POST['htmlVariable'];
}
else {
$myVariable = 'something else';
}
Also note that the order in which you check for the methods may make a difference, depending on your logic.
Upvotes: 0