function that cleans values passed through $_POST before it submits it - php

I'm writing a function that takes the content from $_POST, inserts it in a string and then returns the resulting string
To the question "What is your favorite color?" the user inputs blue
To the question "What is your favorite animal?" the user inputs dog
$content = "The visitor's favorite color is {color}";
$content = sentenceBuilder($content);
$content = "The visitor's favorite animal is a {animal}";
$content = sentenceBuilder($content);
function sentenceBuilder($content){
global $_POST;
foreach($_POST as $key => $value){
if($key=='color'){
$content = preg_replace("/\{($key+)\}/", $value, $content);
}
if($key=='animal'){
$content = preg_replace("/\{($key+)\}/", $value, $content);
}
}
return $content;
}
This returns "The visitor's favorite color is blue" and "The visitor's favorite animal is a dog." If they leave the color element blank, it returns "The visitor's favorite color is " and "The visitor's favorite animal is a dog". If they leave both elements blank, it returns 2 incomplete sentences.
So, I tried to modified it to say so that if $value was empty, the function would just skip it and move on to the next (as this uses every form element that moved over in the $_POST)...
if($key=='color' && $value!=''){
$content = preg_replace("/\{($key+)\}/", $value, $content);
}else{
$content ='';
}
if($key=='animal' && $value!=''){
$content = preg_replace("/\{($key+)\}/", $value, $content);
}else{
$content ='';
}
With this added, the result I get is blank. No sentences or anything. Even if they fill out the elements, the result is still blank with this code added.
So I tried this instead.
function sentenceBuilder($content){
global $_POST;
foreach($_POST as $key => $value){
if(isset($value) && $value!=''){
if($key=='color'){
$content = preg_replace("/\{($key+)\}/", $value, $content);
}
if($key=='animal'){
$content = preg_replace("/\{($key+)\}/", $value, $content);
}
else{
$content = '';
}
}
return $content;
}
This yielded the same results.
TLDR;
I want to be able to have this function replace content with values that are not empty with a sentence. The ones that are empty, I would like for the content to be not displayed.
UPDATE
I got the code to work. Had to redesign it to make it happen though.
<?php
if(isset($_POST)){
$content = "The visitor's favorite color is {color}";
echo sentenceBuilder($content);
?> <br/> <?php
$content = "The visitor's favorite animal is a {animal} from {land}";
echo sentenceBuilder($content);
?> <br/> <?php
$content = "The visitor is from {land}";
echo sentenceBuilder($content);
?> <br/> <?php
$content = "The visitor is from Iowa";
echo sentenceBuilder($content);
?> <br/> <?php
$content = "The visitor is from {state}";
echo sentenceBuilder($content);
}
function sentenceBuilder($content){
preg_match("/\{(.*?)\}/", $content, $checkbrackets);
if(!empty($checkbrackets)){
$gettext = str_replace('{', '', $checkbrackets[0]);
$gettext = str_replace('}', '', $gettext);
if(array_key_exists($gettext,$_POST)){
if(!empty($_POST[$gettext])){
$content = preg_replace("/\{($gettext+)\}/", $_POST[$gettext], $content);
}else{
$content = '';
}
}
}
return $content;
}
?>
<form method="post" action"sentencebuilder.php">
<input type="text" name="color" />
<input type="text" name="animal" />
<input type="text" name="land" />
<input type="submit" />
</form>
Thanks for the help Guys. Enter it in and you'll see what I was going for. I am currently working on it to change additional brackets that exist within the question.

Use this code, definitely that's the solution of you problem:-
<?php
$main_content = array();
if(isset($_POST['submit'])) {
unset($_POST['submit']);
$main_content['color'] = "The visitor's favorite color is {color}";
$main_content['dog'] = "The visitor's favorite dog is {dog}";
$main_content['school'] = "The visitor's favorite school is {school}";
$formData = array_filter($_POST);
if(!empty($formData)) {
echo sentenceBuilder($formData, $main_content);
}
}
function sentenceBuilder($formData=null, $main_content=null){
$newContent = "";
foreach ($formData as $key => $value) {
$newVal = "";
$newVal = preg_replace("/\{($key+)\}/", $value, $main_content[$key]);
$newContent .= $newVal.". <br/>";
}
return $newContent;
}
?>
<form method="post" action="#">
<input type="text" name="color" placeholder="color" />
<input type="text" name="dog" placeholder="dog" />
<input type="text" name="school" placeholder="school" />
<input type="submit" name="submit" />
**OUTPUT:**
The visitor's favorite color is RED.
The visitor's favorite dog is BULLDOG.
The visitor's favorite school is CAMPUS SCHOOL.

Hope this will help you
<?php
$content = '';
echo $content = sentenceBuilder($content);
function sentenceBuilder($content){
global $_POST;
$content = "The visitor's favorite color is {key}";
foreach($_POST as $key => $value){
if (isset($_POST[$key]) && ($_POST[$key] != '')) {
$content = preg_replace("/\{(key+)\}/", $value, $content);
}
}
if(strpos($content, '{key}') !== false)
return $content='';
else
return $content;
}?>
<form method="post">
<input type="text" name="color" />
<input type="text" name="gh" />
<input type="submit" />
</form>
If you want first color check then try
if (isset($_POST['color']) && ($_POST['color'] != '')) {
$content = preg_replace("/\{(key+)\}/", $value, $content);
}
elseif (isset($_POST[$key]) && ($_POST[$key] != '')) {
$content = preg_replace("/\{(key+)\}/", $value, $content);
}

I understand that you really need the function and not just 'inline' code. In that case, this function will do the trick (if I understand your wishes correctly).
In the comments of the code you will find some guidance.
Hope this helps :)
function sentenceBuilder($content = '')
{
preg_match_all('/\{(.*?)\}/', $content, $matches); // Find all {...} matches
$valueMissing = false; // If a POST value is missing, this will be set to TRUE
if(isset($matches[0]) && !empty($matches[0])) { // Braces are found
foreach($matches[0] as $id => $match) {
// Note the usage of $matches[0] vs $matches[1]: $matches[0] = '{animal}','{land}', while $matches[1] = 'animal','land' without the braces
$key = (isset($matches[1][$id]) ? $matches[1][$id] : false); // Quick if/else
$postValue = ($key != false ? (isset($_POST[$key]) ? $_POST[$key] : false) : false); // Quick if/else (double)
if($postValue == false) {
$valueMissing = true;
break; // Leave the foreach loop
} else {
$content = str_replace($match, $postValue, $content); // Replace the value
}
}
if($valueMissing) {
return ''; // Return empty string (braces found, but not all values were found in the POST)
}
}
return $content; // Return the content
}
-------- ORIGINAL POST --------
The preg-replace seems a bit overkill for this, isset() and empty() will do the trick.
<?php
if(isset($_POST) && !empty($_POST))
{
// Start with empty content
$content = '';
// Only add content (.=) when the field is set (posted) and NOT empty
if(isset($_POST['color']) && !empty($_POST['color'])) {
$content .= "The visitor's favorite color is " .$_POST['color']. "<br/>";
}
if(isset($_POST['animal']) && isset($_POST['land']) && !empty($_POST['animal']) && !empty($_POST['land'])) {
$content .= "The visitor's favorite animal is a " .$_POST['animal']. " from " .$_POST['land']. "<br/>";
}
if(isset($_POST['state']) && !empty($_POST['state'])) {
$content .= "The visitor is from " .$_POST['state']. "<br/>";
}
if(isset($_POST['number']) && !empty($_POST['number'])) {
$content .= "The visitor's favorite number is " .$_POST['number']. "<br/>";
}
// If there is some content, show it
if(!empty($content))
{
echo $content;
}
else
{
echo "Please fill in some values!";
}
}
else
{
?>
<form method="post" action"<?php echo $_SERVER['PHP_SELF']; ?>">
Favorite color: <input type="text" name="color" /><br />
Favorite animal: <input type="text" name="animal" /><br />
from land: <input type="text" name="land" /><br />
<br />
Favorite number: <select name="number">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="submit" value="SEND this form" />
</form>
<?php }
And you can use HTMLPurifier (for example) to 'filter' any user-input data. http://htmlpurifier.org/

