I have a form where users can enter the names and emails addresses of colleagues. They are not required to enter anything. However if a name is entered then the email address is required.
<form>
1st name <input type="text" name="name_1" value"" />
1st email <input type="text" name="email_1" value"" />
2nd name <input type="text" name="name_2" value""/>
2nd email <input type="text" name="email_2" value""/>
</form>
I can already make certain fields required using the function below. I think I could use an if else statement to check if the 1st name had a value then make the 1st email required. However the form has twenty potential name / email pairs.
What i'm after is advice about the sort of thing I should be trying to do this rather than a complete solution. I appriciate this a bit of a vague question but I'm very new to PHP and am having difficulty searching for a solution.
function check_required_fields($required_array) {
$field_errors = array();
foreach($required_array as $fieldname) {
if (!isset($_POST[$fieldname]) || (empty($_POST[$fieldname]) && !is_numeric($_POST[$fieldname]))) {
$field_errors[] = $fieldname;
}
}
return $field_errors;
}
As long as you are consistent with naming your fields like name_1, you can extract the number from the array keys with substring operations after _ and look for a comparable value in email_.
foreach ($_POST as $key => $value) {
// If it is a name field and isn't empty
if (strpos($key, 'name_') === 0 && !empty($_POST[$key])) {
// The email field is email_ and the number (which comes after the 5th character in name_num)
$namenumber = substr($key, 5);
$emailfield = 'email_' . $namenumber;
// Append the email requirement onto $field_errors if it's empty in $_POST
if (empty($_POST[$emailfield])) {
$field_errors[] = $emailfield;
}
}
}
Related
I have a simple PHP form that I'd like to improve validation to help fight empty form submissions from bots.
I have the following array that houses input names from another page.
$expected = array('Project-Inquiry','Name','Company-Name','Phone-Number','Email');
I'd like to verify that these elements, in fact, do contain content, as they're already verified with JS on the previous page. JS is only good when it's enabled, so I'd like to add an extra layer of validation here for when it's disabled.
I tried the following:
$expected = array_filter($expected);
if (!empty($expected)) {
// Do Something
}
And I have also tried the following:
$error = false;
foreach($expected as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
// Do Something
}
I seem to be falling short. Any suggestions?
If you want to fight against bots
Create a hidden input that human doesn't see and bots will fill it. You need to check that input before doing anything. If that input filled, it means that form sent by bot not human.
Create a session with current time when you are showing form, when post happening check the time difference. if it is less than 3 sec it's a bot.
use captcha system.
If you want to validate inputs
Don't do validation like what you did on your question. You should try to validate each one of them with proper validation method. for example how you should validate email is completely different from name.
for example do this for email:
$email = (isset($_POST['email']) && is_string($_POST['email']))? trim($_POST['email']) : '';
$email_error = (filter_var($email,FILTER_VALIDATE_EMAIL))? true : false;
for name is different:
$name = (isset($_POST['name']) && is_string($_POST['name']))? trim($_POST['name']) : '';
$name_error = (strlen($name)>20 || strlen($name)<3)? true : false;
You can add more filter to my examples.
Have you considered about using a library to validate?
I recommend you to use https://laravel.com/docs/5.5/validation, so you can validate more complex rules also, and it is very clear.
Let your expected data be array be
$expected = ['name', 'email', 'mobile'];
let form post values be $_POST
foreach($_POST as $key => $value) {
if (empty($value) && in_array($key, $expected)) {
if ($value=='') {
echo $key. ' is should not be empty'."<br/>";
}
}
}
you can get result as expected
HTML FORM
<form action="" method="post">
Name <input type="text" name="name"><br>
email <input type="text" name="email"><br>
mobile<input type="text" name="mobile">
<input type="submit" value="Submit">
</form>
I have a form with login and registration.
My Form
<form method="POST" action="login.php">
<input type="text" name="mail" value="Input your email"/>
<input type="submit" value="Check"/>
</form>
If someone enters their email, I want to check if there is an # in the address. I have tried using an array, but that is not working.
You can use the php function strpos http://php.net/strpos
if(strpos($myEmailPostVariable, '#') === FALSE) {
// do things here to say it failed
}
If you are fixed on using an array then you could use explode http://php.net/explode
$parts = explode('#', $myEmailPostVariable);
if(count($parts) != 2) {
// do things here to say it failed
}
Keep in mind the array way is not great as searching a string is easier and faster and is more readable.
As #jeroen has suggested if you want to validate the email then using filter_input() is the best...
if(filter_input(INPUT_POST, 'mail', FILTER_VALIDATE_EMAIL) === FALSE) {
// do things here to say it failed
}
I am working on a project for my class. We never went over arrays and i am trying to figure out how to use an associate on with user inputs. I have no idea if I am on the right track. I will eventually need to sort my array with key values. But first off it would be great if I could get some feedback on what I have here. I keep getting an error message ": syntax error, unexpected 'each' (T_STRING), expecting "
And i even getting the values for my array correctly and associating them with the array?
I struggle with arrays. I am also new to php.
<HTML>
<HEAD>
<TITLE>Student Form</TITLE>
</HEAD>
<BODY>
<FORM METHOD="post" ACTION="final_project.php">
<P>Please enter your name: <INPUT TYPE="text" NAME="txtname" SIZE= 10></P>
<P>Please enter your id: <INPUT TYPE="text" NAME="txtid" SIZE= 10></P>
<P>Please enter your address: <INPUT TYPE="text" NAME="txtaddress" SIZE= 10></P>
<P>Please enter your cell phone number: <INPUT TYPE="text" NAME="txtcell" SIZE= 10></P>
<P>Please enter your Major: <INPUT TYPE="text" NAME="txtmajor" SIZE= 10></P>
<P>Please enter your E-mail address: <INPUT TYPE="text" NAME="txtemail" SIZE= 10></P>
<P><INPUT TYPE="submit" NAME="submit" VALUE="Submit"></P>
</FORM>
<?php
$txtname = $_POST['txtname'];
$txtid = $_POST['txtid'];
$txtaddress = $_POST['txtaddress'];
$txtcell = $_POST['txtcell'];
$array = array(txtname=>$txtname, txtid=>$txtid, txtaddress=>$txtaddress, txtcell=>$txtcell);
for each ($txtid as $key => $array){
echo "Your first name is ".$txtname.", id number is ".$txtid[$key].", your address is ".$txtaddress.", phone number is ".$txtcell.".";
}
?>
</BODY>
</HTML>
Thanks
Your scripts contain syntax error, for each should be foreach . Array index txtname should be 'txtname' and so on.
Finally in foreach you have used a variable not an array. I think it should be an array ($array). Change your scripts
From
$array = array(txtname=>$txtname, txtid=>$txtid, txtaddress=>$txtaddress, txtcell=>$txtcell);
for each ($txtid as $key => $array){
echo "Your first name is ".$txtname.", id number is ".$txtid[$key].", your address is ".$txtaddress.", phone number is ".$txtcell.".";
}
to
$array = array('txtname'=>$txtname, 'txtid'=>$txtid, 'txtaddress'=>$txtaddress, 'txtcell'=>$txtcell);
foreach ($array as $value){
echo $value.'</br>';
}
There's a few modifications you should consider. It's a good idea to check the $_POST values to ensure that they exist before trying to use them. It's also a good idea to sanitize any user input you receive to make sure you protect yourself from possible malicious content. Finally, if you save the posted values with the field names, you can reference them easily to create a sentence without having to loop through the array using for, foreach, while or do-while.
<?php
/*
* Array contains the desired fields. You could add txtmajor or txtemail
* for example in the future if you desire. This is an additional safety
* check as well. You should never blindly save all $_POST fields as a
* user with malicious intent or a third party may have modified the
* initial request to contain extra data.
*/
$fields = array("txtname", "txtid", "txtaddress", "txtcell");
// Ensure this was a POST request and not the initial GET request.
if(strtolower($_SERVER['REQUEST_METHOD']) === "post") {
// Create an array to store the posted values
$values = array();
/*
* Loop through the $fields array you created above and make sure
* the post array contains the key. This will ensure that you don't
* leave a required field out or make a typo in your HTML.
*/
foreach($fields as $value) {
/*
* If the key exists and the value was not left blank, strip it
* for any malicious tags, trim off leading and trailing white
* space and save it in your $values array with the field name
* as the key. This makes it easy to reference the value in the
* future.
*
* Note: This is minimal sanitation. You should always take
* check your user's input especially if you plan to
* redisplay it on the screen at a later time or store
* it in a database.
*/
if(array_key_exists($value, $_POST) && !empty($_POST[$value])) {
$values[$value] = trim(strip_tags($_POST[$value]));
} else {
/*
* If the key doesn't exist, there may be a typo in your HTML
* or the returned content may have been manipulated by a third
* party person, proxy or service. Whatever the case, kill the
* script and render the plain HTML.
*/
exit;
}
}
/*
* Finally, since you know the field names and you want to use the
* information in a single sentence, there's no point in looping back
* through the array. Reference the values and echo the sentence...
*/
echo "Your first name is " . $values['txtname'] . ", id number is " . $values['txtid'] . ", your address is " . $values['txtaddress'] . ", phone number is " . $values['txtcell'] . ".";
}
?>
I want to make email template management.I have a column additional_data where I'm inserting two input fields values (Subject and Body.)
Subject value contain simple text and body value contain HTML and other templates related materials.
My PHP Code
$additional_data = array();
// getting data again for update to fill up form
$editdata = ($id && $display == 'Update') ? $db->getRow("SELECT * FROM `{$db_table}` WHERE `nli_id`='$id'") : FALSE;
if(!is_array($editdata['additional_data']) && count($editdata['additional_data']))
$additional_data = json_decode($editdata['additional_data'], TRUE);
p($additional_data, 'Additional Data');
// setting template vars
if(count($additional_data))
{
foreach($additional_data as $key => $value)
{
$tmpl->setvar($key, $value);
} // foreach ends
unset($key);
unset($value);
} // if ends
HTML Code
<input type="text" class="span6" autocomplete="off" name="subject" id="subject" value="{var name='additional_data'}">
<textarea name="body" class="span6 autogrow">{var name='additional_data'}</textarea>
So let me know where I am wrong or is there any other way to solve the problem.
Yes, this "smarty" looks very strange. I would say it's Vlib:
http://en.wikipedia.org/wiki/VlibTemplate
But anyway, in you PHP code you are going trough $additional_data array and creating variables from elements of that array. Element key is name of new template variable and element value is tmpl. variable value.
So, in your template code "additional_data" does not exist. Print out that $additional_data array from your PHP code to see what elements are you really passing to template engine.
I have checkboxes with the following names:
chk-cloud-a
chk-cloud-b
and so on...
chk-dco-a
chk-dco-b
and so on...
How do I validate after form submission such that:
Atleast one element from the checkboxes with name starting with chk-cloud or chk-dco must be ticked?
I hope someone can help me with this.
Cheers!
If they're checkboxes then all you really care about is whether or not they have a value. What that value is is not significant.
All you need to do is check that there are elements in the $_GET or $_POST (depending on form submission method) that contain fields of that name.
if (array_key_exists ('chk-cloud-a ', $_POST)) {
// Do what should happen of that checkbox is checked
}
If the problem is that you have multiple similar checkboxes then you might want to consider grouping them together in an array. This is done by using square bracket notation in the field name:
<input type="checkbox" value="1" name="chk-cloud[a]" />
<input type="checkbox" value="1" name="chk-cloud[b]" />
<input type="checkbox" value="1" name="chk-cloud[c]" />
<input type="checkbox" value="1" name="chk-cloud[d]" />
You can use a loop to process such a group
foreach ($_POST [chk-cloud] as $key => $value) { // We're really only interested in the key
handleCheckbox ($key) // handleCheckbox is some function you've wrote
}
Or
foreach (array_keys ($_POST [chk-cloud]) as $key) { // Logically the same as above
Just use preg_match or strpos to check if any key in POST matches Your requirements. Personally i would make subarray of these elements and just check if its empty.
try like this:
function checkBoxValidate(){ //method to test checkbox
$array = array('a','b','c','d', ....); // make array for each checkbox name
foreach ($array as $a){
if((isset($_REQUEST['chk-cloud-'.$a]) || isset($_REQUEST['hk-dco-'.$a])) && ($_REQUEST['chk-cloud-'.$a] == 'check_value' || $_REQUEST['hk-dco-'.$a] == 'check_value' ) ){
return true;
}
}
return false; //return no check box was checked
}