PHP I want to demand my Array at my will - php

First off, I am a PHP NOOB.
I am currently trying to develop a PHP page that is suppose to calculate a monthly budget for you and I am having problem with one section of it.
I am having problem with my food variables.
I can't give you the syntax I have for the "foodPerMonth" array because I simply don't know how to write it. Everything I've written so far is wrong.
Anyhow. This is how I want it to work.
I have my html form. I'm making it shorter just for the food part.
You are suppose to type in how many i.e "Adult Woman" you want in your budget.
And I will have a variable for each of those that will contain the cost per month for each person.
<form action="function.php" method="post">
<label>Adult Woman: </label><input type="text" name="foodPerMonth[]" /><br />
<label>Adult Man: </label><input type="text" name="foodPerMonth[]" /><br />
<label>Juvenile Girl: </label><input type="text" name="foodPerMonth[]" /><br />
<label>Juvenile Boy: </label><input type="text" name="foodPerMonth[]" /><br />
<label>Child Girl: </label><input type="text" name="foodPerMonth[]" /><br />
<label>Child Boy: </label><input type="text" name="foodPerMonth[]" /><br />
<label>Baby Girl: </label><input type="text" name="foodPerMonth[]" /><br />
<label>Baby Boy: </label><input type="text" name="foodPerMonth[]" /><br />
<input type="submit" value="Submit" />
</form>
What I want to know is how do I type this kind of array that will go with the form and etc.
I would also appreciate if someone could thorougly explain how arrays and keys work and how they are used and what they are used for. Doesn't matter how much I read the fact in the manual. It wont stuck.
Thank you in advance for answering, all help will be greatly appreciated.

You're going to want:
<label>Adult Woman: <input type="text" name="foodPerMonth[adultwoman]" /></label><br />
<label>Adult Man: <input type="text" name="foodPerMonth[adultman]" /></label><br />
[note: also wrap the labels around the inputs]
Which will be accessible via:
$_POST['foodPerMonth']['adultman'];
$_POST['foodPerMonth']['adultwomman'];
Just the blank foodPerMonth[] syntax crams everything into a numbered array which skips any fields left blank making the numbering unreliable.

Related

How to create a form where input elements are already set but one must remain fixed?

I am feeding my forms preset data values from another file in a MVC application. One of the data set attributes, the ID, is to remain fixed and cannot be updated. Only the names, phones numbers etc can be updated. My issue is that I need to have something set with this that I can submit, just like the other preset data; however unlike the other preset data I cannot put this in a form as a user may change it.
<form action="crud.ctrl.php?act=update" method="post">
<label>ID: <?=$data1["id"]?> <br /><br>
<label>First Name:</label> <br><input type="text" name="fnameUP" id="fnameUP" value="<?= $data1["fname"] ?>"> <br />
<label>Last Name:</label> <br><input type="text" name="lnameUP" value="<?= $data1["lname"] ?>""> <br />
<label>Phone:</label> <br><input type="text" name="phoneUP" value="<?= $data1["phone"] ?>""> <br />
<label>Email:</label> <br><input type="text" name="emailUP" value="<?= $data1["email"] ?>""> <br />
<label>Location:</label> <br><input type="text" name="locationUP" value="<?= $data1["location"] ?>""> <br />
<label>MC:</label> <br><input type="text" name="mcUP" value="<?= $data1["mc"] ?>""> <br />
<label>Position:</label> <br><input type="text" name="posUP" value="<?= $data1["pos"] ?>""> <br />
<label>Department:</label> <br><input type="text" name="deptUP" value="<?= $data1["dept"] ?>""> <br />
<input type="submit">
</form>
one way to solve this issue would be to have another unique column in the original table. For example you could 'salt' the ID and hash that or use some other form of creating a long enough string to prevent the user to guess any of the existing "IDs".
And then just include that column in the form as a hidden input field for example
<input type="hidden" name="custom_id" value="<?=$data1["custom_id"]?>">
that way even if the user does mess with the ID, there is a very small chance for him to be able to change another record. The more complex your hashing, the smaller the chance.
If that is not secure enough, my next idea would be to have another column/table in the database where you generate a hash when retreiving the data that will be shown in the form and only allow updating the records that have that value set. that way the only "editable" rows are the ones where someone requested the edit form in the last X minutes.