This works.
<?php
if(isset($_POST)){
$content = "The visitor's favorite color is {color}";
echo sentenceBuilder($content);
?> <br/> <?php
$content = "The visitor's favorite animal is a {animal} from {land}";
echo sentenceBuilder($content);
?> <br/> <?php
$content = "The visitor is from {land}";
echo sentenceBuilder($content);
?> <br/> <?php
$content = "The visitor is from Iowa";
echo sentenceBuilder($content);
?> <br/> <?php
$content = "The visitor is from {state}";
echo sentenceBuilder($content);
}
function sentenceBuilder($content){
preg_match("/\{(.*?)\}/", $content, $checkbrackets);
if(!empty($checkbrackets)){
$gettext = str_replace('{', '', $checkbrackets[0]);
$gettext = str_replace('}', '', $gettext);
if(array_key_exists($gettext,$_POST)){
if(!empty($_POST[$gettext])){
$content = preg_replace("/\{($gettext+)\}/", $_POST[$gettext], $content);
}else{
$content = '';
}
}
}
return $content;
}
?>
<form method="post" action"sentencebuilder.php">
<input type="text" name="color" />
<input type="text" name="animal" />
<input type="text" name="land" />
<input type="submit" />
</form>

Related

Want to save all values of checkbox in csv (php), unfortunately only one gets saved

