I am trying to create a simple form validation and the form wont submit until all of the fields were set. I have two files here.
-form.php
-process.php
For some reason the $error won't appear and the radio button wont submit. Is there anything wrong?
here's the form.php:
<?php
if(isset($_GET['error']) && $_GET['error']!=""){
echo $_GET['error'];
}
?>
<body>
<form action="process.php" method="POST">
<p>
<label for="name">Your Name:</label>
<input type="text" name="name" id="name" value="">
</p>
<p>
<label for="location">Dojo Location:</label>
<select name="location">
<option value="Mountain View">Mountain View</option>
<option value="San Francisco">San Francisco</option>
<option value="South Korea">South Korea</option>
<option value="Philippines">Philippines</option>
</select>
</p>
<p>
<label for="language">Favorite Language:</label>
<select name="language">
<option value="JavaScript">JavaScript</option>
<option value="PHP">PHP</option>
<option value="Ruby">Ruby</option>
<option value="Python">Python</option>
</select>
</p>
<p>
<label for="comment">Comment: (Optional)</label><br/>
<textarea rows="10" cols="50" name="comment"></textarea>
</p>
<p>
<label for="comment">Can we store cookies in your computer?</label>
<input type="radio" name="cookies" value="yes">Yes
<input type="radio" name="cookies" value="no">No
</p>
<input type="submit" value="Submit">
</form>
here's the process.php:
<?php
if (isset($_POST["submit"])) {
if (empty($_POST["name"])) {
$Error = "Missing Name";
}
if (empty($_POST["location"])) {
$Error = "Missing Location";
}
if (empty($_POST["language"])) {
$Error = "Missing language";
}
if (empty($_POST["cookies"])) {
$Error = "Select cookies";
}
}else{
$name = $_POST['name'];
$location = $_POST['location'];
$language = $_POST['language'];
$comment = $_POST['comment'];
$cookies = $_POST['cookies'];
}
if($Error!=""){
header("Location:form.php?error=".$Error);
}
?>
<h2>Submitted Information:</h2>
<p><?php echo "NAME: {$name}"; ?> </p>
<p><?php echo "DOJO LOCATION: {$location}"; ?></p>
<p><?php echo "FAVORITE LANGUAGE: {$language}:"; ?> </p>
<p><?php echo "COMMENT: {$comment}"; ?></p>
<p><?php echo "COOKIES: {$cookies}"; ?></p>
Any idea?
Try something like this in your process.php
if($Error!=""){
header("Location:form.php?error=".$Error);
}
On your form.php
if(isset($_GET['error']) && $_GET['error']!=""){
echo $_GET['error'];
}
In your process.php change the code to
<?php
if (isset($_POST["submit"])) {
$Error ="";
if (isset($_POST["name"]) && $_POST["name"]!="") {
$Error = "Missing Name";
}
if (isset($_POST["location"]) && $_POST["location"]!="") {
$Error = "Missing Location";
}
if (isset($_POST["language"]) && $_POST["language"]!="") {
$Error = "Missing language";
}
if (isset($_POST["cookies"]) && $_POST["cookies"]!="") {
$Error = "Select cookies";
}
if($Error!=""){
header("Location:form.php?error=".$Error);
}
$name = $_POST['name'];
$location = $_POST['location'];
$language = $_POST['language'];
$comment = $_POST['comment'];
$cookies = $_POST['cookies'];
}
?>
Either you need a form to redirect back to your form.php, or move the echo $Error to your process.php so you can show the error from that page.
Related
I need help with 'Confirm Form Resubmission' message (getting in chrome while watching view source)
If I delete the comment, it's shows only username 1 not matter which ID I selected, and if the comment stay as below code, its works with the re submit message...
<?php
$username = get_username_from_db(1);
if (isset($_POST['id'])) {
$id = $_POST['id'];
$username = get_username_from_db($id);
/*
// if this comment stay as comment, username will update with 'confirm form resubmission' message
// else 'confirm form resubmission' message not shows but username not updated (keep as default [1])
header('Location: ' . $_SERVER['HTTP_HOST']);
exit();
*/
}
?>
<body>
<form method="POST">
<fieldset>
<legend>Choose ID</legend>
<select name="id" onchange="this.form.submit()">
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
</select>
<br>
<label>Username:</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</fieldset>
</form>
</body>
Any idea?
Try this:
Code with $_GET;
<?php
$username = get_username_from_db(1);
if (isset($_POST['id'])) {
$id = $_POST['id'];
$username = get_username_from_db($id);
/*
// if this comment stay as comment, username will update with 'confirm form resubmission' message
// else 'confirm form resubmission' message not shows but username not updated (keep as default [1])
*/
$url = $_SERVER['HTTP_HOST'] . '?name='.$username;
header('Location: ' . $url);
exit();
}
else if(isset($_GET['name']) && !empty($_GET['name'])){
$username = $_GET['name'];
}
?>
<body>
<form method="POST">
<fieldset>
<legend>Choose ID</legend>
<select name="id" onchange="this.form.submit()">
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
</select>
<br>
<label>Username:</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</fieldset>
</form>
</body>
Code with $_SESSION;
<?php
session_start();
$user_id = 1;
if(isset($_SESSION['user_id'])){
$user_id = intval($_SESSION['user_id']);
}
// prevent 0 and negative;
if($user_id <= 0){
$user_id = 1;
}
$username = get_username_from_db($user_id);
if(isset($_POST['id'])){
$id = intval($_POST['id']);
// prevent 0 and negative;
if($id <= 0){
$id = 1;
}
$_SESSION['user_id'] = $id;
$url = $_SERVER['HTTP_HOST'];
header('Location: ' . $url);
exit();
}
?>
<body>
<form method="POST">
<fieldset>
<legend>Choose ID</legend>
<select name="id" onchange="this.form.submit()">
<option value="1">1st</option>
<option value="2">2nd</option>
<option value="3">3rd</option>
</select>
<br>
<label>Username:</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</fieldset>
</form>
</body>
I have an assignment that calls for data entries from a php form to be stored in a plain text file on the same web server. I created the php form page and the plain text file but I am unsure how to connect the two. I've searched the internet and tried multiple ways for about two hours now and no dice. The data entries have to accumulate in the plain text file too (1st person submits, and a 2nd person submitting can see 1st person's submission and so on).
I didn't add any of the code I've tried to the plain text file because none of them were working and I wanted to (in theory) simplify the process of not having to try and fix the code. I know that the plain text file needs some sort of code to retrieve the code from the php form but unsure what to try at this point. And yes I wrote permissions for the plain text file to be writable via FileZilla.
Here's my php form code:
<!DOCTYPE HTML>
<html>
<head>
<title>Roy Feedback Form Assignment 7</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = $likesErr = $howErr = $rateErr = "";
$name = $email = $comment = $likes = $how = $rate = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
if (empty($_POST["comment"])) {
$commentErr = "Comments are required";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["likes"])) {
$likesErr = "Things you liked is required";
} else {
$likes = test_input($_POST["likes"]);
}
if (empty($_POST["how"])) {
$howErr = "How you got to our site is required";
} else {
$how = test_input($_POST["how"]);
}
if (empty($_POST["rate"])) {
$rateErr = "Rating our site is required";
} else {
$rate = test_input($_POST["rate"]);
}
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Roy Feedback Form Assignment 7</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br><br>
Things you liked:
<input type="radio" name="likes" value="Site design">Site design
<input type="radio" name="likes" value="Links">Links
<input type="radio" name="likes" value="Ease of use">Ease of use
<input type="radio" name="likes" value="Images">Images
<input type="radio" name="likes" value="Source code">Source code
<span class="error">* <?php echo $likesErr;?></span>
<br><br>
How you got to our site:
<input type="radio" name="how" value="Search engine">Search engine
<input type="radio" name="how" value="Links from another site">Links from another site
<input type="radio" name="how" value="Deitel.com website">Deitel.com website
<input type="radio" name="how" value="Reference from a book">Reference from a book
<input type="radio" name="how" value="Other">Other
<span class="error">* <?php echo $howErr;?></span>
<br><br>
Rate our site:
<select name="rate">
<option value="">- Please Select -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<span class="error">* <?php echo $rateErr;?></span>
<br/><br/>
<input type="submit" name="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
And here's the plain text file code:
<!DOCTYPE html>
<html>
<head>
<title>Roy Feedback Results Assignment 7</title>
</head>
<body>
</body>
</html>
Update 1
So I'm still having issues (sorry, I know it's like trying to teach PHP to a grapefruit). So when I use the following code nothing happens on the plain text page (as in the data isn't stored where I tell it to be):
function file_write($data, $feedback_results_html_only){
if(is_readable($feedback_results_html_only)){
if(is_string($data)){
return file_put_contents($feedback_results_html_only, $data, FILE_APPEND | LOCK_EX);//this appends the new data to the file and locks it while doing so to prevent multiple access to thje file at the same time.
}//return an error message if the data isnt a string
}//return an error message if the file doesnt exist or isnt readable
}
However when I use the following code it at least places the "John Smith" name into the file (which is the first time I actually got it to somewhat work, hooray coding!):
<?php
$file = 'feedback_results_html_only.php';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
Also I am aware that I didn't use the ".php" on the "feedback_results_html_only" in the first example of code (in update 1) because it created an error. Could I possibly try something like the second example (in update 1) instead to make it work?
$file = 'feedback_results_html_only.php'
You are looking for file_put_contents(). Simply collect the data and write it to your file. Here is the refined code:
PS: You could consider starting with the php code first :-)
<?php
// define variables and set to empty values
$nameErr = '';
$emailErr = '';
$commentErr = '';
$likesErr = '';
$howErr = '';
$rateErr = '';
$name = '';
$email = '';
$comment = '';
$likes = '';
$how = '';
$rate = '';
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
if (empty($_POST["comment"])) {
$commentErr = "Comments are required";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["likes"])) {
$likesErr = "Things you liked is required";
} else {
$likes = test_input($_POST["likes"]);
}
if (empty($_POST["how"])) {
$howErr = "How you got to our site is required";
} else {
$how = test_input($_POST["how"]);
}
if (empty($_POST["rate"])) {
$rateErr = "Rating our site is required";
} else {
$rate = test_input($_POST["rate"]);
}
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//concatenate the data, then format and validate it then use this function to write it to your plain text file
function file_write($data, $pathtoplaintxtfile){
if(is_string($data)){
return file_put_contents($pathtoplaintxtfile, $data, FILE_APPEND | LOCK_EX);//this appends the new data to the file and locks it while doing so to prevent multiple access to thje file at the same time.
}//return an error message if the data isnt a string
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Roy Feedback Form Assignment 7</title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<h2>Roy Feedback Form Assignment 7</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br><br>
Things you liked:
<input type="radio" name="likes" value="Site design">Site design
<input type="radio" name="likes" value="Links">Links
<input type="radio" name="likes" value="Ease of use">Ease of use
<input type="radio" name="likes" value="Images">Images
<input type="radio" name="likes" value="Source code">Source code
<span class="error">* <?php echo $likesErr;?></span>
<br><br>
How you got to our site:
<input type="radio" name="how" value="Search engine">Search engine
<input type="radio" name="how" value="Links from another site">Links from another site
<input type="radio" name="how" value="Deitel.com website">Deitel.com website
<input type="radio" name="how" value="Reference from a book">Reference from a book
<input type="radio" name="how" value="Other">Other
<span class="error">* <?php echo $howErr;?></span>
<br><br>
Rate our site:
<select name="rate">
<option value="">- Please Select -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<span class="error">* <?php echo $rateErr;?></span>
<br/><br/>
<input type="submit" name="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
EDIT: file_put_contents() automaticly creates a file if it doesnt exist, remove is_readable file check.
EDIT: Usage -
$data = $name.$email.$comment.$likes.$how.$rate.
'This is just test data. If no other data is visible, then you didnt fill them out';
file_write($data, 'feedback_results_html_only.php')
Use file_put_contets
$relative_or_absolute_path = '../'; //relative folder up
$ext = '.txt'; //file can be with no extension at all or even *.php
$filename = 'plain_log';
$contents = '';
foreach($users as $user){
$contents .= $user . '\n'; //a newline
}
//execute
file_put_contents($relative_or_absolute_path.$filename.$ext, $contents, FILE_APPEND);
//FILE_APPEND is an optional flag // otherwise it will rewrite
I have a php contact form and all works great going to a single address but I'm trying to modify my script to handle a drop down selector, which enables choosing a recipient (which email address to send to).
Here is the part of the code that I have so far in trying to deal with this issue:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="recipient" id="recipient">
<p class="text">
Please select recipient<br>
<select name="recipient" size="4"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['recipient'], ENT_QUOTES).'"';
} ?>
>
<option value="">Select...</option>
<option value="1">Artistic Director</option>
<option value="2">Site Administrator</option>
<option value="3">Someone else</option>
</select>
</p>
</form>
<?php if (array_key_exists('send', $_POST)) {
// mail processing script
if ('recipient' == 1) {
$to = 'soandso#mail.com';
}
elseif('recipient' == 2) {
$to = 'soandso#mail.com';
}
elseif('recipient' == 3) {
$to = 'soandso#mail.com';
}
else {
echo 'Sorry for no recipient';
}
//then remainder code to process the rest which works fine
I'm sure my problem lies in the calling/getting the value of recipient but I can't figure out where to go from here.
You're trying to do something weird here. It should be:
if ($_POST['recipient'] == 1) {
$to = 'soandso#mail.com';
}
else if($_POST['recipient'] == 2) {
$to = 'soandso#mail.com';
}
else if($_POST['recipient'] == 3) {
$to = 'soandso#mail.com';
}
else {
echo 'Sorry for no recipient';
}
Of course 'recipient' will never be equal to 1, 2 or 3.
I also noticed the form and the select has the same name 'recipient'. I don't know is that is an issue though. But I would like to address it anyway.
This code is working 100% :
(function($) {
$('#recipient').on('click', function() {
$('#recipient-form').submit();
});
})(jQuery);
<div id="page">
<?php
$to = '';
if (isset($_POST['recipient'])) :
// mail processing script
if ($_POST['recipient'] == 1) {
$to = 'recipient1';
}
else if($_POST['recipient'] == 2) {
$to = 'reciipient2';
}
else if($_POST['recipient'] == 3) {
$to = 'recipient3';
}
else {
$to = 'Sorry for no recipient';
}
echo $to;
else : ?>
<form action="" method="post" id="recipient-form">
<select id="recipient" name="recipient" size="4">
<option value="">Select...</option>
<option value="1">Artistic Director</option>
<option value="2">Site Administrator</option>
<option value="3">Someone else</option>
</select>
</form>
</div>
<?php endif; ?>
The page in it's (mostly) entirety for clarification purposes hopefully:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="recipient-form">
<p class="text">
Please select recipient<br>
<select id="recipient" name="recipient" size="4">
<option value="">Select...</option>
<option value="1">Artistic Director</option>
<option value="2">Site Administrator</option>
<option value="3">Someone else</option>
</select>
</p>
</form>
<?php if (array_key_exists('send', $_POST)) {
// mail processing script
$to = '';
if ($_POST['recipient']) {
// mail processing script
if ($_POST['recipient'] == 1) {
$to = '';
}
else if($_POST['recipient'] == 2) {
$to = '';
}
else if($_POST['recipient'] == 3) {
$to = '';
}
else {
$to = 'Sorry for no recipient';
}
}
$subject = 'Feedback From Website';
// list expected fields
$expected = array('name', 'email', 'comments', 'subscribe');
// set required fields
$required = array('name', 'email', 'comments');
// set additional headers
$headers = 'From: ';
// set the include
$process = 'includes/process.inc.php';
if (file_exists($process) && is_readable($process)) {
include($process);
}
else {
$mailSent = false;
mail($me, 'Server Problem', "$process cannot be read", $headers);
}
}
?>
<?php
if ($_POST && isset($missing) && !empty($missing)) {
?>
<p class="warning">Please complete the missing item(s) indicated.</p>
<?php
}
elseif ($_POST && $link) {
?>
<p class="warning">Sorry, Messages sent that contain links will not be sent.</p>
<?php
}
elseif ($_POST && !$mailSent) {
?>
<p class="warning">Sorry, there was a problem sending your message. Please try again later.</p>
<?php
}
elseif ($_POST && $mailSent) {
?>
<p class="success">Your message has been sent. Thank you for your message!</p>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contact" id="contact" onSubmit="MM_validateForm('name','','R','email','','RisEmail','comments','','R');return document.MM_returnValue">
<p>
<label for="name">Name: <?php
if (isset($missing) && in_array('name', $missing)) { ?>
<span class="warning">Please enter your name</span><?php } ?>
</label>
<input name="name" type="text" class="textInput" id="name"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['name'], ENT_QUOTES).'"';
} ?>
>
</p>
<p>
<label for="email">Email: <?php
if (isset($missing) && in_array('email', $missing)) { ?>
<span class="warning">Please enter your email address</span><?php } ?>
</label>
<input name="email" type="text" class="textInput" id="email"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['email'], ENT_QUOTES).'"';
} ?>
>
</p>
<p>
<label for="comments">Message:<?php
if (isset($missing) && in_array('comments', $missing)) { ?>
<span class="warning">Please enter your message</span><?php } ?>
</label>
<textarea name="comments" id="comments" cols="45" rows="5"><?php
if (isset($missing)) {
echo htmlentities($_POST['comments'], ENT_QUOTES);
} ?></textarea>
</p>
<p>
<p class="text">
Please check the box if you would like to sign up for our Mailing List!
<input type="checkbox" name="subscribe" value="Yes"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['subscribe'], ENT_QUOTES).'"';
} ?>
>
</p>
<p>
<?php
require_once('recaptchalib.php');
$publickey = "6Lf3NdQSAAAAAOAwgPGRybLnY175X6k9PJ1F2vHx"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
</p>
<p class="last">
<input type="submit" name="send" id="send" value="Send Message">
</p>
</form>
Hopefully having all of it now will help someone come up with the best solution!
The entirety again. I think/hope we're getting closer:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="getEmail">
<p class="text">Please select recipient</p><br>
<select name="recipient" size="4">
<option value="">Select...</option>
<option value="1">Artistic Director</option>
<option value="2">Site Administrator</option>
<option value="3">Someone else</option>
</select>
<input type='hidden' name='do' value='1'>
</form>
<?php
if (array_key_exists('send', $_POST)) {
if (isset($_POST['do'])) {
// mail processing script
if ($_POST['recipient'] == 1) { $to = ''; }
else if($_POST['recipient'] == 2) { $to = ''; }
else if($_POST['recipient'] == 3) { $to = ''; }
else echo 'Sorry for no recipient';
}
echo $to;
$subject = 'Feedback From Website';
// list expected fields
$expected = array('name', 'email', 'comments', 'subscribe');
// set required fields
$required = array('name', 'email', 'comments');
// set additional headers
$headers = 'From:';
// set the include
$process = 'includes/process.inc.php';
if (file_exists($process) && is_readable($process)) {
include($process);
}
else {
$mailSent = false;
mail($me, 'Server Problem', "$process cannot be read", $headers);
}
}
?>
<?php
if ($_POST && isset($missing) && !empty($missing)) {
?>
<p class="warning">Please complete the missing item(s) indicated.</p>
<?php
}
elseif ($_POST && $link) {
?>
<p class="warning">Sorry, Messages sent that contain links will not be sent.</p>
<?php
}
elseif ($_POST && !$mailSent) {
?>
<p class="warning">Sorry, there was a problem sending your message. Please try again later.</p>
<?php
}
elseif ($_POST && $mailSent) {
?>
<p class="success">Your message has been sent. Thank you for your message!</p>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="contact" id="contact" onSubmit="MM_validateForm('name','','R','email','','RisEmail','comments','','R');return document.MM_returnValue">
<p>
<label for="name">Name: <?php
if (isset($missing) && in_array('name', $missing)) { ?>
<span class="warning">Please enter your name</span><?php } ?>
</label>
<input name="name" type="text" class="textInput" id="name"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['name'], ENT_QUOTES).'"';
} ?>
>
</p>
<p>
<label for="email">Email: <?php
if (isset($missing) && in_array('email', $missing)) { ?>
<span class="warning">Please enter your email address</span><?php } ?>
</label>
<input name="email" type="text" class="textInput" id="email"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['email'], ENT_QUOTES).'"';
} ?>
>
</p>
<p>
<label for="comments">Message:<?php
if (isset($missing) && in_array('comments', $missing)) { ?>
<span class="warning">Please enter your message</span><?php } ?>
</label>
<textarea name="comments" id="comments" cols="45" rows="5"><?php
if (isset($missing)) {
echo htmlentities($_POST['comments'], ENT_QUOTES);
} ?></textarea>
</p>
<p>
<p class="text">
Please check the box if you would like to sign up for our Mailing List!
<input type="checkbox" name="subscribe" value="Yes"
<?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['subscribe'], ENT_QUOTES).'"';
} ?>
>
</p>
<p>
<?php
require_once('recaptchalib.php');
$publickey = "6Lf3NdQSAAAAAOAwgPGRybLnY175X6k9PJ1F2vHx"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
</p>
<p class="last">
<input type="submit" name="send" id="send" value="Send Message">
</p>
</form>
Your form name and select name is the same. also you are echoing the post value inside the select. i think it is left over from your previous input box.
try this;
<form action="" method="post" id="getEmail">
<p class="text">Please select recipient<br></p>
<select name="recipient" size="4">
<option value="">Select...</option>
<option value="1">Artistic Director</option>
<option value="2">Site Administrator</option>
<option value="3">Someone else</option>
</select>
<input type='hidden' name='do' value='1'>
<input type='sumbit' value='Go'>
</form>
<?php if (isset($_POST['do'])) {
// mail processing script
if ($_POST['recipient'] == 1)$to = 'email1';
else if($_POST['recipient'] == 2)$to = 'email2';
else if($_POST['recipient'] == 3)$to = 'email3';
else echo 'Sorry for no recipient';
}
//echo $to;
//to send mail
$sub = 'Mail from web Form';
$msg = 'My message';
$mail_status= mail($to, $sub, $msg);
if($mail_status){do something on success}; else {do something on failure};
?>
I have tried the following php script to validate the user input.But the form is sent to database without prompting the user to fill the required fields i.e if a user leaves one or more fields empty, the form is submitted without asking to fill the fields.How do stop it from submitting until the conditions for each form field are met?
here is the code:-
<?php
$fnameErr=$lnameErr=$emailErr=$passwordErr=$cpasswordErr="";
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if(empty($_POST["fname"]))
{
$fnameErr="First name is Required";
}
else
{
$fname = $_POST["fname"];
}
if (empty($_POST["lname"]))
{
$lnameErr = "Last Name is required";
}
else
{
$lname = $_POST["lname"];
}
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email = $_POST["email"];
}
if (empty($_POST["password"]))
{
$passwordErr = "Password is required";
}
else
{
$password = $_POST["password"];
}
if (empty($_POST["cpassword"]))
{
$cpasswordErr = "Confirm Password";
}
else
{
$cpassword = $_POST["cpassword"];
}
//Create connection
$con=mysqli_connect("localhost","root","p11","daot");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO registration (FirstName, LastName, EmailAddress,Password,ConfirmPassword)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[email]','$_POST[password]','$_POST[cpassword]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mastercss.css">
<title>SIGN UP PAGE</title>
</head>
<body>
<?php include 'header.php'; ?>
<div class="leftbar">
</div>
<div class="content">
<h1 class="h1">complete the following form to register</h1>
<fieldset style="width:450px; background:gray;">
<form autocomplete="on" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="fname">First Name:</label>
<input type="text" name="fname"><?php echo $fnameErr;?><br><br>
<label for="lname">Last Name:</label>
<input type="text" name="lname"><?php echo $lnameErr;?><br><br>
<label for="email">Email:</label>
<input type="email" name="email"><?php echo $emailErr;?><br><br>
<label for="password">Password:</label>
<input type="password" name="password"><?php echo $passwordErr;?><br><br>
<label for="cpassword">Confirm Password</label>
<input type="password" name="cpassword"><?php echo $cpasswordErr;?><br><br>
<!--<label for="sex">Sex</label><input type="radio" name="sex" value="female"> Female
<input type="radio" name="sex" value="male">Male<br>
<label for="select">Birthday</label>
<select name="birthday_Month" id="month">
<option value="0" selected="1">Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
</select>
<select name="birthday_day" id="month">
<option value="0" selected="1">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="birthday_year" id="year">
<option value="0" selected="1">year</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
</select><br><br>-->
<input type="submit" value="SIGN UP" style="width:100: height:100" name="Submit">
</form>
</fieldset>
</div>
<div class="rightbar"><br><br>
<a href="https://www.twitter.com"><img src="tw1.jpg">
<img src="fb2.jpg">
</div>
<?php include "footer.php";?>
</body>
</html>
The form is being submitted without showing validations because it is executing the following line of codes even after executing the validation conditions. You need to avoid executing of the code if any validation is not proper by exiting from the code segment.
if(empty($_POST["fname"]))
{
$fnameErr="First name is Required";
exit;
}
You should do this instead
if(empty($_POST["fname"]))
{
$fnameErr="First name is Required";
echo $fnameErr;
exit();
}
and same for the rest of the conditions.
This will display all your errors at once:
In your PHP:
$error = array(); //save all errors into one array, later we will check if this array is empty to proceed with saving into DB
if(empty($_POST["fname"]))
{
$error['fname']="First name is Required";
}
else
{
$fname = $_POST["fname"];
}
if (empty($_POST["lname"]))
{
$error['lname'] = "Last Name is required";
}
else
{
$lname = $_POST["lname"];
}
if (empty($_POST["email"]))
{
$error['email'] = "Email is required";
}
else
{
$email = $_POST["email"];
}
if (empty($_POST["password"]))
{
$error['password'] = "Password is required";
}
else
{
$password = $_POST["password"];
}
if (empty($_POST["cpassword"]))
{
$error['cpassword'] = "Confirm Password";
}
else
{
$cpassword = $_POST["cpassword"];
}
if (empty($errors)) {
//if there are no errors, save into DB
//Create connection
$con=mysqli_connect("localhost","root","p11","daot");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO registration (FirstName, LastName, EmailAddress,Password,ConfirmPassword)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[email]','$_POST[password]','$_POST[cpassword]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
}
And in your HTML:
<label for="fname">First Name:</label>
//checking if error message is set, if yes display it
<input type="text" name="fname"><?php echo isset($error['fname'])?$error['fname']:'' ;?><br><br>
<label for="lname">Last Name:</label>
<input type="text" name="lname"><?php echo isset($error['lname'])?$error['lname']:'' ;?><br><br>
<label for="email">Email:</label>
<input type="email" name="email"><?php echo isset($error['email'])?$error['email']:'' ;?><br><br>
<label for="password">Password:</label>
<input type="password" name="password"><?php echo isset($error['password'])?$error['password']:'' ;?><br><br>
<label for="cpassword">Confirm Password</label>
<input type="password" name="cpassword"><?php echo isset($error['cpassword'])?$error['cpassword']:'' ;?><br><br>
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$gender = $_POST["gen"];
$age = $_POST["age"];
$comments = $_POST["comments"];
if(empty($_POST["name"])){
echo "empty name";
}
if(empty($_POST["email"])){
echo "empty email";
}
///
if(empty($_POST["gen"])){
echo "empty gender";
}
if(empty($_POST["comments"])){
echo "empty comments";
}
if(!isset($_POST['submit'])) {
?>
<html>
<head>
<title>Lab6 : P1</title>
</head>
<body>
<fieldset>
<legend><h4>Enter your information in the fields below</h4></legend>
<form name="info" method="post" action="<?php echo $PHP_SELF;?>" method="post">
<strong>Name:</strong> <input type="text" name="name" id="name" /><br>
<strong>Email:</strong> <input type="text" name="email" id="email" /><br>
<br>
<strong>Gender</strong><br>
<input type="radio" name="gen" value="Male">Male</input><br>
<input type="radio" name="gen" value="Female">Female</input><br>
<br>
<select name="age">
<option value="Under 30">Under 30</option><br>
<option value="Between 30 and 60">Between 30 and 60</option><br>
<option value="60+">60+</option>
</select>
<br>
Comments: <textarea name="comments" cols="20" rows="5"> </textarea>
</fieldset>
<input type="submit" name="submit" value="Submit my Information" />
</form>
</body>
</html>
<?
}
else {
echo "Thank you, ".$name." for your comments: " . "<strong>" . $comments . "</strong>";
echo "<br>We will reply to you at:" . "<em>" . $email . "</em>";
}
?>
I need it to validate the fields: name, email, comments for empty strings (not allowed) and not allow unselected radio buttons for gender and age selection.
Can anyone help
<?php
// to eventually re-fill the fields
$name = "";
$email = "";
$gender = "";
$age = "";
$comments = "";
// to re-select a radio button and select option
$Mchecked = "";
$Fchecked = "";
$selectMinus_30="";
$select30_to_60="";
$select60_plus="";
// to display errors
$error = "";
$done=false;
if (isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["age"])){
if($_POST["name"]==""){
$error = "empty name <br/>";
}
if($_POST["email"]==""){
$error = $error . "empty mail <br/>";
}
if(!isset($_POST["gen"])){
$error = $error . "empty gender <br/>";
}
else{
$gender = $_POST["gen"];
if ($gender == "Male"){
$Mchecked = "checked";
}
else if ($gender == "Female"){
$Fchecked = "checked";
}
}
if($_POST["comments"]==""){
$error = $error . "error: empty comments <br/>";
}
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["comments"];
$age = $_POST["age"];
if ($age == "Under 30"){
$selectMinus_30 = "selected";
}
else if ($age == "Between 30 and 60"){
$select30_to_60 = "selected";
}
else if ($age == "60+"){
$select60_plus = "selected";
}
if ($error==""){
$done=true;
}
}
?>
<html>
<head>
<title>Lab6 : P1</title>
</head>
<body>
<?php if (!$done){ ?>
<fieldset>
<legend><h4>Enter your information in the fields below</h4></legend>
<p class="error" style="color:red;"><?php echo $error;?></p>
<form name="info" method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<strong>Name:</strong> <input type="text" name="name" id="name" value="<?php echo $name; ?>" /><br/>
<strong>Email:</strong> <input type="text" name="email" id="email" value="<?php echo $email; ?>" /><br/>
<br/>
<strong>Gender</strong><br/>
<input type="radio" name="gen" value="Male" <?php echo $Mchecked;?>>Male</input><br/>
<input type="radio" name="gen" value="Female" <?php echo $Fchecked;?>>Female</input><br/>
<br/>
<select name="age" value="<?php echo $age;?>">
<option value="Under 30" <?php echo $selectMinus_30;?>>Under 30</option><br/>
<option value="Between 30 and 60" <?php echo $select30_to_60;?>>Between 30 and 60</option><br/>
<option value="60+" <?php echo $select60_plus;?>>60+</option>
</select>
<br/>
Comments: <textarea name="comments" cols="20" rows="5"><?php echo $comments; ?></textarea>
</fieldset>
<input type="submit" name="submit" value="Submit my Information" />
</form>
<?php }else{
echo "Thank you, ".$name." for your comments: " . "<strong>" . $comments . "</strong>";
echo "<br/>We will reply to you at:" . "<em>" . $email . "</em>";
} ?>
</body>
</html>
Here I did proper validation, and also re-fill the form when you submit with any empty field.
P.S. Thank you Marc B , I didn't realize that my first post was aweful.