Get field names on unchecked checkboxes - php

I created an HTML application form for my employer so that applicant's can apply online. However, I'm running into some issues with the PHP bit. I'd like for it to send me an email containing ALL of the forms field names along with their values (even if the value is left blank). It needs to be in this specific format so that I can quickly 'convert' that data programmatically from the email into an HCL Notes form.
However, when a checkbox on my HTML form is left unchecked, it is not sent to the $_POST array at all, which then obviously ends up breaking the bit that converts it as it can't find the correct field names.
I know this is a strange and very specific issue, but does anyone have any ideas as to how I can go about this successfully?
My PHP code currently (removed the parameters at the top for privacy):
<?php session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Results</title>
</head>
<body>
<?php
//--------------------------Set these paramaters--------------------------
// Subject of email sent to you.
$subject = '';
// Your email address. This is where the form information will be sent.
$emailadd = '';
// Where to redirect after form is processed.
$url = '';
// Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty.
$req = '0';
$time = time();
// --------------------------Do not edit below this line--------------------------
$text = "Results from form:\n\n";
$space = ' ';
$line = '
';
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// handle the error accordingly with your other error checking
// or you can do something really basic like this
die('The code you entered was incorrect. Go back and try again.');
}
foreach ($_POST as $key => $value)
{
if ($key != "captcha_code"){
$j = strlen($key);
if ($j >= 40){echo "Name of form element $key cannot be longer than 39 characters";die;}
$j = 40 - $j;
for ($i = 1; $i <= $j; $i++)
{$space .= ' ';}
$value = str_replace('\n', "$line", $value);
$conc = "{$key}:$space{$value}$line";
$text .= $conc;
$space = ' ';
}
}
$text .= 'END OF APPLICATION';
mail($emailadd, $subject, $text, 'From: ');
echo '<script>alert("Application successfully submitted.");</script>';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
?>
</body>
</html>
Here's how the emails look, I need it to be just like this but with ALL fields regardless of if they have values or not:

Create an array that lists all the fields that should be in the email. Then instead of looping through $_POST, loop through that array. Display the corresponding $_POST field if it's filled in, otherwise show a blank value.
$fields = ['ReasonForReferral', 'FirstName', 'MiddleName', ...];
foreach ($fields as $field) {
$conc .= "$field: " . (isset($_POST[$field]) ? str_replace($_POST[$field], "\n", $line) : '') . $line;
}

Related

how to stop a non-numeric value encountered warning in php

Im trying to understand php a little better so Im making an application that converts different units. In my code I ask the user to enter a value for units of length, volume, and weight, then check a multiple checkboxes to convert what unit they want. I have everything working except for when I enter no input in a input box I get a warning A non-numeric value encountered in " ". So my question is how do I stop this warning from showing and just have it say you forgot to enter an input.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="convert_units2.php" method="POST">
<?php
//use from other php code
// require("form_functions.php");
//
// include("form_functions.php");
function generate_options_pulldown($options){
echo '<select name = "' . $options["title"] . '_unit">';
foreach($options["list"] as $opt){
echo '<option value="' . $opt . '">' . $opt . '</option>';
}
echo '</select>';
}
function generate_options_checkbox($options){
foreach($options["list"] as $opt){
echo '<lable><input type ="checkbox" name="'. $opt . '">' .$opt .'</label>';
}
}
function generate_conversion_form($units){
echo '<input type="text" size="10" name="' . $units["title"] . '_val"> ';
generate_options_pulldown($units);
echo "-->";
generate_options_checkbox($units);
}
//
$length_units = array("title"=>"length","list"=>array("meter","mm","cm","km"));
$volume_units = array("title"=>"volume","list"=>array("liter","oz","gallon"));
$weight_units = array("title"=>"weight","list"=>array("gram","mg","kg"));
if ($_SERVER["REQUEST_METHOD"] == "GET"){
generate_conversion_form($length_units);
echo "<p>";
generate_conversion_form($volume_units);
echo "<p>";
generate_conversion_form($weight_units);
echo '<p><input type="submit" value="Convert"></p>';
}
else{//Post
// var_dump($_POST);
$length_units_conversion_table = array("meter"=>1,"mm"=>1000,"cm"=>100,"km"=>0.001);
$from_unit = $_POST["length_unit"];
$val = $_POST["length_val"];
$meter = $val / $length_units_conversion_table[$from_unit];
foreach($length_units_conversion_table as $unit => $rate){
if(isset($_POST[$unit]) and $_POST[$unit] == 'on' )
printf("%s %s is %s %s<br>",$val, $from_unit,$meter * $rate, $unit);
}
echo '<br>';
$volumn_units_conversion_table = array("liter"=>1,"oz"=>33.8,"gallon"=>0.264);
$from_unit = $_POST["volume_unit"];
$val = $_POST["volume_val"];
$liter = $val / $volumn_units_conversion_table[$from_unit];
foreach($volumn_units_conversion_table as $unit => $rate){
if(isset($_POST[$unit]) and $_POST[$unit] == 'on' )
printf("%s %s is %s %s<br>",$val, $from_unit,$liter * $rate, $unit);
}
echo '<br>';
$weight_units_conversion_table = array("gram"=>1,"mg"=>1000,"kg"=>0.001);
$from_unit = $_POST["weight_unit"];
$val = $_POST["weight_val"];
$gram = $val / $weight_units_conversion_table[$from_unit];
foreach($weight_units_conversion_table as $unit => $rate){
if(isset($_POST[$unit]) and $_POST[$unit] == 'on' )
printf("%s %s is %s %s<br>",$val, $from_unit,$gram * $rate, $unit);
}
}
?>
</form>
</body>
</html>
you can check if the value is numeric using the function is_numeric() (https://www.php.net/manual/en/function.is-numeric.php)
if(!is_numeric($_POST["volume_val"])) { ...} )
For the specific case where no value has been set, you can either check that the value is not an empty string,
if( $_POST["volume_val"] == '') {...}
or convert an empty string to zero
$volume_val = empty($_POST["volume_val"]) ? 0 : $_POST["volume_val"];
For the empty field alert, you can use the required attribute in the input, so when you submit the form you'll get the "Field required" warning and the form won't submit.
Then, in the POST part of your code, you can test $_POST["length_unit"] for empty:
if (empty(trim($_POST["length_unit"])))
if this is true then ... you can either treat this as 0 or just send a warning.
You can also test for numeric value before processing:
if (is_numeric($_POST["length_unit"]))