I have a form and I am exporting the answers into a csv file. Radio buttons working fine. The value of the textarea is not getting exported and the value of all selected checkboxes is also not exported. Only one value gets exported. What I am doing wrong? Please help!
My code index.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
include 'php/create-csv.php';
?>
<!DOCTYPE html>
<html lang="de">
<body>
<form method="post" action="" name="contactform">
<div class="control-group">
<label class="control control-checkbox"> Insurances
<input type="checkbox" value="insurances" name="topic[]"/>
<div class="control_indicator"></div>
</label>
<label class="control control-checkbox"> Savings
<input type="checkbox" value="savings" name="topic[]"/>
<div class="control_indicator"></div>
</label>
<label class="control control-checkbox"> Other
<input type="checkbox" value="other_topic" name="topic[]"/>
<div class="control_indicator"></div>
</label>
<div id="textarea">
<textarea rows="4" cols="40" name="other"></textarea>
</div>
</div>
<input type="submit" name="submit" value="Send" id="submit"
class="submit-btn">
<?php
if (isset($errors)) {
foreach ($errors as $error) {
echo $error;
}
}
?>
</form>
</body>
</html>
Code for create-csv.php
<?php
if (isset($_POST['submit'])) {
$topic = isset($_POST['topic']) ? $_POST['topic'] : '';
$rating = isset($_POST['rating']) ? $_POST['rating'] : '';
$other = isset($_POST['other']) ? $_POST['other'] : '';
if ($rating == '') {
$errors[] = '<div class="notification error clearfix"><p>Please select a number.</p></div>';
}
if ($topic == '') {
$errors[] = '<div class="notification error clearfix"><p>Please select at
least one topic.</p></div>';
}
if (!isset($errors)) {
if(!empty($_POST['topic'])) {
foreach($_POST['topic'] as $value){
echo $value;
}
}
$header = "Rating,Topics,Other\n";
$data = "$rating, $topic, $other\n";
$fileName = dirname(__DIR__) . "/results.csv";
if (file_exists($fileName)) {
file_put_contents($fileName, $data, FILE_APPEND);
} else {
file_put_contents($fileName, $header . $data);
}
header("Location: thankyou.html");
exit;
}
}
First of all, there's no "rating" in this form you posted. Maybe it is the radio button you mentioned before.
Also, it seems like you're trying to convert an array to string here:
$data = "$rating, $topic, $other\n";
I recommend you to implode your array with a pipe (|), like this:
$data = "$rating, " . implode ("|", $topic) . ", $other\n";
Try updating
if(!empty($_POST['topic'])) {
foreach($_POST['topic'] as $value){
echo $value;
}
}
To
if(!empty($_POST['topic'])) {
foreach($_POST['topic'] as $value){
$topic .= ', '.$value;
}
}