HOW to add increment value to $_POST['variable'] in php?

I am using dynamic form where user add more input text boxes for a certain field he want and the name of each box change with an increment like:
<form method="post" action="somescript.php">
<input type="text" name="textbox" />
<input type="text" name="textbox1" />
<input type="text" name="textbox2" />
<input type="text" name="textbox3" />
.... and so on
</form>
I want to echo these data following a loop:
<?PHP
$k=$_POST['counter']; //counter value coming as post variable
for($i=1$i<=$k;$k++){
echo $_POST['textbox'.$i]; //something like this......?
}
?>
Please reply.
Use array notation instead.
<form method="post" action="somescript.php">
<input type="text" name="textbox[]" />
<input type="text" name="textbox[]" />
<input type="text" name="textbox[]" />
<input type="text" name="textbox][" />
.... and so on
</form>
When the form is submitted, $_POST['textbox'] will then be an array, and you can loop over it:
foreach ($_POST['textbox'] as $textbox) {
echo $textbox;
}
I just came across this issue because I had blocks of data that needed to be created dynamically and
echo $_POST["textbox$i"];
worked without the concatenation in it. Let me know if this is bad practice, it works in my situation though. The array way didn't work for me. Sorry for posting this on a 3 year old question. I'm not sure if that's bad practice. Thanks.

PHP contact form submitting 1's in all fields