Create a HTML form that submits from the fillers mail address to my email address

I have a HTML form on my site that submits using a very simple PHP script. As the script is written now I receive the form in my email address, the email that i receive has both the To and From fields as my email address. I.E if person1#email.com fills in the form I receive an email that says
From : my_email#email.com
To : my_email#email.com
I would like to change the script so that the From is the persons email address that filled in the form. I.E the mail I receive should be:
From : person1#email.com
To : my_email#email.com
This way I will be able to set up a automated reply on the mail account so that as a person fills in the form they will receive a welcome mail from my account.
Below is the HTML form code that I use:
<form action="../php/submit-candidate-form.php" enctype="multipart/form-data" method="post">
<p>1) What is your name?</p>
<input class="input" type="text" name="name" placeholder="Name" required>
<p>2) What is your E-Mail address?</p>
<input class="input" type="email" name="email" placeholder="Email" required>
<button class="main-button icon-button">Submit form</button>
And this is the simple php script that I use:
<?php
$subject = 'Email Subject line.';
$emailadd = 'my_email#email.com';
$url = 'http://www.example.com/thankyou';
$req = '0';
$text = "You have recieved the following message from the form:\n\n";
$space = ' ';
$line = '
';
foreach ($_POST as $key => $value) {
if ($req == '1') {
if ($value == '') {
echo "$key is empty";
die;
}
}
$j = strlen($key);
if ($j >= 20) {
echo "Name of form element $key cannot be longer than 20 characters";
die;
}
$j = 20 - $j;
for ($i = 1; $i <= $j; $i++) {
$space .= ' ';
}
$value = str_replace('\n', "$line", $value);
$conc = "{$key}:$space{$value}$line";
$text .= $conc;
$space = ' ';
}
mail($emailadd, $subject, $text, 'From: '.$emailadd.'');
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
?>
Just change
mail($emailadd, $subject, $text, 'From: '.$emailadd.'');
to
mail($emailadd, $subject, $text, 'From: '.$_POST['email'].'');
As i see, you are using same variable in place of "To" and "From". If you want two different emails so you have to change them like this:
$from_email = "person1#email.com";
mail($emailadd, $subject, $text, 'From: '.$from_email.'');
Here, you can add the email you want in $from_email.

How to validate php if form is filled