How to keep form data after validation fail and when the page redirects with PHP?

I have this form that I'm working with off a tutorial. I'm trying keep the fields populated when there is a validation error.
Here is my form:
<div class="add">
<?php $errors4 = errors_seesion_funtion(); ?>
<?php echo form_errors($errors4); ?>
<div class="error-message"><?php echo message(); ?></div>
<div class="done"><input name="Done" type="button" value="Done" /></div>
<h2>ADD New Department:</h2>
<form action="create-department-process.php" method="post">
<p class="department-name">Department name:
<input type="text" name="department_name" id="department-name" value="<?php if (isset($_POST['department_name'])) { echo htmlentities($_POST['department_name']); } ?>" />
<span class="error">* <?php if (!empty($errors4)) { echo "<div class=\"error\">";
echo "Hi";
echo "</div>";
}
?></span>
</p>
<p class="department-name">Test name:
<input type="text" name="test_name" id="test-name" value="" />
<span class="error">* <?php /*echo form_errors($errors4); */
if (!empty($errors4)) {
echo "<div class=\"error\">";
echo "test name";
echo "</div>";
}
?></span>
</p>
<input type="submit" name="dept_added" id="add-btn" value="ADD Department" />
</form>
<br />
<div class="cancel">Cancel</div>
Here is my Session:
session_start();
function message() {
if (isset($_SESSION["message"])) {
$output = "<div class='message'>";
$output .= htmlentities($_SESSION["message"]);
$output .= "</div>";
// clear message after use
$_SESSION["message"] = null;
return $output;
}
}
function errors_seesion_funtion() {
if (isset($_SESSION["errors3"])) {
$errors2 = $_SESSION["errors3"];
$_SESSION['post_data'] = $_POST;
// clear message after use
$_SESSION["errors3"] = null;
return $errors2;
}
}
Here is my Validation Functions:
$errors_array = array();
function fieldname_as_text($fieldname) {
$fieldname = str_replace("_", " ", $fieldname);
$fieldname = ucfirst($fieldname);
return $fieldname;
}
function has_presence($value) {
return isset($value) && $value !== "";
}
function validate_presences($required_fields) {
global $errors6;
foreach($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors6[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
Here is my create-department-process.php
if (isset($_POST['dept_added'])) {
$department_name = mysql_prep($_POST["department_name"]);
//Validations for form
$required_fields = array("department_name", "test_name");
validate_presences($required_fields);
if (!empty($errors6)) {
$_SESSION["errors3"] = $errors6;
redirect_to("add-department.php"); //this is the page the form is on
}
// Process the form
$query1 = "INSERT INTO departments (";
$query1 .= " department_name ";
$query1 .= ") VALUES ( ";
$query1 .= " '{$department_name}' ";
$query1 .= ") ";
$result1 = mysqli_query($db_connection, $query1);
if ($result1) {
// Success
$_SESSION["message"] = "Department created.";
redirect_to("add-department.php");
} else {
// Failure
$_SESSION["message"] = "Department creation failed.";
redirect_to("creation-error.php");
}
} else {
redirect_to("fail.php");
}
I've tried to put this in the value of my form
<?php if (isset($_POST['department_name'])) { echo htmlentities($_POST['department_name']); } ?>
But the value I type in doesn't stay when PHP runs the form validation and redirects. Does anyone have any idea on how I can keep the data I type into the form fields when I have a validation error?
Thank you for your time and Help! I really appreciate it!
I think your POST data is getting lost when you do this:
if (!empty($errors6)) {
$_SESSION["errors3"] = $errors6;
redirect_to("add-department.php"); //this is the page the form is on
}
I'm guessing redirect_to actually redirects your browser to the specified page, therefore resetting the REQUEST values and losing the pervious POST data. You either need to save the POST values in the session (a la errors_seesion_funtion) and access them from there in your form, or include the form above to preserve the original POST values.

Extract emails from a list of url

I have a list of urls that I want to extract the email or from the href or from the text. Each page has one email only.
The problem is that my list is big and can not do it manually.
EMAIL
How can I do this using PHP, regex?
/mailto:([a-zA-Z0-9_\.-]+#[\da-z\.-]+\.[a-z\.]{2,6})"/gm
see this demo https://regex101.com/r/mC7jM3/1
Extract email from url contain
<?php
$the_url = isset($_REQUEST['url']) ? htmlspecialchars($_REQUEST['url']) : '';
if (isset($_REQUEST['url']) && !empty($_REQUEST['url'])) {
$text = file_get_contents($_REQUEST['url']);
}
elseif (isset($_REQUEST['text']) && !empty($_REQUEST['text'])) {
$text = $_REQUEST['text'];
}
if (!empty($text)) {
$res = preg_match_all(
"/[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}/i", $text, $matches
);
if ($res) {
foreach (array_unique($matches[0]) as $email) {
echo $email . "<br />";
}
}
else {
echo "No emails found.";
}
}
?>
<form method="post" action="">
Please enter full URL of the page to parse (including http://):<br />
<input type="text" name="url" size="65" value="<?php echo $the_url; ?>"/><br />
<input type="submit" name="submit" value="Submit" />
</form>

Strange validation error for form

The error i got was:
Notice: Undefined index: visible in C:\xampp\htdocs\introducingphp\includes\validation_function.php on line 22
It should not happen since i already instantiated all the variables including visible
Validation_function.php
<?php
$errors = array();
function fieldname_as_text($fieldname) {
$fieldname = str_replace("_", " ", $fieldname);
$fieldname = ucfirst($fieldname);
return $fieldname;
}
// * presence
// use trim() so empty spaces don't count
// use === to avoid false positives
// empty() would consider "0" to be empty
function has_presence($value) {
return isset($value) && $value !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
// * string length
// max length
function has_max_length($value, $max) {
return strlen($value) <= $max;
}
function validate_max_lengths($fields_with_max_lengths) {
global $errors;
// Expects an assoc. array
foreach($fields_with_max_lengths as $field => $max) {
$value = trim($_POST[$field]);
if (!has_max_length($value, $max)) {
$errors[$field] = fieldname_as_text($field) . " is too long";
}
}
}
// * inclusion in a set
function has_inclusion_in($value, $set) {
return in_array($value, $set);
}
?>
new_page.php (the page that has the one-page submit form that does validation)
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/db_connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php require_once("includes/validation_function.php"); ?>
<?php find_selected_page(); ?>
<?php
// Can't add a new page unless there is a subject as a parent
if (!$current_subject) {
// subject ID was missing or invalid or
//subject couldn't be found in database
redirect_to("manage_content.php");
}
?>
<?php
if (isset($_POST['submit'])) {
// Process the form
//validations
$required_fields = array("menu_name", "position", "visible",
"content");
validate_presences($required_fields);
$fields_with_max_lengths = array("menu_name" => 60);
validate_max_lengths($fields_with_max_lengths);
if (empty($errors)) {
// perform Create
//add the subject_id
$subject_id = $current_subject["id"];
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
//escape content
$content = mysql_prep($_POST["content"]);
// 2. Perform database query
$query .= "INSERT INTO pages (";
$query .= " subject_id, menu_name, position, visible,
content";
$query .= ") VALUES (";
$query .= " {$subject_id}, '{$menu_name}', {$position},
{$visible}, '{$content}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result ) {
// Success
$_SESSION["message"] = "Page Created.";
redirect_to("manage_content.php?subject=" .
urlencode($current_subject["id"]));
}else {
// Failure
$_SESSION["message"] = "Page creation failed.";
}
}
} else {
// This is probably a GET request
} // End: If(isset($_POST['submit']))
?>
<?php $layout_context = "admin"; ?>
<?php include("header.php"); ?>
<div id="main">
<div id="navigation">
<?php echo navigation($current_subject, $current_page); ?>
</div>
<div id="page">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
<h2>Create Page</h2>
<form action="new_page.php?subject=<?php echo
urlencode($current_subject["id"]); ?>" method="post">
<p>Menu name:
<input type="text" name="menu_name" value="" />
</p>
<p>Position:
<select name="position">
<?php
$page_set =
find_all_pages_for_subject($current_subject["id"], false);
$page_count = mysqli_num_rows($page_set);
for($count=1; $count <= ($page_count + 1); $count++) {
echo "<option value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible
<input type="radio" name="visible" value="0" /> NO
<input type="radio" name="visible" value="1" /> Yes
</p>
<p>Content:<br />
<textarea name="content" rows="20" cols="80"></textarea>
</p>
<input type="submit" name="submit" value="Create Page" />
</form>
<br />
<a href="manage_content.php?subject=<?php echo
urlencode($current_subject["id"]); ?>">Cancel</a>
</div>
</div>
<?php include("includes/footer.php"); ?>
You probably have a typo on the input HTML field. You can use:
if (isset($_POST[$field])) {
on validate_presences() function to be sure that the value exists.
When you try to do trim($_POST[$field]); you assume, the field exists in the $_POST array - for visible it does not in this case. You could move the trim to has_presence()
function has_presence($value) {
return isset($value) && trim($value) !== "";
}
function validate_presences($required_fields) {
global $errors;
foreach($required_fields as $field) {
if (!has_presence($value)) {
$errors[$field] = fieldname_as_text($field) . " can't be blank";
}
}
}
Now when you will only have the trim if the variable exists.
Okay, marking the radio check button makes it work now. Thanks for all your inputs guys. It has helped me a great deal.

PHP Drop Down Multi Select

I am new to the world of coding and PHP. Having picked up some of the basics, I have put a form together. I'm sure there are much efficient ways to code a page however seeing I have put something together with what I have learnt so far, I am having troubling getting past on select a multi-select dropdown after the user has posted the page i.e. to remember what the user selected. Here is my entire code.
<?php
//Process form variables
//Validate if the form has been submitted
if(isset($_POST['submit'])) {
//Validate if the form elements were completed
$fname = isset($_POST['fname']) ? $_POST['fname'] : '';
$lname = isset($_POST['lname']) ? $_POST['lname'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$gender = isset($_POST['gender']) ? $_POST['gender'] : '';
$updates = isset($_POST['updates']) ? $_POST['updates'] : '';
$media = isset($_POST['media']) ? $_POST['media'] : '';
$comments = isset($_POST['comments']) ? $_POST['comments'] : '';
//Place error messages in an array
$errormsg = array();
if(empty($fname)) {
$errormsg[0] = 'Please specify your first name. It\'s blank.';
}
if(empty($lname)) {
$errormsg[1] = 'Please specify your last name. It\'s blank.';
}
if(empty($email)) {
$errormsg[2] = 'Please provide an email address. It\'s blank.';
}
if(empty($gender)) {
$errormsg[3] = 'Please select a gender. It\'s blank.';
}
if(empty($updates)) {
$errormsg[4] = 'Please select how we can contact you. It\'s blank.';
}
if(empty($media)) {
$errormsg[5] = 'Please select where you heard about us. It\'s blank.';
}
if(empty($comments)) {
$errormsg[6] = 'Please tell us what you think of us. It\'s blank.';
}
//Return list of error messages
foreach($errormsg as $errormsg) {
echo $errormsg . '<br />';
}
//Debug
print_r($_POST['media']);
}
?>
<html>
<head>
<title>Sample Registration Form</title>
</head>
<body>
<h2>Sample Registration Form</h2>
<form name="registration" method="post" action="registration.php">
<div>
First Name: <br />
<input type="text" name="fname" value="<?php if(!empty($_POST['fname'])) { echo $fname; } ?>">
</div>
<div>
Last Name: <br />
<input type="text" name="lname" value="<?php if(!empty($_POST['lname'])) { echo $lname ; } ?>">
</div>
<div>
Email Address: <br />
<input type="text" name="email" value="<?php if(!empty($_POST['email'])) { echo $email; } ?>">
</div>
<div>
Gender: <br />
<?php
//Generate gender array
$gender = array('male', 'female');
$countgender = count($gender);
for($start=0;$start < $countgender;$start=$start+1) {
$status = '';
if(isset($_POST['submit'])) {
if($_POST['gender'][0] == $gender[$start]) {
$status = 'checked';
// echo $gender[$start];
}
}
$genderform = '<input type="radio" name="gender[]" value="'. $gender[$start] . '" '. $status. '>' . $gender[$start];
echo $genderform;
}
// foreach($gender as $gender) {
// $status = '';
// if(isset($_POST['submit'])) {
// if($_POST['gender'][0] == $gender) {
// $status = 'checked';
// }
// }
// $genderform = '<input type="radio" name="gender[]" value="' .$gender . '" ' . $status .'>'. $gender . '';
// echo $genderform;
// }
?>
</div>
<div>
Would you like to receive updates from us? <br />
<?php
$updates = array(0 => 'newsletter', 1 => 'email', 2 => 'sms');
foreach($updates as $updatekeys => $updatevalues) {
$status = '';
if(!empty($_POST['updates'][$updatevalues]) == $updatevalues) {
$status = 'checked';
// echo $_POST['updates'][$updatevalues];
}
echo '<input type="checkbox" name="updates[' . $updatevalues . ']" value="'. $updatevalues. '" '. $status . '>'.$updatevalues;
}
?>
</div>
<div>
How did you hear about us? <br />
<select name="media[]" multiple>
<?php
$media = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure');
foreach($media as $mediakey => $mediavalue) {
$mediaform = '<option value="'. $mediavalue . '">'.$mediavalue.'</option>';
echo $mediaform;
}
?>
</select>
</div>
<div>
Tell us what you think: <br />
<textarea name="comments" cols="50" rows="10"><?php if(!empty($_POST['comments'])) { echo $comments; } ?></textarea>
</div>
<div>
<input type="submit" name="submit" value="submit">
</div>
</form>
</body>
</html>
EDIT
Guys, I have updated my code to reflect some of the suggestions below. Let me know if the page is better coded. I have not included suggestions such as $start++ just because I am trying to understand what it means. I love to make coding as short as possible but seeing that I am just learning, best to get a good foundation.
<?php
//Initialize session
session_start();
//Generate session id
echo session_id() . '<br />';
//Process form variables
//Validate if the form has been submitted
if(isset($_POST['submit'])) {
//Validate if the form elements were completed
$fname = isset($_POST['fname']) ? $_POST['fname'] : '';
$lname = isset($_POST['lname']) ? $_POST['lname'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$gender = isset($_POST['gender']) ? $_POST['gender'] : '';
$updates = isset($_POST['updates']) ? $_POST['updates'] : '';
$media = isset($_POST['media']) ? $_POST['media'] : '';
$comments = isset($_POST['comments']) ? $_POST['comments'] : '';
//Place error messages in an array
$errormsg = array();
if(empty($fname)) {
$errormsg[0] = 'Please specify your first name. It\'s blank.';
}
if(empty($lname)) {
$errormsg[1] = 'Please specify your last name. It\'s blank.';
}
if(empty($email)) {
$errormsg[2] = 'Please provide an email address. It\'s blank.';
}
if(empty($gender)) {
$errormsg[3] = 'Please select a gender. It\'s blank.';
}
if(empty($updates)) {
$errormsg[4] = 'Please select how we can contact you. It\'s blank.';
}
if(empty($media)) {
$errormsg[5] = 'Please select where you heard about us. It\'s blank.';
}
if(empty($comments)) {
$errormsg[6] = 'Please tell us what you think of us. It\'s blank.';
}
//Return list of error messages
foreach($errormsg as $errormsg) {
echo $errormsg . '<br />';
}
//Debug
// print_r($_POST['media']);
}
?>
<html>
<head>
<title>Sample Registration Form</title>
</head>
<body>
<h2>Sample Registration Form</h2>
<form name="registration" method="post" action="registration.php">
<div>
First Name: <br />
<input type="text" name="fname" value="<?php if(!empty($_POST['fname'])) { echo $fname; } ?>">
</div>
<div>
Last Name: <br />
<input type="text" name="lname" value="<?php if(!empty($_POST['lname'])) { echo $lname ; } ?>">
</div>
<div>
Email Address: <br />
<input type="text" name="email" value="<?php if(!empty($_POST['email'])) { echo $email; } ?>">
</div>
<div>
Gender: <br />
<?php
//Generate gender array
$gender = array('male', 'female');
$countgender = count($gender);
for($start=0;$start < $countgender;$start=$start+1) {
$status = '';
if(isset($_POST['submit']) && !empty($_POST['gender'])) {
$status = in_array($gender[$start], $_POST['gender']) ? 'checked' : '';
}
$genderform = '<input type="radio" name="gender[]" value="'. $gender[$start] . '" '. $status. '>' . $gender[$start];
echo $genderform;
}
?>
</div>
<div>
Would you like to receive updates from us? <br />
<?php
$updates = array(0 => 'newsletter', 1 => 'email', 2 => 'sms');
foreach($updates as $updatekeys => $updatevalues) {
$status = '';
if(isset($_POST['submit']) && !empty($_POST['updates'])) {
$status = in_array($updatevalues, $_POST['updates']) ? 'checked' : '';
}
// if(!empty($_POST['updates'][$updatevalues]) == $updatevalues) {
// $status = 'checked';
// echo $_POST['updates'][$updatevalues];
// }
echo '<input type="checkbox" name="updates[' . $updatevalues . ']" value="'. $updatevalues. '" '. $status . '>'.$updatevalues;
}
?>
</div>
<div>
How did you hear about us? <br />
<select name="media[]" multiple>
<?php
$media = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure');
foreach($media as $mediakey => $mediavalue) {
$status = in_array($mediavalue,$_POST['media'])? 'selected' : '';
$mediaform = '<option value="'. $mediavalue . '" '. $status .'>'.$mediavalue.'</option>';
echo $mediaform;
}
?>
</select>
</div>
<div>
Tell us what you think: <br />
<textarea name="comments" cols="50" rows="10"><?php if(!empty($_POST['comments'])) { echo $comments; } ?></textarea>
</div>
<div>
<input type="submit" name="submit" value="submit">
</div>
</form>
</body>
</html>
You can use in_array function to check whether the current $mediavalue in the array of selected $media - but you need to select another name for array with media sources, because it overwrites the $media variable with user selection. For example:
$mediaTypes = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure');
foreach($mediaTypes as $mediakey => $mediavalue) {
$mediaform = '<option value="'. $mediavalue . '" '
. (in_array($mediavalue, $media) ? 'selected' : '') . '>' . $mediavalue.'</option>';
echo $mediaform;
}
There are a few recommended minor modifications to you code as well:
you do not need to use numbers in array - it duplicates the default behavior, so $mediaTypes = array(0 => 'internet', 1 => 'pamphlet', 2 => 'brochure'); can be just $mediaTypes = array('internet', 'pamphlet', 'brochure');
when gender is not set, $_POST['gender'] causes notice "Undefined index: gender".
$start=$start+1 can be compacted to $start++;
it is better to reuse the variables with user inputs instead of accessing $_POST directly
Try this:
foreach($media as $mediakey => $mediavalue) {
$selected=in_array($mediavalue,$_POST['media'])?"selected":"";
$mediaform = '<option '.$selected.' value="'. $mediavalue . '">'.$mediavalue.'</option>';
echo $mediaform;
}
based on form output of the dropdown, set a $_SESSION['variable'] the do something like:
if (isset($_SESSION['variable'])) {
// if exists
}
else {
// if doesn't exist
}
you could even include other elseif statements based on different parameters. Then use else as an error handle.

Categories