PHP: Parsing of a given form input variable - php

How would I go about parsing incoming form data where the name changes based on section of site like:
<input type="radio" name="Motorola section" value="Ask a question">
where 'Motorola section may be that, or Verizon section, or Blackberry section, etc.
I do not have any control over changing the existing forms unfortunately, so must find a way to work with what is there.
Basically, I need to be able to grab both the name="" data as well as its coresponding value="" data to be able to populate the email that gets sent properly.

Well, you don't receive a HTML form, but just field names and values in $_POST. So you have to look what to make out of that.
Get the known and fixed fields from $_POST and unset() those you've got [to simplify]. Then iterate over the rest. If " section" is the only constant, then watch out for that:
foreach ($_POST as $key=>$value) {
if (stristr($key, "section")) {
$section = $value;
$section_name = $key;
}
}
If there are multiple sections (you didn't say), then build an section=>value array instead.

<form action="formpage.php" method="post">
<input type="radio" name="Motorola_section" value="Ask a question">
</form>
$motorola = $_POST['Motorola_section'];
if ($motorola =='Ask a question')
{
form submit code if motorola is selected
}

Well, first off, you shouldn't have spaces in the name field (even though it should work with them).
Assuming it's a form, you can get the value through the $_POST (for the POST method) and $_GET (for the GET method) variables.
<?php
if ( isset( $_POST['Motorola section'] ) ) // checks if it's set
{
$motoSec = $_POST['Motorola section']; // grab the variable
echo $motoSec; // display it
}
?>
You can also check the variables using print_r( $_GET ) or print_r( $_POST ).

Related

Store _POST into variable to use with Page Data [duplicate]

I'm making a php script that stores 3 arrays: $images, $urls, $titles based on the input data of the form within the php file.
I want to print the values of these arrays in the first part of the page and then to pre-fill the form's input fields with the value of the arrays. Also when a user modifies an input field and clicks on "Save" the page should reload with the modfied version.
My problem is that on each call of the php file in a browser the value of the variables gets deleted. Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?
<?php
//save the arrays with the form data
$images = array($_POST["i0"],$_POST["i1"],$_POST["i2"],$_POST["i3"]);
$urls = array($_POST["u0"],$_POST["u1"],$_POST["u2"],$_POST["u3"]);
$titles = array($_POST["t0"],$_POST["t1"],$_POST["t2"],$_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
echo"<div>
<input name='i".$x."' type='text' value='".$images[$x]."'>
<input name='u".$x."' type='text' value='".$urls[$x]."'>
<input name='t".$x."' type='text' value='".$titles[$x]."'>";
$x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
Store the variables in a PHP session.
session_start();
$_SESSION['images'] = $images;
Then on next (or any other) page, you can retrieve the values as:
session_start();
$images = $_SESSION['images'];
Changing the scope of the variables to a larger scope, might do the trick. Also, check if you have a post request before updating the values.
<?php
if(sizeof($_POST) >0)
{
//UPDATE VALUES
}
?>
If you want a permanent storage of state, between different pages, you should use sessions, by putting session_start(); in the start of your script. After this, every variable $_SESSION[$x] will be persisted, and will be available to your scripts.
However, in this particular case, answering your question: "Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?", it is easier to just use the $_POST variable if it exists already:
<?php
if(!$_POST){
$_POST = array();
foreach(array("i0","i1","i2","i3") as $i) $_POST[$i]="";
foreach(array("u0","u1","u2","u3") as $i) $_POST[$i]="";
foreach(array("t0","t1","t2","t3") as $i) $_POST[$i]="";
}
foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
//save the arrays with the form data
$images = array($_POST["i0"], $_POST["i1"], $_POST["i2"], $_POST["i3"]);
$urls = array($_POST["u0"], $_POST["u1"], $_POST["u2"], $_POST["u3"]);
$titles = array($_POST["t0"], $_POST["t1"], $_POST["t2"], $_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
echo"<div>
<input name='i".$x."' type='text' value='".$images[$x]."'>
<input name='u".$x."' type='text' value='".$urls[$x]."'>
<input name='t".$x."' type='text' value='".$titles[$x]."'>";
$x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
Note: this line foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
should be enough to protect you from basic XSS attacks.
Note also that in general, it is best to follow the pattern of reloading pages with GET after POST, which makes you less susceptible to form resubmitions, in which case using sessions for storage is the better solution.
What brought me here was somewhat different kind of beast. I had problem with subsequent post request from AXIS IP camera and needed to preserve last file name across requests. In case that someone stumble here looking for some way to cache variables and SESSION is not an option maybe should look at Alternative PHP Cache:
Note: Unlike many other mechanisms in PHP, variables stored using
apc_store() will persist between requests (until the value is removed
from the cache).
http://php.net/manual/en/book.apc.php
Use sessions: http://php.net/manual/en/function.session-start.php
You can use sessions to store values and write rules to refill form fields after validations on data submit. Also function isset() is very helpful to avoid "not defined" errors.
The solution you are looking for is the session. Use $_SESSION to store value of Your variables. For example, at the end of script:
$_SESSION['images'] = $images;
and in form's input:
<input name='i".$x."' type='text' value='".(isset($_SESSION['images']) ?
$_SESSION['images'] : '')."'>

Doing an inline if in the action of a form

I need to redirect the user to a site that gets the "Short_proj_name" information. So i did this:
<form action="Main.php?short_proj_name=<?=$_REQUEST['short_proj_name']?>" method="post" name="formProjName" target="_blank" id='frmProjName'>
However, upon searching, i found out that there are several reasons NOT to use $_REQUEST, one of them being security and all that. However, simply doing $_POST['short_proj_name'] or $_GET['short_proj_name'] never returns the information i need.
Basically, how would i go about doing an if statement that checks if the $_GET is empty, and does a $_POST instead? Can i do that in the action method of my form?
EDIT:
Adittionally, is it possible that maybe using both $_POST and $_GET return null, yet using $_REQUEST doesnt? As far as i know, $_REQUEST is both get and post together, but none of them returns any information
It works if i do it as so:
if(!empty($_POST['short_proj_name']))
{
$projName = $_POST['short_proj_name'];
}
elseif (!empty($_GET['short_proj_name']))
{
$projName = $_GET['short_proj_name'];
}
else
{
$projName = $_REQUEST['short_proj_name'];
}
But i'm not sure if that solves the security problem at all
I think the answer here is to always use _GET.
A form can actually send both _GET and _POST data based on what you use in the "action" attribute of the form. The action part doesn't care what you set the "method" attribute as.
From what you are showing above, the params are all in the "action" part of the form so these are always passed into _GET anyway. If the inputs were inside the form then those would be received via _POST
Here's an example.
In PHP I would receive $_GET['monkey'] = '1' and $_POST['lion'] = 1
<form method='post' action='receive.php?monkey=1'>
<input type='text' name='lion' value='1' />
<input type='submit' />
</form>
There shouldn't really ever be an instance where you need to check if the answer is in _GET or _POST and as mentioned in a comment, it's quite a security risk to use $_REQUEST or check if it's in _GET or _POST.
Most times, you can just push the page request URL back into the form "action" to ensure all the same _GET params are included on the form _POST.
The big mistake most people do is try to move them from _GET into hidden input fields inside a form thinking they need to do that to carry all that data through.
However, this type of function call might help you but I wouldn't approve of it.
function getRequestParam($param){
if(isset($_GET[$param])){return $_GET[$param];}
if(isset($_POST[$param])){return $_POST[$param];}
return "";
}
you can like
<?php
if(!empty($_POST))
{
$projName = $_POST['short_proj_name'];
}
else
{
$projName = $_GET['short_proj_name'];
}
?>
<form action="Main.php?short_proj_name=<?=$projName ?>" method="post" name="formProjName" target="_blank" id='frmProjName'>
but i think it's ugly
Here is a simple code :
<?php
if (isset($_GET) && $_GET['short_proj_name'] != '')
echo $_GET['short_proj_name'];
else if (isset($_POST) && $_POST['short_proj_name'] != '')
echo $_GET['short_proj_name'];
else
echo $_REQUEST['short_proj_name'];
?>
But if you get the value from a post or get, it can be anything so be careful...
If the "short_proj_name" is a file name, a nasty person can get access to other files just by guessing their names...

PHP avoiding a long POST

This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}

check if checkbox is checked in php

I have a check box list which I fill it with data from my table.Here is the code:
<?php
mysql_connect("localhost","root","");
mysql_select_db("erp");
$a="Select * from magazine";
$b=mysql_query($a);
$c=mysql_fetch_array($b);
while($c=mysql_fetch_array($b))
{
print '<input type="checkbox"/>'.$c['den_mag'];
echo "</br>";
}
if(isset($_POST['den_mag']))
{
echo "aaaa";
}
?>
It's a simple query and for each data just show it with a checkbox.Now what I want is when I press a checkbox the value of that checkbox to be shown in a table.So if I have check1 with value a , check2 with value b and I check check1 the value a to be outputted to a table row.How can I achieve that? how cand I get which checkbox is checked?
A few notes:
Try to avoid using SELECT * queries. Select the fields you are going to use:
$sql= '
SELECT
id,
den_mag
FROM
magazine
';
Use better variable names. $a and $c make your code harder to follow for others, and for yourself when you come back at a later time. Use more descriptive variable names like $query_object and $row. Your code should read almost like an essay describing what you're doing.
In your form, use an array of elements. By giving the input a name like selected_magazines[], you will end up with an array in your post data, which is what you want -- multiple selections
Use the row ID as the value of the checkbox element. Your array in POST will then be a list of all the IDs that the user selected
Separate your logic from your HTML generation. The top portion of your script should take care of all logic and decisions. At the bottom, output your HTML and avoid making logical decisions. It makes for a script that is easier to follow and maintain, as well as debug.
Here is a sample script incorporating these ideas with the details you've given:
<?php
// FILE: myfile.php
mysql_connect("localhost","root","");
mysql_select_db("erp");
if(isset($_POST['selected_magazine'])) {
// $_POST['selected_magazine'] will contain selected IDs
print 'You selected: ';
print '<ul><li>'.implode($_POST['selected_magazine'], '</li><li>').'</li></ul>';
die();
}
$sql= '
SELECT
`id`,
`den_mag`
FROM
`magazine`
';
$query_object=mysql_query($sql);
$checkboxes = array();
while($row = mysql_fetch_array($query_object)) {
$checkboxes[] = '<input name="selected_magazine[]" value="'.$row['id'].'" type="checkbox" /> '.$row['den_mag'];
}
?>
<form action="myfile.php" method="post">
<?php print implode('<br>', $checkboxes); ?>
<input type="submit" value="Submit" />
</form>
<input name="test" type="checkbox" />
<?php
if(isset($_REQUEST['test'])){
// selected
}
?>
When you give input-type elements (input, textarea, select, button) a name attribute (like I did), the browser will submit the state/value of the element to the server (if the containing form has been submitted).
In case of checkboxes, you don't really need to check the value, but just that it exists. If the checkbox is not selected, it won't be set.
Also, you need to understand the client-server flow. PHP can't check for something if the client does not send it.
And finally, someone mentioned jQuery. jQuery is plain javascript with perhaps some added sugar. But the point is, you could in theory change stuff with jQuery so that it gets (or doesn't get) submitted with the request. For example, you could get jQuery to destroy the checkbox before the form is submitted (the checkbox won't be sent in this case).
Here you go :
<html>
<input name="test" value="true" type="checkbox" />
</html>
<?php
$Checkbox1 = "{$_POST['test']}";
if($Checkbox1 == 'true'){
// yes, it is checked
}
?>

how to store variable values over multiple page loads

I'm making a php script that stores 3 arrays: $images, $urls, $titles based on the input data of the form within the php file.
I want to print the values of these arrays in the first part of the page and then to pre-fill the form's input fields with the value of the arrays. Also when a user modifies an input field and clicks on "Save" the page should reload with the modfied version.
My problem is that on each call of the php file in a browser the value of the variables gets deleted. Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?
<?php
//save the arrays with the form data
$images = array($_POST["i0"],$_POST["i1"],$_POST["i2"],$_POST["i3"]);
$urls = array($_POST["u0"],$_POST["u1"],$_POST["u2"],$_POST["u3"]);
$titles = array($_POST["t0"],$_POST["t1"],$_POST["t2"],$_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
echo"<div>
<input name='i".$x."' type='text' value='".$images[$x]."'>
<input name='u".$x."' type='text' value='".$urls[$x]."'>
<input name='t".$x."' type='text' value='".$titles[$x]."'>";
$x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
Store the variables in a PHP session.
session_start();
$_SESSION['images'] = $images;
Then on next (or any other) page, you can retrieve the values as:
session_start();
$images = $_SESSION['images'];
Changing the scope of the variables to a larger scope, might do the trick. Also, check if you have a post request before updating the values.
<?php
if(sizeof($_POST) >0)
{
//UPDATE VALUES
}
?>
If you want a permanent storage of state, between different pages, you should use sessions, by putting session_start(); in the start of your script. After this, every variable $_SESSION[$x] will be persisted, and will be available to your scripts.
However, in this particular case, answering your question: "Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?", it is easier to just use the $_POST variable if it exists already:
<?php
if(!$_POST){
$_POST = array();
foreach(array("i0","i1","i2","i3") as $i) $_POST[$i]="";
foreach(array("u0","u1","u2","u3") as $i) $_POST[$i]="";
foreach(array("t0","t1","t2","t3") as $i) $_POST[$i]="";
}
foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
//save the arrays with the form data
$images = array($_POST["i0"], $_POST["i1"], $_POST["i2"], $_POST["i3"]);
$urls = array($_POST["u0"], $_POST["u1"], $_POST["u2"], $_POST["u3"]);
$titles = array($_POST["t0"], $_POST["t1"], $_POST["t2"], $_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
echo"<div>
<input name='i".$x."' type='text' value='".$images[$x]."'>
<input name='u".$x."' type='text' value='".$urls[$x]."'>
<input name='t".$x."' type='text' value='".$titles[$x]."'>";
$x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>
Note: this line foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
should be enough to protect you from basic XSS attacks.
Note also that in general, it is best to follow the pattern of reloading pages with GET after POST, which makes you less susceptible to form resubmitions, in which case using sessions for storage is the better solution.
What brought me here was somewhat different kind of beast. I had problem with subsequent post request from AXIS IP camera and needed to preserve last file name across requests. In case that someone stumble here looking for some way to cache variables and SESSION is not an option maybe should look at Alternative PHP Cache:
Note: Unlike many other mechanisms in PHP, variables stored using
apc_store() will persist between requests (until the value is removed
from the cache).
http://php.net/manual/en/book.apc.php
Use sessions: http://php.net/manual/en/function.session-start.php
You can use sessions to store values and write rules to refill form fields after validations on data submit. Also function isset() is very helpful to avoid "not defined" errors.
The solution you are looking for is the session. Use $_SESSION to store value of Your variables. For example, at the end of script:
$_SESSION['images'] = $images;
and in form's input:
<input name='i".$x."' type='text' value='".(isset($_SESSION['images']) ?
$_SESSION['images'] : '')."'>

Categories