//So i have a php validation external and a html file. I'm trying to validate if //the input boxes are filled out correctly... so far i have one but I can't get it //to run and i tried testing it out doesn't work... do i need to download //something or is my code completely wrong. I just trying to check if its empty and if it has at least 3 characters
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cal5t</title>
</head>
<body>
<?php
$title= $_REQUEST["title"];
if ($title == "" or >3 ) {
echo "<p>5please!</p>";
?>
</body>
</html>
You are probably looking for something like:
if (($title == "") or (strlen($title) < 5))
{
echo "<p>5please!</p>";
}
if(!empty($title= $_POST['title']) && strlen($title) > 5){
echo "valid: $title";
} else {
echo "incorrect title: '$title'";
}
Also, its beter to use $_POST or $_GET over $_REQUEST.
I think you're looking for:
if(strlen($title) < 5){
echo '<p>The title you entered is not long enough.</p>";
}
You can make sure there is a value with the isset() function.
requird validation
$title = trim($_POST['title']); // it will remove stat and end spaces
if(strlen($title) <= 0)
{
echo "Title Field is required";
}

I need to iterate through multiple fields and have them inserted into my MySQL database

Ok, I'm really stuck. But I think I'm headed in the right direction. the script that calls this script has multiple fields which are generated dynamically by PHP. I need some way of looping through them and checking if they're set to avoid any undefined variables, and then once I know that they're all set and checked for validity inserting them into the MySQL table passwords. I could really use your help on this one guys.
<?php
require_once('/session/session.php');
require_once('auth/auth.php');
require_once('/MySQLi/mysqliConnect.php');
require_once('check_fields_function.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<!-- Copyright 2015 Brock Lynch -->
<?php $page = "passwords"; ?>
<?php require_once('/headerFooter/docHead.php'); ?>
<body>
<?php require_once('/headerFooter/header.php');?>
<div id="boxWrapper"> <!-- beginning of boxWrapper -->
<?php require_once('question_nav.php'); ?>
<div id="display_categories">
<?php
// This is just for reference: check_fields($pattern,$post,$minlength,$maxlength,$name_of_field)
$numOfFields = $_POST['numOfFields'];
for($z = 1;$z <= $numOfFields;$z++) {
if(isset($_POST['password_input$z']) && isset($_POST['group_input$z']) && isset($_POST['belongs_input$z']) && isset($_POST['name_input$z']) && isset($_POST['choice$z'])) {
$password[$z] = check_fields("/([[:alnum:]\!\#\#\$\%\^\&\*\*\(\)\-\_\+\=\[\]\;\'\:\"\'\<\>\?\/\`\~])+/",$_POST['password_input$z'],6,50,'Password$z');
$password_group[$z] = check_fields("/^[a-zA-Z \'\"]+$/",$_POST['group_input$z'],1,50,'Password Group$z');
$password_belongs_to[$z] = check_fields("/^[a-zA-Z \'\"]+$/",$_POST['belongs_input$z'],1,50,'Belongs To$z');
$password_name[$z] = check_fields("/^[a-zA-Z \'\"]+$/",$_POST['name_input$z'],1,50,'Password Name$z');
$changes_periodically[$z] = check_fields("/^[0-1]+$/",$_POST['choice$z'],1,50,'Changes Periodically$z');
}
else {
$password[$z] = false;
$password_group[$z] = false;
$password_belongs_to[$z] = false;
$password_name[$z] = false;
$changes_periodically[$z] = false;
}
}
// Iterate through each array and if they are all set, set the master password_setting to true
function check_all_arrays($fieldArray)
{
global $numOfFields;
$p = 0;
if(isset($fieldArray)) {
foreach($fieldArray as $test) {
echo "Yeah, this seems to be working";
if($test == true) {
$p++;
}
}
}
else {
return false;
}
if($p == $numOfFields) {
return true;
}
else {
return false;
}
}
if(check_all_arrays($password) == true && check_all_arrays($password_group) == true && check_all_arrays($password_belongs_to) == true && check_all_arrays($password_name) == true && check_all_arrays($changes_periodically) == true) {
echo "Got passed master checks, this is good";
// Encrypt the users password before entering it into the database.
// Clean the data before inserting it into the database.
$instance = PasswordCrypt::createWithNewPassword($_POST['password_input']);
$password_pass = mysqli_escape_string($mysqli,$instance->encodePassword($_POST['password_input']));
$token_pass = mysqli_escape_string($mysqli,$instance->getToken());
$key_pass = mysqli_escape_string($mysqli,$instance->getKey());
$group = mysqli_escape_string($mysqli,$_POST['group_input']);
$belongs_input = mysqli_escape_string($mysqli,$_POST['belongs_input']);
$name_input = mysqli_escape_string($mysqli,$_POST['name_input']);
$password_save = "INSERT INTO passwords (password_id,customer_id,password_not_key,token_pass,key_pass,password_group,
changes_periodically,security_status,belongs_to,password_name)VALUES('','" . $_SESSION['customer_id'] . "','" . $password_pass . "','". $token_pass . "','" . $key_pass . "','" . $group . "','" . $choice . "','','" . $belongs_input . "','" . $name_input . "')";
mysqli_query($mysqli,$password_save) OR DIE(mysqli_error($mysqli));
// Echo confirmation message to user
echo "<div style='text-align:center;'>You have successfully stored 1 password</div>";
?>
<form action="myPassword.php">
<button input="submit_back">Back</button>
</form>
<?php
}
else {
// Tell them to use only letters in fields besides the password field.
echo "<div style='text-align:center;'>All fields are required except changes periodically. Password field may have letters, numbers, and special characters and must be at least 6 characters. All other fields may only have letters. Thank you</div>";
?>
<form action="myPassword.php">
<button type="submit">Go Back</button>
</form>
<?php
}
?>
</div> <!-- End of display categories -->
</div> <!-- End of boxWrapper div -->
</body>
<div class="bigBoldFont"></div>
<?php require_once('headerFooter/footer.php'); ?>
</div><!-- end of boxWrapper -->
</body>
</html>
What you have now will work if you change the single quotes on all the $_POST variables to double quotes.
E.g. change isset($_POST['password_input$z']) to isset($_POST["password_input$z"])
You could also make it a little easier to read by wrapping the variable in curly braces {}. isset($_POST["password_input{$z}"])

PHP mailing database search

I made a PHP page that looks up Constant Contact e-mail addresses in a database and returns a table listing their name, e-mail address, and mailing list they are in. You enter the addresses here: Contact Lookup Tool along with your Constant Contact user name and password.
For some reason, only the last row of the results page has a list of mailing lists. The other ones have the word "Array," which I stripped out, so now those rows are blank. Here is a screen shot of what I mean:
http://www.advantage-computer.com/images/ScreenCap.png
They're all in a list, though. Here's the code for search.php. The form submits to that file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>List of Contacts</title>
<style type="text/css">
.hdr
{
margin-bottom: 0px;
padding-bottom: 0px;
}
</style>
</head>
<body>
<table width="75%">
<tr>
<td class="hdr">Name</td>
<td class="hdr">E-mail address</td>
<td class="hdr">List(s)</td>
</tr>
<tr>
<td colspan="3">
<hr style="padding:0; margin:0">
</td>
</tr>
<?PHP
require_once('./class.cc.php');
/*VARIABLES*/
$cc = new cc($_POST['userName'], $_POST['password']);
if($cc)
{
$strEmails = $_REQUEST['emails'];
$aryEmails = explode("\n", $strEmails);
$page = (isset($_GET['page'])) ? $_GET['page'] : 'lists';
$lists = $cc->get_lists($page);
/*METHODS*/
foreach ($aryEmails as $email)
{
if($lists)
{
foreach($lists as $k => $v)
{
$list = $v['Name'];
$page = (isset($_GET['page'])) ? $_GET['page'] : 'members';
$members = $cc->get_list_members($v['id'], $page);
if($members)
{
foreach($members as $k => $v)
{
if($v['EmailAddress'] == $email)
{
$strLists .= $list . ", ";
}
}
}
}
}
$strLists = str_replace("Array", "", $strLists);
$strLists = substr($strLists, 0, -2);
$contact = $cc->query_contacts(trim($email));
if($contact)
{
$strName = $contact['Name'];
if(is_array($strName))
{
$strName = "";
}
echo
(
"<tr><td>".$strName."</td>".
"<td>".$contact['EmailAddress']."</td>".
"<td>".$strLists."</td></tr>"
);
}
else
{
echo("<tr><td colspan='3'>Could not find {$email}.</td></tr>");
}
}
}
else
{
echo "Invalid user name or password";
}
?>
</table>
</body>
</html>
Here is the class.cc file: http://advantage-computer.com/tools/class.cc.txt
Firstly, you should break out of that loop once you have matched a record, and you are not using $k so we can remove that from the loop too, eg:
if($members)
foreach($members as $v)
if($v['EmailAddress'] == $email)
{
$strLists .= $list . ", ";
break;
}
I would also add a line in there to debug whats in the $list variable when it is an array:
if (is_array($list))
var_dump($list);
I would say that whatever is setting "$_list['content']['ContactList']['Name']" in your class is not doing it correctly.
Thanks everyone for the replies. My brother found the problem. He changed
foreach ($aryEmails as $email){
...
}
to
foreach ($aryEmails as $tmpEmail){
$email = rtrim($tmpEmail);
...
}
It appears that it only matched the last line in the text area because there were still carriage returns in the e-mail array left over from the text area. He added rtrim to remove them.

Categories