I've recently developed a website for a freelance client of mine, and within their website is a Contact Form and a Request for Estimate form.
Once a day, both forms are being submitted and emailed to the designated email address. However, the submitted forms are clearly not from a real user, this is because all of the fields contain the number 1. For example, the name field will be Name:1, and the address field will be Address:1. The number 1 is repeated for all input text fields, and even radio and check box form fields.
Below is a copy of the PHP file that I am using to submit the Request for Estimate form.
<?
$subject="Associated Sennott Contractors Request For Estimate From:".$_GET['firstname'];
$headers= "From: ".$_GET['email']."\n";
$headers.='Content-type: text/html; charset=iso-8859-1';
mail("email#gmail.com", $subject, "
<html>
<head>
<title>Associated Sennott Contractors Request For Estimate</title>
</head>
<body>
<p><strong>Associated Sennott Contractors Request For Estimate</strong></p>
<p>
First Name: ".$_GET['firstname']." <br />
Last Name: ".$_GET['lastname']." <br />
Company Name: ".$_GET['company']." <br />
Address 1: ".$_GET['address1']." <br />
Address 2: ".$_GET['address2']." <br />
City: ".$_GET['city']." <br />
State: ".$_GET['state']." <br />
Zip: ".$_GET['zip']." <br />
Phone: ".$_GET['phone']." <br />
Fax: ".$_GET['fax']." <br />
Email: ".$_GET['email']." <br /><br />
<strong>Property Type:</strong><br />
Residential Single Family: ".$_GET['singlefamily']." <br />
Residential Multi-Family: ".$_GET['multifamily']." <br />
Residential Out-Building : ".$_GET['outbuilding']." <br />
Commercial Office: ".$_GET['commercial']." <br />
Retail Store: ".$_GET['retail']." <br />
Restaurant: ".$_GET['restaurant']." <br />
Industrial Building: ".$_GET['industrial']." <br /><br />
<strong>Requested Services:</strong><br />
Fire, Water or Wind Damage Restoration: ".$_GET['restoration']." <br />
Scope of Loss Estimate to Insurance Company: ".$_GET['scope']." <br />
Smoke Odor Remediation: ".$_GET['smoke']." <br />
Exterior Remodeling or Siding: ".$_GET['exterior']." <br />
Interior Remodeling: ".$_GET['interior']." <br />
Hardwood and Laminate Flooring: ".$_GET['flooring']." <br />
Finish Carpentry: ".$_GET['carpentry']." <br />
Demolition and Debris Removal: ".$_GET['demo']." <br />
Exterior Decks, Patios and Fencing: ".$_GET['patio']." <br />
Other: ".$_GET['other']." <br /><br />
<strong>Additional Information:</strong><br />
Message: ".$_GET['info']."
</p>
</body>
</html>" , $headers);
header( 'Location: thankyou.html' ) ;
?>
You can also view the PHP code by follow the link here: http://sennottcontractors.com/home-repair-estimate/quote-code.html
You can then view the HTML code for the actual form below:
<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Request An Estimate Form</title>
<script type="text/javascript">
function formSubmit()
{
document.getElementById("estimate-form").submit();
}
</script>
</head>
<body>
<fieldset>
<legend><h3>Request a Home Restoration Estimate</h3></legend>
<form id="estimate-form" name="estimate-form" target="_parent" method="get" action="quote.php" onsubmit='return formValidator()'>
<p><strong>Contact Information</strong></p>
<p>First Name: *<br />
<input type="text" size="40" name="firstname" id="firstname" /></p>
<p>Last Name: *<br />
<input type="text" size="40" name="lastname" id="lastname" /></p>
<p>Company Name:<br />
<input type="text" size="40" name="company" id="company" /></p>
<p>Address 1: *<br />
<input type="text" size="40" name="address1" id="address1" /></p>
<p>Address 2:<br />
<input type="text" size="40" name="address2" id="address2" /></p>
<p>City: *<br />
<input type="text" size="30" name="city" id="city" /></p>
<p>State: *<br />
<input type="text" size="5" name="state" id="state" /></p>
<p>Zip: *<br />
<input type="text" size="10" name="zip" id="zip" /></p>
<p>Phone: *<br />
<input type="text" size="20" name="phone" id="phone" /></p>
<p>Fax:<br />
<input type="text" size="20" name="fax" id="fax" /></p>
<p>Email: *<br />
<input type="text" size="40" name="email" id="email" /></p>
<br />
<p><strong>Property Type</strong> *</p>
<p><input type="checkbox" name="singlefamily" id="singlefamily"/> Residential Single Family</p>
<p><input type="checkbox" name="multifamily" id="multifamily"/> Residential Multi-Family <em>(Condominium, apartment, town house, ect)</em></p>
<p><input type="checkbox" name="outbuilding" id="outbuilding"/> Residential Out-Building <em>(Garage, shed, ect)</em></p>
<p><input type="checkbox" name="commercial" id="commercial"/> Commercial Office</p>
<p><input type="checkbox" name="retail" id="retail"/> Retail Store</p>
<p><input type="checkbox" name="restaurant" id="restaurant"/> Restaurant</p>
<p><input type="checkbox" name="industrial" id="industrial"/> Industrial Building</p>
<br />
<p><strong>Requested Services</strong> *</p>
<p><input type="checkbox" name="restoration" id="restoration"/> Fire, Water or Wind Damage Restoration</p>
<p><input type="checkbox" name="scope" id="scope"/> Scope of Loss Estimate to Insurance Company</p>
<p><input type="checkbox" name="smoke" id="smoke"/> Smoke Odor Remediation</p>
<p><input type="checkbox" name="exterior" id="exterior"/> Exterior Remodeling or Siding</p>
<p><input type="checkbox" name="interior" id="interior"/> Interior Remodeling</p>
<p><input type="checkbox" name="flooring" id="flooring"/> Hardwood and Laminate Flooring</p>
<p><input type="checkbox" name="carpentry" id="carpentry"/> Finish Carpentry</p>
<p><input type="checkbox" name="demo" id="demo"/> Demolition and Debris Removal</p>
<p><input type="checkbox" name="patio" id="patio"/> Exterior Decks, Patios and Fencing</p>
<p><input type="checkbox" name="other" id="other"/> Other</p>
<br />
<p><strong>Additional Information</strong><br />
Please provide any information regarding details of your home restoration project or additional information to your requested services.</p>
<p><textarea rows="10" cols="65" id="info" name="info"></textarea></p>
<button type="submit" id="submit" onclick="formSubmit()">Submit</button>
</form>
<p>* Required Fields</p>
</fieldset>
</body>
</html>
The Request an Estimate form that is using the PHP file and code mentioned above you can view by following the link here: http://sennottcontractors.com/home-repair-estimate/index.html
Again, both the Request an Estimate form and the Contact Form are being submitted once a day, everyday, with the number 1 in every form field.
My guess is that this may be an issue with the PHP file itself, or it may be an issue from the server side of the hosted website.
Please help!!!
There's nothing technically wrong with your form. You said the cause of the issue yourself: "... the submitted forms are clearly not from a real user ...". So the solution is to make your form anti-bot. See this question on the pro Webmasters site for how you can do this: Make your site anti-bot?
One part of this problem is that you need to use a form nonce or "token".
Form.php
<?php
session_start();
$_SESSION['token'] = md5(mt_rand() . unique_id('form', TRUE));
...
?>
<form>
<input type="hidden" value="<?php print $_SESSION['token']; ">
...
</form>
process.php
<?php
session_start();
if($_SESSION['token'] !== $_POST['token'])
{
die('They did not load the form!');
}
...
(validation)
...
$db->insert($record);
You're not doing any validation. What do you expect?
Anyone could just grab the form fields, create the URL (because you're using GET instead of POST), and submit it ad nauseum if they wanted to. What you're probably encountering is a bot trying to figure out if it can hijack your form to send emails where it wants to send them.
What you should do is switch to using POST and check the $_SERVER['HTTP_REFERER'] variable to make sure it's coming from your form (at least). You could also use a CAPTCHA, but those are becoming increasingly unreliable. You could take this further and use a validation class to set rules for each field and what kind of data is allowed to be in each one.
Forms are easily manipulated, so if you expect to have any integrity in your form submissions, you should be doing the validation on the server-side. Client-side validation doesn't hurt, but only use it for user experience purposes, not to ensure data integrity.

Adding multiple inputs to file php form submit

I have a form that looks like so:
<label for="fullpath"><span class="required">*Full Path of folder to change access:</span></label>
<input name="fullpath" id="it10" type="text" size="50" maxlength="50" />
<br />
<small>Example: g:\A\Folder or j:\Your\Folder</small><br />
<div class="bgdiff">
<label for="userpermissiongroup">User Permission Group to be changed:</label>
<input name="userpermissiongroup" type="text" id="it11" size="50" maxlength="50" />
<small>If Known...</small></div>
<br />
<label for="addreadaccess">Additional users requiring read access:</label>
<input name="addreadaccess" type="text" id="it12" size="15" maxlength="15" />
<br />
<small>AD Username</small><br />
<div class="bgdiff">
<label for="addauthoraccess">Additional users requiring author access:</label>
<input name="addauthoraccess" type="text" id="it13" size="12" maxlength="12" />
<br />
<small>AD Username</small></div>
<br />
<label for="removeaccess">Users to be removed from access:</label>
<input name="removeaccess" type="text" id="it14" size="12" maxlength="12" />
<br />
<small>AD Username</small><br />
<div class="bgdiff">
<label for="supervisor"><span class="required">*Data Steward, Program Manager, Project Lead, or Supervisor who can authorize access changes:</span></label>
<input name="supervisor" type="text" id="it15" size="30" maxlength="30" />
<br />
<small>AD Username</small></div>
<br/>
<label for="phoneapprover"><span class="required">*Phone number of approving official: </span></label>
<input name="phoneapprover" type="text" id="it16" size="30" maxlength="30" />
<br />
<small>999-999-9999</small><br />
</fieldset>
</div>
I would like to give users the option to add all of this info to this form more than 1x before submitting. (say 10x max) I have run a couple ideas through my head. 1 is using Javascript to create the new fields and then parse them with my php script somehow. 2 is put say 10 code snips just like the form above in the code and hide them until the user clicks ADD ANOTHER.
Each input needs to be unique as I am submitting this info thought a simple $_REQUEST php script. I understand how to do this with 1 input and a for each loop, but am not sure how to make it work with such a large amount of inputs, labels, etc...
<?php
foreach($_POST['newdata'] as $value) {
echo "$value <br />";
}
?>
Anyone have some suggestions on the best way to go about this? I am not sure adding his form via JS is the best idea, so just displaying the new info from a hidden div seems quicker and easier...
If you append [] to your form field names, PHP will take those fields and turn them into an array, e.g.
<input type="text" name="field[]" value="first" />
<input type="text" name="field[]" value="second" />
<input type="text" name="field[]" value="third" />
would produce the following $_POST structure:
$_POST = array(
'field' => array(
0 => 'first',
1 => 'second',
2 => 'third',
)
);
The alternative is to append incrementing numbers to each field name, as you duplicate the existing field sets for each new block. This provides a nice separation between blocks and allows you guarantee that related fields have the same numerical tag, but it does complicate processing.
It's not so difficult: main idea is to use IDs for each iteration, so your inputs will have unique names and will be processed without problems
for ($i=0;$i<10;$i++){
echo "<input name='removeaccess' type='text' id='it14_{$i}' size='12' maxlength='12' />";
}
So, you take your code of current set of inputs with lables and add to input names IDs, formed on each circle iteration. Be carefull about ' and "!

Form validation

I need to create a form that has many of the same fields, that have to be inserted into a database, but the problem I have is that if a user only fills in one or two of the rows, the form will still submit the blank data of the empty fields along with the one or two fields the user has filled in.
How can I check for the rows that have not been filled in and leave them out of the query?
or check for those that have been filled in and add them to the query. . .
The thank_you.php file will capture the $_POST variables and add them to the database.
<form method="post" action="thank_you.php">
Name: <input type="text" size="28" name="name1" />
E-mail: <input type="text" size="28" name="email1" />
<br />
Name: <input type="text" size="28" name="name2" />
E-mail: <input type="text" size="28" name="email2" />
<br />
Name: <input type="text" size="28" name="name3" />
E-mail: <input type="text" size="28" name="email3" />
<br />
Name: <input type="text" size="28" name="name4" />
E-mail: <input type="text" size="28" name="email4" />
<input type="image" src="images/btn_s.jpg" />
</form>
I am assuming that I could use javascript or jQuery to accomplish this, how would I go about doing this?
Thanx in advance for the help.
As others have said, it's bad practise to rely on javascript as your only form of validation. Look to javascript as a way to help your users submit valid data - but you should always validate on the server side. With that in mind, here's my suggestion:
<form method="post" action="thank_you.php">
Name: <input type="text" size="28" name="name1" />
E-mail: <input type="text" size="28" name="email1" />
<br />
Name: <input type="text" size="28" name="name2" />
E-mail: <input type="text" size="28" name="email2" />
<br />
Name: <input type="text" size="28" name="name3" />
E-mail: <input type="text" size="28" name="email3" />
<br />
Name: <input type="text" size="28" name="name4" />
E-mail: <input type="text" size="28" name="email4" />
<input type="image" src="images/btn_s.jpg" />
</form>
<?php
$num = 4; //Number of times the field is repeated
for($i = 1; $i <= $num; $i++){
if($_POST['name'.$i] != '' && $_POST['email'.$i] !=''){ //Only process if name and email are not blank
$thisname = $_POST['name'.$i];
$thisemail = $_POST['email'.$i];
//Your code here
}
}
?>
It's good to use javascript for form validation, but you shouldn't rely on it. The first thing to do is to check the values in $_POST in PHP, and make sure they're something valid looking (or at the very least, check that they're not "").
To check with javascript, you would put an onSubmit="..." in the form tag, which returns false if the form data is invalid (meaning "don't submit the form"). And you'd also probably want an alert, or you could modify the page somehow to indicate the problem. I'm not going to write out a form validation script for you though.
You can do JavaScript validation by using the submit button to call a JavaScript function instead of submitting the form. If the data passes your validation criteria, the JavaScript function can then submit the data. However, you should not rely completely on JavaScript validation. If the user has JavaScript disabled, their data will not be validated, so your PHP application must be robust enough to handle blank data. It isn't just blank data that you need to be concerned with, though. You need to validate the user input for garbage and sanitize the data before using it in the database.
I don't know the exact PHP syntax, but I'll write some pseudo-code that ought to do the trick. The basic idea is when you retrieve the $_POST values, you'll want to create a new hash that has values that are acceptable and then you can pass that hash to whatever methods needs to build out queries or whatever. The way I'll do this is to remove invalid values from the hash entirely, so it appears they were never there. Obviously, you can do this differently (mark them as invalid, etc).
$cleaned_args = array();
foreach ($_POST as $key => $value) {
if ($_POST[$key] != "" && is_valid_email($_POST[$key])) {
$cleaned_args[$key] = $_POST[$key];
}
make_db_call_or_whatever($cleaned_args);
where is_valid_email is a method that maybe PHP has or you have to write. You could even generalize the if clause into an is_valid($_POST[arg]) method if you want, but it depends on how complex the situation is.
Hopefully, this helps to give you an idea of how to do this. I think this will be easier than dynamically removing inputs with JavaScript before the form submission and, as mentioned, will be more secure than doing it only on the client side.

Categories