I'm trying to figure out how to apply a conditional to check if a year is a Leap year or Not. But when I add the leap function it just does not work.
Any idea how to make it work?
This is my code :
<?php
$name = "";
$character = "";
$email = "";
$birth_year = 1969;
$validation_error = "";
$existing_users = ["admin", "guest"];
$options = ["options" => ["min_range" => 1920, "max_range" => date("Y")]];
function leap($year) {
date('L', strtotime("$year-01-01")) ? TRUE : FALSE;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$raw_name = trim(htmlspecialchars($_POST["name"]));
if (in_Array($raw_name,$existing_users)){
$validation_error .= "This name is taken. <br>";
} else {
$name = $raw_name;
}
$raw_character = $_POST["character"];
if (in_array($raw_character,["wizard", "mage", "orc"])) {
$character = $raw_character;
} else {
$validation_error .= "You must pick a wizard, mage, or orc. <br>";
}
$raw_email = $_POST["email"];
if (filter_var($raw_email,FILTER_VALIDATE_EMAIL)) {
$email = $raw_email;
} else {
$validation_error .= "Invalid email. <br>";
}
$raw_birth_year = $_POST["birth_year"];
if (filter_var($raw_birth_year,FILTER_VALIDATE_INT,$options)){
$birth_year = $raw_birth_year;
if ($raw_character === "mage") {
if (!leap($birth_year)){
$validation_error .= "Mages have to be born on leap years. <br>";
}}
} else {
$validation_error .= "That can't be your birth year. <br>";
}
}
?>
<h1>Create your profile</h1>
<form method="post" action="">
<p>
Select a name: <input type="text" name="name" value="<?php echo $name;?>" >
</p>
<p>
Select a character:
<input type="radio" name="character" value="wizard" <?php echo ($character=='wizard')?'checked':'' ?>> Wizard
<input type="radio" name="character" value="mage" <?php echo ($character=='mage')?'checked':'' ?>> Mage
<input type="radio" name="character" value="orc" <?php echo ($character=='orc')?'checked':'' ?>> Orc
</p>
<p>
Enter an email:
<input type="text" name="email" value="<?php echo $email;?>" >
</p>
<p>
Enter your birth year:
<input type="text" name="birth_year" value="<?php echo $birth_year;?>">
</p>
<p>
<span style="color:red;"><?= $validation_error;?></span>
</p>
<input type="submit" value="Submit">
</form>
<h2>Preview:</h2>
<p>
Name: <?=$name;?>
</p>
<p>
Character Type: <?=$character;?>
</p>
<p>
Email: <?=$email;?>
</p>
<p>
Age: <?=date("Y")-$birth_year;?>
</p>
Im using this function to find if a year is Leap or not
function leap($year) {
date('L', strtotime("$year-01-01")) ? TRUE : FALSE;
}
And this is the conditional that does not work :(
if ($raw_character === "mage") {
if (!leap($birth_year)){
$validation_error .= "Mages have to be born on leap years. <br>";
}}
I think your problem is the function is not returning anything, try :
function leap($year) {
return date('L', strtotime("$year-01-01")) ? TRUE : FALSE;
}
Related
I'm creating a simple web app that calculates the age of when you're going to graduate. My program runs fine in eclipse but as soon as I push it to the server and push my button (submit) it redirects to a 404 error. I'm using ipages and I'm aware that they are using php 5.6. Any helpful tips would help out a ton.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">
<html>
<head>
<title>Graduation Calculator</title>
</head>
<body>
<img alt="Image goes here..." src="Balloon-Banner.jpg" width = "1050" height="180">
<form action="grad.php" method="POST">
<center>
<br>
<br>
<br>
<label><?php echo "Today is " . date("m/d/Y"); ?></label>
<br>
<br>
<br>
<label>Enter your birth year: </label>
<input type="text" name="birthYear" />
<label>Enter your graduation year: </label>
<input type="text" name="gradYear" />
<br>
<label>Enter your Birth Month: </label>
<input type = "text" name = "birthMonth"/>
<label> Enter your graduation month</label>
<input type = "text" name = "gradmonth" />
<br>
<label> Enter your birthday</label>
<input type = "text" name = "birthDay" />
<label>Enter your graduation day: </label>
<input type="text" name="gradday" />
<br>
<input type='submit' value='Graduation Age' id = 'submit' />
</center>
</form>
<?php
$submitted = ! empty ( $_POST );
if ($submitted == true)
{
$bYear = (int) $_POST ['birthYear'];
$gYear = (int) $_POST ['gradYear'];
$gMonth = (int) $_POST['gradmonth'];
$bMonth = (int) $_POST['birthMonth'];
$bday = (int) $_POST['birthDay'];
$gday = (int) $_POST ['gradday'];
$age = getAge($bYear, $gYear, $bMonth, $gMonth, $bday, $gday);
if($age!= NULL){
echo "You will be " . $age . " at your graduation.";
}
else{
echo "INVALID INPUT, PLEASE TRY AGAIN";
}
}
function getAge( $bYear, $gYear, $bMonth, $gMonth, $bday, $gday)
{
If($bYear> $gYear || $bMonth>12 || $gMonth >12 || $bday >31 || $gday >31 || $bYear == 0 || $gYear == 0 || $bMonth == 0 || $bday == 0 || $gMonth ==0|| $gday == 0){
return NULL;
}
$age = $gYear - $bYear;
if($bMonth == $gMonth){
if($bday <= $gday){
return $age;
}
else{
$age = $age-1;
return $age;
}
}
elseif($bMonth < $gMonth){
return $age;
}
else{
return $age-1;
}
return $age;
}
?>
</body>
</html>
If you're executing your front-end and back-end code in the same file, just keep it simple and just do it in the same file unless you have a framework.
Change <form action="grad.php" method="POST"> to <form method="POST">.
Should work, if not we'll try to work something out ;)
Remove the action="grad.php" from form. So it will submit to self.
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Book A Table</title>
</head>
<body>
<h1>Book A Table</h1>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $numErr=$dateErr = $timeErr = personsErr="";
$name = $email = $num= $date = $time = $persons = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["num"])) {
$numErr = "Number is required";
} else {
$num = test_input($_POST["num"]);
}
if (empty($_POST["date"])) {
$dateErr = "Date is required";
} else {
$date = test_input($_POST["date"]);
}
if (empty($_POST["time"])) {
$timeErr = "Time is required";
} else {
$time = test_input($_POST["time"]);
}
if (empty($_POST["persons"])) {
$personsErr = "Number of persons is required";
} else {
$persons = test_input($_POST["persons"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Full Name<br> <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail<br> <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Contact Number <input type="text" name="num">
<span class="error"><?php echo $numErr;?></span>
<br><br>
Reservation Date*<br> <input type="date" name="date"><br><br>
<span class="error"><?php echo $dateErr;?></span>
<br><br>
Reservation Time*<br>(Mon - Thur: 18:00 - 23:00 Fri - Sun: 12:00 - 00:00)<br> <input type="time" name="time"><br><br>
<span class="error"><?php echo $timeErr;?></span>
<br><br>
Number of Persons*<br> <input type="text" name="persons"><br><br>
<span class="error"><?php echo $personsErr;?></span>
<br><br>
Comments<br><textarea name="comment" rows="5" cols="40"></textarea><br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $num;
echo "<br>";
echo $date;
echo "<br>";
echo $time;
echo "<br>";
echo $persons;
echo "<br>";
?>
</body>
</html>
I just started learning PHP today so im a beginner and im not very
familiar with it. trying to use php on a local host to make a booking
reservation page for a restaurant. What i was trying to do is make a
form and validate it so that the user wont be able to leave out any
required fields. however it doesnt seem to work. can anyone tell me
where i went wrong please ?
if there aren't any errors you have to check the name of the php file? does it have the extension ".php"?
Are you referring the right directory?
is the server running?
I have a simple example of check box's which remember what has been selected after the form has been submitted and there is an error.
That part works great... but, I would like to post the resultant 'checked' boxes to my forms mail function.
What I have now only reports if its checked or unchecked I would prefer to have the checked box's 'value' without the unchecked box even registering.
<?php
$CB_1 = 'unchecked';
$CB_2 = 'unchecked';
$CB_3 = 'unchecked';
$CB_4 = 'unchecked';
$CB_5 = 'unchecked';
if (isset($_POST['submit'])) {
if (isset($_POST['CB_1'])) {$CB_1 = $_POST['CB_1'];
if ($CB_1 == 'item_01') {$CB_1 = 'checked';}
}
if (isset($_POST['CB_2'])) {$CB_2 = $_POST['CB_2'];
if ($CB_2 == 'item_02') {$CB_2 = 'checked';}
}
if (isset($_POST['CB_3'])) {$CB_3 = $_POST['CB_3'];
if ($CB_3 == 'item_03') {$CB_3 = 'checked';}
}
if (isset($_POST['CB_4'])) {$CB_4 = $_POST['CB_4'];
if ($CB_4 == 'item_04') {$CB_4 = 'checked';}
}
if (isset($_POST['CB_5'])) {$CB_5 = $_POST['CB_5'];
if ($CB_5 == 'item_05') {$CB_5 = 'checked';}
}
}
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "E-mail address not valid.";
}
} else {
$error .= "E-mail address is required.";
}
if (empty($error)) {
$from = 'From: '. #TEST .' <'. $email .'>';
$to = "someone#company.com";
$subject = "CHECKBOX TEST";
$content = "
checkbox selections:
check box 01: $CB_1
check box 02: $CB_2
check box 03: $CB_3
check box 04: $CB_4
check box 05: $CB_5
";
$success = mail($to,$subject,$content,$from);
}
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<?php if (!empty($error)) echo $error ?>
<br><br><br>
e-mail: <input type="text" name="email" value="<?php if (isset ($_POST {'email'})) { echo $_POST['email']; } ?>" />
<P>
<input type="checkbox" name="CB_1" value="item_01" <?PHP echo $CB_1; ?> /> Item 01
<input type="checkbox" name="CB_2" value="item_02" <?PHP echo $CB_2; ?> /> Item 02
<input type="checkbox" name="CB_3" value="item_03" <?PHP echo $CB_3; ?> /> Item 03
<input type="checkbox" name="CB_4" value="item_04" <?PHP echo $CB_4; ?> /> Item 04
<input type="checkbox" name="CB_5" value="item_05" <?PHP echo $CB_5; ?> /> Item 05
<P>
<input type="submit" name="submit" value="Submit"></input>
</form>
I know this may not necessarily answer the question but a way you could make your code more efficiant is do this.
for($i=1; $i<=5;$i++)
{
if(isset($_POST['submit'])&& isset($_POST['CB_'.$i]) && $CB_.$i=='item_0'.$i)
{
$CB_.$i = $_POST['CB_'.$i];
$CB_.$i = 'checked';
}
}
If you fix it that way it may also make it easier for us to debug.
okay, I found a way to do what I wanted but I'm fairly sure it's not the way someone who has real experience with PHP would do it. Any suggestions?
redelman431, thanks for your suggestion but it was really too advanced for my skill level.
<?php
if(isset($_POST['item_01'])) {$item_01 = 'Item 01';}
if(isset($_POST['item_02'])) {$item_02 = 'Item 02';}
if(isset($_POST['item_03'])) {$item_03 = 'Item 03';}
if(isset($_POST['item_04'])) {$item_04 = 'Item 04';}
if(isset($_POST['item_05'])) {$item_05 = 'Item 05';}
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "E-mail address not valid.";
}
} else {
$error .= "E-mail address is required.";
}
if (empty($error)) {
$from = 'From: '. #TEST .' <'. $email .'>';
$to = "someone#company.com";
$subject = "CHECKBOX TEST";
$content = "
checkbox selections:
checked box's: $item_01 $item_02 $item_03 $item_04 $item_05
";
$success = mail($to,$subject,$content,$from);
}
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<span style="color: red;"><?php if (!empty($error)) echo $error ?></span>
<br><br><br>
e-mail: <input type="text" name="email" value="<?php if (isset ($_POST {'email'})) { echo $_POST['email']; } ?>" />
<P>
<input type="checkbox" name="item_01" value="Item 01"
<?php if(isset($_POST['item_01'])) { echo 'checked'; } ?> /> Item 01
<input type="checkbox" name="item_02" value="Item 02"
<?php if(isset($_POST['item_02'])) { echo 'checked'; } ?> /> Item 02
<input type="checkbox" name="item_03" value="Item 03"
<?php if(isset($_POST['item_03'])) { echo 'checked'; } ?> /> Item 03
<input type="checkbox" name="item_04" value="Item 04"
<?php if(isset($_POST['item_04'])) { echo 'checked'; } ?> /> Item 04
<input type="checkbox" name="item_05" value="Item 05"
<?php if(isset($_POST['item_05'])) { echo 'checked'; } ?> /> Item 05
<P>
<input type="submit" name="submit" value="Submit"></input>
</form>
I found what I was looking for I suppose in the way of an array which I think 'redelman431' was trying to get me to do but it didn't make any sense to me at the time.
I then stumbled onto another array by 'David Bélanger' that for some reason made more sense to me so I used it into my check box's and it works fabulously.
the new problem is that I cant get the check box's that have been checked to remember that if there is an error elsewhere on the page which is a disaster as my final form has a ton of them.
Any ideas?
<?php
# Default Vars
$_group_01 = '';
if(isset($group_01) === TRUE){
# Is Array ?
if(is_array($group_01) === TRUE){
# Count
$c = count($group_01);
# Loop
for($i=0; $i < $c; $i++){
$_group_01.= (isset($group_01[$i]) === TRUE ? $group_01[$i] : '').($i == ($c-1) ? '' : ($i == $c-2 ? ' and ' : ', '));
}
}
}
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['email'])) {
$email = $_POST['email'];
if (!preg_match("/^[a-z0-9]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)){
$error .= "E-mail address not valid.";
}
} else {
$error .= "E-mail address is required.";
}
if (empty($error)) {
$from = 'From: '. TEST .' <'. $email .'>';
$to = "someone#company.com";
$subject = "CHECKBOX TEST";
$content = "
checkbox selections:
Items Checked: $_group_01
";
$success = mail($to,$subject,$content,$from);
}
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<span style="color: red;"><?php if (!empty($error)) echo $error ?></span>
<br><br><br>
e-mail: <input type="text" name="email" value="<?php if (isset ($_POST {'email'})) { echo $_POST['email']; } ?>" />
<P>
<input type="checkbox" name="group_01[]" value="Item 01"
<?php if(isset($_POST['group_01'])) { echo 'checked'; } ?> />Item 01
<input type="checkbox" name="group_01[]" value="Item 02"
<?php if(isset($_POST['group_01'])) { echo 'checked'; } ?> />Item 02
<input type="checkbox" name="group_01[]" value="Item 03"
<?php if(isset($_POST['group_01'])) { echo 'checked'; } ?> />Item 03
<input type="checkbox" name="group_01[]" value="Item 04"
<?php if(isset($_POST['group_01'])) { echo 'checked'; } ?> />Item 04
<input type="checkbox" name="group_01[]" value="Item 05"
<?php if(isset($_POST['group_01'])) { echo 'checked'; } ?> />Item 05
<P>
<input type="submit" name="submit" value="Submit"></input>
</form>
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
EDIT/UPDATE:
I moved my php code from my process.php file to the top of my contact.php file and it worked. So what am I missing from the process.php file that is not redirecting it back to the contact.php page?
This is my html in contact.php
<?php echo $message; ?>
<form action="process.php" method="post" name="sign_up">
<input type="text" name="first_name" placeholder="First Name" value="<?php echo $_POST[first_name]; ?>" required/>
<input type="text" name="last_name" placeholder="Last Name" value="<?php echo $_POST[last_name]; ?>" required/><br>
<label class="bill-address">Billing Address:<br>
<input type="text" name="address1" placeholder="Address 1" value="<?php echo $_POST[address1]; ?>" required/><br>
<input type="text" name="address2" placeholder="Address 2" value="<?php echo $_POST[address2]; ?>" /><br>
<input type="text" name="city" placeholder="City" value="<?php echo $_POST[city]; ?>" required/>
</label>
<?php
$state_list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'WV'=>"West Virginia",
'WI'=>"Wisconsin",
'WY'=>"Wyoming");
?>
<select name="state">
<?php
while(list($k,$v) = each($state_list)) {
$selected = '';
if ($k == $_POST[state]) {
$selected = ' selected="true"';
}
echo "<option value=\"$k\"$selected>$v</option>\n";
}
?>
</select>
<input type="text" name="zip" placeholder="Zip Code" value="<?php echo $_POST[zip]; ?>" required/>
<br style="clear: left;" />
<input type="email" name="email" placeholder="you#youremail.com" value="<?php echo $_POST[email]; ?>" required/>
<input type="tel" name="phone" placeholder="Phone" value="<?php echo $_POST[phone]; ?>" required/>
<h3>Choose your Package</h3>
<select name="package">
<option value="Free">Free!</option>
<option value="Basic">Basic</option>
<option value="Corporate">Corporate</option>
<option value="Enterprise">Enterprise</option>
<option value="Enterprise_20">Enterprise 20</option>
<option value="Enterprise_50">Enterprise 50</option>
<option value="Enterprise_100">Enterprise 100</option>
</select>
<h3>Add Media Package?</h3>
<input type="radio" name="Yes" value="yes" />Yes
<input type="radio" name="No" value="no" />No
<button type="submit" class="btn">Send »</button>
<?php echo $success_message; ?>
</form>
And this is my process.php
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when submit has been pressed, begin form validate
if(isset($_POST['submit'])) {
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message .= "Please include your first name. ";
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message .= "Please include your last name. ";
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message .= "Please include your billing address. ";
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message .= "Please enter a city. ";
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message .= "Please select a state. ";
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message .= "Please include a zip code. ";
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message .= "Please include your phone number. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message .= "A valid email is required. ";
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message .= "You forgot to select a service package. ";
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
unset($_POST);
}
}
It is not working. Also the html5 validation isn't even working either. Is there something wrong with my form markup?
When you click on submit, your browser navigates to process.php. All of the code from contact.php is forgotten and a new page is generated.
There is no implied link between the two pages. The messages from process.php will not apppear on contact.php. Currently, process.php doesn't echo anything, so you're probably arriving at a blank page.
An alternate way to do this would be to merge the two pages like this:
<?php
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when submit has been pressed, begin form validate
if(isset($_POST['submit'])) {
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message .= "Please include your first name. ";
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message .= "Please include your last name. ";
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message .= "Please include your billing address. ";
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message .= "Please enter a city. ";
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message .= "Please select a state. ";
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message .= "Please include a zip code. ";
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message .= "Please include your phone number. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message .= "A valid email is required. ";
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message .= "You forgot to select a service package. ";
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
//don't clear this, you need this to re-populate the page below
//unset($_POST);
}
}
?><!doctype html>
<html>
<head>
...
</head>
<body>
<?php echo $message; ?>
<form action="contact.php" method="post" name="sign_up">
<input type="text" name="first_name" placeholder="First Name" value="<?php echo $_POST[first_name]; ?>" required/>
<input type="text" name="last_name" placeholder="Last Name" value="<?php echo $_POST[last_name]; ?>" required/><br>
<label class="bill-address">Billing Address:<br>
<input type="text" name="address1" placeholder="Address 1" value="<?php echo $_POST[address1]; ?>" required/><br>
<input type="text" name="address2" placeholder="Address 2" value="<?php echo $_POST[address2]; ?>" /><br>
<input type="text" name="city" placeholder="City" value="<?php echo $_POST[city]; ?>" required/>
</label>
<?php
$state_list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'WV'=>"West Virginia",
'WI'=>"Wisconsin",
'WY'=>"Wyoming");
?>
<select name="state">
<?php
while(list($k,$v) = each($state_list)) {
$selected = '';
if ($k == $_POST[state]) {
$selected = ' selected="true"';
}
echo "<option value=\"$k\"$selected>$v</option>\n";
}
?>
</select>
<input type="text" name="zip" placeholder="Zip Code" value="<?php echo $_POST[zip]; ?>" required/>
<br style="clear: left;" />
<input type="email" name="email" placeholder="you#youremail.com" value="<?php echo $_POST[email]; ?>" required/>
<input type="tel" name="phone" placeholder="Phone" value="<?php echo $_POST[phone]; ?>" required/>
<h3>Choose your Package</h3>
<select name="package">
<option value="Free">Free!</option>
<option value="Basic">Basic</option>
<option value="Corporate">Corporate</option>
<option value="Enterprise">Enterprise</option>
<option value="Enterprise_20">Enterprise 20</option>
<option value="Enterprise_50">Enterprise 50</option>
<option value="Enterprise_100">Enterprise 100</option>
</select>
<h3>Add Media Package?</h3>
<input type="radio" name="Yes" value="yes" />Yes
<input type="radio" name="No" value="no" />No
<button type="submit" class="btn">Send »</button>
<?php echo $success_message; ?>
</form>
</body>
</html>
The $message and $success_message variables are now saved and they should display in the page markup below.
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when submit has been pressed, begin form validate
if(isset($_POST['submit'])) {
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message = "Please include your first name. ";
echo $message;
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message = "Please include your last name. ";
echo $message;
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message = "Please include your billing address. ";
echo $message;
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message = "Please enter a city. ";
echo $message;
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message = "Please select a state. ";
echo $message;
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message = "Please include a zip code. ";
echo $message;
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message = "Please include your phone number. ";<
echo $message;
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message = "A valid email is required. ";
echo $message;
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message = "You forgot to select a service package. ";
echo $message;
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
echo $success_message;
//clear form when submission is successful
unset($_POST);
}
}
i added echo $message for echoing during validation and .= was i think wrong way, otherwise you would have a message that contains all error messages..
Try adding this after the unset( $_POST ) line:
header('Location: contact.php');
That should take you back to the contact.php page.
EDIT:
However, in order for your code completely to work the way you want it, here what I would do.
<?php
session_start();
if (isset ($_SESSION['message'])) {
echo $_SESSION['message'];
session_destroy();
}
?>
<form action="process.php" method="post" name="sign_up">
<input type="text" name="first_name" placeholder="First Name" value="<?php echo $_POST[first_name]; ?>" />
<input type="text" name="last_name" placeholder="Last Name" value="<?php echo $_POST[last_name]; ?>" /><br>
<label class="bill-address">Billing Address:<br>
<input type="text" name="address1" placeholder="Address 1" value="<?php echo $_POST[address1]; ?>" /><br>
<input type="text" name="address2" placeholder="Address 2" value="<?php echo $_POST[address2]; ?>" /><br>
<input type="text" name="city" placeholder="City" value="<?php echo $_POST[city]; ?>" />
</label>
<?php
$state_list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'WV'=>"West Virginia",
'WI'=>"Wisconsin",
'WY'=>"Wyoming");
?>
<select name="state">
<?php
while(list($k,$v) = each($state_list)) {
$selected = '';
if ($k == $_POST[state]) {
$selected = ' selected="true"';
}
echo "<option value=\"$k\"$selected>$v</option>\n";
}
?>
</select>
<input type="text" name="zip" placeholder="Zip Code" value="<?php echo $_POST[zip]; ?>" />
<br style="clear: left;" />
<input type="email" name="email" placeholder="you#youremail.com" value="<?php echo $_POST[email]; ?>" />
<input type="tel" name="phone" placeholder="Phone" value="<?php echo $_POST[phone]; ?>" />
<h3>Choose your Package</h3>
<select name="package">
<option value="Free">Free!</option>
<option value="Basic">Basic</option>
<option value="Corporate">Corporate</option>
<option value="Enterprise">Enterprise</option>
<option value="Enterprise_20">Enterprise 20</option>
<option value="Enterprise_50">Enterprise 50</option>
<option value="Enterprise_100">Enterprise 100</option>
</select>
<h3>Add Media Package?</h3>
<input type="radio" name="Yes" value="yes" />Yes
<input type="radio" name="No" value="no" />No
<button type="submit" class="btn">Send »</button>
<?php
//session already started on line 2
if (isset( $_SESSION['success'] )) {
echo $_SESSION['success'];
session_destroy();
}
?>
</form>
That's for contact.php, and
<?php
//when submit has been pressed, begin form validate else return to contact.php
if ( $_SERVER[ 'REQUEST_METHOD' ] == "POST" ) {
session_start();
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message .= "Please include your first name. ";
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message .= "Please include your last name. ";
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message .= "Please include your billing address. ";
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message .= "Please enter a city. ";
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message .= "Please select a state. ";
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message .= "Please include a zip code. ";
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message .= "Please include your phone number. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message .= "A valid email is required. ";
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message .= "You forgot to select a service package. ";
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
unset($_POST);
$_SESSION['success']=$success_message;
}
else {
$_SESSION['message'] = $message;
}
header('Location: contact.php');
} // end of if ( $_SERVER[ 'REQUEST_METHOD' ] == "POST" )
else header('Location: contact.php');
?>
process.php
The following control I think was creating the biggest confusion in your code:
//when submit has been pressed, begin form validate
if(isset($_POST['submit']))
as soon as I replaced it, everything started to work better.
<?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.