PHP Form, when no text is entered - php

I'm creating a mobile landing page and I have also created a form that allows me to create more, by duplicating a folder that's host to a template file. The script then takes you to a page where you input the company details one by one and press submit. Then the page is created.
My problem is, when a field is left out (YouTube for instance), the button is created and is blank. I would like there to be a default text for when there is no text. I've tried a few things and have been struggling to make this work for DAYS!
<?php
$company = $_POST["company"];
$phone = $_POST["phone"];
$colour = $_POST["colour"];
$email = $_POST["email"];
$website = $_POST["website"];
$video = $_POST["video"];
?>
<div id="contact-area">
<form method="post" action="generate.php"><br>
<input type="text" name="company" placeholder="Company Name" /><br>
<input type="text" name="slogan" placeholder="Slogan" /><br>
<input class="color {required:false}" name="colour" placeholder="Company Colour"><br>
<input type="text" name="phone" placeholder="Phone Number" /><br>
<input type="text" name="email" placeholder="Email Address" /><br>
<input type="text" name="website" placeholder="Full Website - Include http://" /><br>
<input type="text" name="video" placeholder="Video URL" /><br>
<input type="submit" value="Generate QuickLinks" style="background:url(images/submit.png) repeat-x; color:#FFF"/>
</form>
That's the form. It takes the variables and post's them to the file below.
<?php
$File = "includes/details.php";
$Handle = fopen($File, 'w');
?>
<?php
$File = "includes/details.php";
$Handle = fopen($File, 'w');
$Data = "<div id='logo'>
<h1 style='color:#$_POST[colour]'>$_POST[company]</h1>
<h2>$_POST[slogan]</h2>
</div>
<ul data-role='listview' data-inset='true' data-theme='b'>
<li style='background-color:#$_POST[colour]'><a href='tel:$_POST[phone]'>Phone Us</a></li>
<li style='background-color:#$_POST[colour]'><a href='mailto:$_POST[email]'>Email Us</a></li>
<li style='background-color:#$_POST[colour]'><a href='$_POST[website]'>View Full Website</a></li>
<li style='background-color:#$_POST[colour]'><a href='$_POST[video]'>Watch Us</a></li>
</ul>
\n";
fwrite($Handle, $Data);
fclose($Handle);
?>
and there is what the form turns into. I need there to be a default link put in incase the field is left blank, witch it is sometimes. Thanks in advance guys.

Just use something like this for every element:
$company = trim($_POST["company"]);
if (!isset($company) || empty($company)) {
$company = "Not filled in";
}
I added trim to make sure spaces are ignored

Use following format for each variables:
$company = (isset($_POST["company"]) && !empty($_POST["company"]))? $_POST["company"]:"";
"" at the end of the can assign any default values.

It's usually easier to work with post variables if you wrap the access in a function:
function post($key, $default = '') {
if (!isset($_POST[$key])) return $default;
$value = trim($_POST[$key]);
if ($value == '')
return $default;
else
return $value;
}
You can now assign your variables like this:
$company = post('company');
$phone = post('phone', 'Not provided');
$colour = post('colour', 'blue');
... and so on...

Can you get away with simply wrapping your variable definitions in code like:
if (strlen($_POST["company"]) > 0) {
$company = $_POST["company"];
} else {
$company = "default company";
}
That will let you specify a default value that will be over-written by the user's data if there is any.

Related

Trying to break the PHP script which processes $_POST form data

I can't find any explicit information on this.
I have an HTML5 form...
which outputs to an external PHP script
which saves the variables output by the form as $_SESSION variables
which are then passed on to another page
which displays them
I've not (yet) escaped any of the data from any of the form fields.
Yet, when I enter a ' or a " or a & into the <textarea> of the form, everything continues working smoothly and nothing breaks.
I'm just as happy that it doesn't (since I want my form processing to be as robust as possible), but why doesn't it?
Is there some behind-the-scenes automatic escaping going on that I don't know about?
I am keen to find out if there is an authoritative source which explains what is going on.
The Form Page (HTML5):
<form class="contactform" method="post" action="/form-processing.php">
<fieldset>
<legend>Please Enter your Contact Details</legend>
<ul>
<li><label for="contactName">Contact Name:</label><input type="text" id="contactName" name="contactName" placeholder="Your Full Name" required /></li>
<li><label for="company">Company:</label><input type="text" id="company" name="company" placeholder="Your Company" required /></li>
<li><label for="telephone">Telephone:</label><input type="tel" id="telephone" name="telephone" placeholder="Your Work Telephone" required /></li>
<li><label for="email">Email:</label><input type="email" id="email" name="email" placeholder="Your Work Email" required /></li>
<li><label for="message">Message:</label>
<textarea id="message" name="message" placeholder="Write your message here..." required></textarea></li>
</ul>
</fieldset>
<input type="submit" value="Send your message" />
</form>
The Form Processing Page (PHP)
$Contact_Name = $_POST['contactName'];
$Company = $_POST['company'];
$Telephone = $_POST['telephone'];
$Email = $_POST['email'];
$Message = $_POST['message'];
if (($Contact_Name != '') && ($Company != '') && ($Telephone != '') && ($Email != '') && ($Message != '')) {
[...SCRIPT HERE...]
session_start();
$_SESSION['contactName'] = $Contact_Name;
$_SESSION['company'] = $Company;
$_SESSION['telephone'] = $Telephone;
$_SESSION['email'] = $Email;
$_SESSION['message'] = $Message;
header('Location: http://'.$_SERVER['HTTP_HOST'].'/confirmation-page.php');
}
The Confirmation Page (PHP)
if ((isset($_SESSION['contactName'])) && (isset($_SESSION['company'])) && (isset($_SESSION['telephone'])) && (isset($_SESSION['email'])) && (isset($_SESSION['message']))) {
$Contact_Name = $_SESSION['contactName'];
$Company = $_SESSION['company'];
$Telephone = $_SESSION['telephone'];
$Email = $_SESSION['email'];
$Message = $_SESSION['message'];
echo '<p>Your message has been sent.</p>
<dl>
<dt>Contact Name:</dt>
<dd>'.$Contact_Name.'</dd>
<dt>Company:</dt>
<dd>'.$Company.'<dd>
<dt>Telephone:</dt>
<dd>'.$Telephone.'<dd>
<dt>Email:</dt>
<dd>'.$Email.'</dd>
</dl>
<p>Message:</p>
<pre>'.$Message.'</pre>
<p>Thank you for your message.</p>
<p>We will be in touch.</p>';
I would have expected ' to break the PHP script the form data is passed to... but it doesn't. Any idea why not? I thought that's how XSS attacks were supposed to work?
my comments in answer form:
20 years ago the & and " (rather than & and ") may have broken some browsers when rendering the html, but nowadays they're able to handle it OK (& & " are correct though).
PHP variables may contain any arbitrary string (binary data even).. there's no issue with a var containing ' or ".
When assigning values pragmatically, they need escaped:
$myVar = 'sha\'zam!'; // ' needs escaped as the string is enclosed with '
$myVar = "dblquote -> \"!" // " needs escaped as the string is enclosed with "
As you're not doing any database stuff, there's nothing to "break" on the server side, but since you're not sanitizing stuff.... enter some values like
</form> or
<script>alert('shazam!')</script>
This is how an attacker could end up getting session id (of victim) or other sensitive information.

Passing PHP variable data onto another page after validation

While I found something similar to this question on here it didn't answer my question outright.
I have set up this php script to validate the form data, which works, after its validated I want it to then pass the info onto another script page to let the user then verify their input data and then mail the data. Its at this state that I'm having trouble. I've spent the last few days trying to find a solution to this and unfortunately coming up short.
<?php
$name_error = '';
$email_error = '';
$comments_error = '';
$error = false;
if (!empty($_POST['submitted']))
{ //if submitted, the validate.
$name = trim($_POST['name']);
if (empty($name))
{
$name_error='Name is required';
$error = true;
}
$email = trim($_POST['email']);
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
$email_error='E-mail address not valid';
$error = true;
}
$comments = trim($_POST['comments']);
if (empty($comments))
{
$comments_error='Comments are required';
$error = true;
}
if ($error == false)
{
$name_send = $name;
$email_send = $email;
$comments_send = $comments;
/* Redirect visitor to the thank you page */
header('Location: /mail.php');
exit();
}
}
The form this is attached to:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
<label>Your Name</label><br />
<input type="text" name="name" style="width:95%" class="text" value='<?php echo htmlentities($name) ?>' />
<br/>
<span class='error'><?php echo $name_error ?></span>
<br />
<label>Email</label><br />
<input type="email" name="email" style="width:95%" class="text" value='<?php echo htmlentities($email) ?>' />
<br/>
<span class='error'><?php echo $email_error ?></span>
<br />
<label for="comments" style="font-size:16px;">Feedback Comments</label><br />
<textarea name="comments" style="width:95%;" rows="8" value='<?php echo htmlentities($comments) ?>'></textarea>
<br />
<span class='error'><?php echo $comments_error ?></span>
<br />
<input type="checkbox" name="allowCommentPublish" checked="checked" />
<label for="allowCommentPublish" style="font-size:10px;">Allow these comments to be used on our website</label>
<fieldset class="optional">
<h2>[ OPTIONAL ]</h2>
<label>Company Name</label><br />
<input type="text" name="companyName" style="width:95%" class="text" />
<br/>
<label>Phone</label><br />
<input type="text" name="phone" style="width:95%" class="text" /><br/>
<div style="margin:5px 0px;">
<input type="checkbox" name="incmarketing" />
<label style="font-size:10px;"> Yes, you can email me specials and promotions.</label>
<br/>
</div>
</fieldset>
<fieldset>
<input type="submit" name="submitted" value="Send" />
</fieldset>
I will point out im focusing on the main data inputs: Name E-mail and comments.
I need the info from this form to be sent onward but i dont know exactly how to do this and any help will be appreciated greatly.
For passing the values to next page you will have to use either of the three methods.
1. Set cookies with the data.
2. Use global variable session.
3.Pass the data in the url.
For cookies u can set cookies with the values like
setcookie('name',$name);
in ur next page read those cookie data
For sessions:
$_SESSION['name']= $name;
for reading data from cookies & session:
$name = $_COOKIE['name'];
$name = $_SESSION['name'];
For using sessions you must add the line
session_start();
at the start of both the pages that send or receive(use) the data
and for urls
header('Location: /mail.php?name=$name&email=$email&comment=$comments');
Read more on using session
If you need to pass values from one script to another you can use $_SESSION variables. To start a session use: (at the top of the php script)
session_start();
$_SESSION['somename'] = $somevariable;
To access or get that same variable you can use this:
session_start();
$some_other_variable = $_SESSION['somename'];
or you can use hidden input fields.
You can use hidden fields and javascript to submit the form. However as this is the same php page as the original form you will need an if statement
echo '<form name="newForm" action="newpage.php" method="POST">';
echo '<input type="hidden" name="name2" value"' . $name . '">;
echo '<input type="hidden" name="email2" value"' . $email . '">;
echo '<input type="hidden" name="comments2" value"' . $comments . '"></form>;
echo '<script> if (document.getElementById("name2").value != ""){window.onload = function(){ window.document.newForm.submit(); }} </script>';

Php/mysql some data refuses to insert

In my site's registration, the insert is only working for certain data, not sure why
heres the code (I know, no salt, I will fix that next)
if ($id == "0" || $id == null)
{ echo '<title>Start</title>';
$content .= '
<body><center>
<h1>TitleBar</h1>
<img src="logo.png" alt="Smiley face" height="400" width="400">
<form action="?id=loginF" method="POST">
<fieldset>
<legend>LOGIN </legend>
<p><label for="username">Username</label> <input type="text" name="username" required="required" autofocus="autofocus"/></p>
<p><label for="password">Password</label> <input type="password" name="password" required="required"/></p>
<p class="submit"><input type="submit" value="Login"/></p>
</fieldset>
</form>
</center>
';
echo $content;
}
This next section is for after the form is submitted:
if ($id == "loginF")
{
echo '<title>Login</title>';
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['username'];
$snapchat = new Snapchat($username,$password);
echo $username;
$_SESSION['name'] = $username;
$_SESSION['pass'] = $password;
$ulz="INSERT INTO user_attribs(username,email,salted)VALUES('$username'
,'$email','$password')";
mysql_query($ulz);
$content .= '
<ul>
<li>Get Snaplist</li>
<li>Get Friendlist</li>
<li>Send pics</li>
<li>Logout</li>
</ul>
';
echo $content;
}
for example:
top#kek.com with any password will insert as a username
however, any username with, for example, an #hotmail.com address will not insert
what could be the cause of that?
I tried to google it, I honestly have no idea.
EDIT::
I want to be more specific in the error. I did some testing. The following CAN insert: hotmail.com, .hotmail.com, a#hotmail.com, art#hotmail.com, however, a.rt#hotmail.com cannot be inserted. it must be the front period.
After looking at the table description, username was VARCHAR(15)
This was what caused the problem. By extending the column length, I was able to get the data inserted.

PHP - Redisplay forms with valid values in fields and error messages where validation fails

I have created a PHP form to take 4 text fields name, email, username and password and have set validation for these. I have my code currently validating correctly and displaying messages if the code validates or not.
However, I would like for it to keep the correctly validated fields filled when submitted and those that failed validation to be empty with an error message detailing why.
So far I have the following code, the main form.php:
<?php
$self = htmlentities($_SERVER['PHP_SELF']);
?>
<form action="<?php echo $self; ?>" method="post">
<fieldset>
<p>You must fill in every field</p>
<legend>Personal details</legend>
<?php
include 'personaldetails.php';
include 'logindetails.php';
?>
<div>
<input type="submit" name="" value="Register" />
</div>
</fieldset>
</form>
<?php
$firstname = validate_fname();
$emailad = validate_email();
$username = validate_username();
$pword = validate_pw();
?>
My functions.php code is as follows:
<?php
function validate_fname() {
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if (strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)) {
$fname = htmlentities($_POST['fname']);
echo "<p>You entered full name: $fname</p>";
} else {
echo "<p>Full name must be no more than 150 characters and must contain one space.</p>";
} }
}
function validate_email() {
if (!empty($_POST['email'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['email']);
if (filter_var($trimmed, FILTER_VALIDATE_EMAIL)) {
$clean['email'] = $_POST['email'];
$email = htmlentities($_POST['email']);
echo "<p>You entered email: $email</p>";
} else {
echo "<p>Incorrect email entered!</p>";
} }
}
function validate_username() {
if (!empty($_POST['uname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['uname']);
if (strlen($trimmed)>=5 && strlen($trimmed) <=10) {
$uname = htmlentities($_POST['uname']);
echo "<p>You entered username: $uname</p>";
} else {
echo "<p>Username must be of length 5-10 characters!</p>";
} }
}
function validate_pw() {
if (!empty($_POST['pw'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['pw']);
if (strlen($trimmed)>=8 && strlen($trimmed) <=10) {
$pword = htmlentities($_POST['pw']);
echo "<p>You entered password: $pword</p>";
} else {
echo "<p>Password must be of length 8-10 characters!</p>";
} }
}
?>
How can I ensure that when submit is pressed that it will retain valid inputs and empty invalid ones returning error messages.
Preferably I would also like there to be an alternate else condition for initial if(!empty). I had this initially but found it would start the form with an error message.
Lastly, how could I record the valid information into an external file to use for checking login details after signing up via this form?
Any help is greatly appreciated.
Try using a separate variable for errors, and not output error messages to the input field.
You could use global variables for this, but I'm not fond of them.
login.php
<?php
$firstname = '';
$password = '';
$username = '';
$emailadd = '';
$response = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
<fieldset>
<p>Please enter your username and password</p>
<legend>Login</legend>
<div>
<label for="fullname">Full Name</label>
<input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
</div>
<div>
<label for="emailad">Email address</label>
<input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
</div>
<div>
<label for="username">Username (between 5-10 characters)</label>
<input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
</div>
<div>
<label for="password">Password (between 8-10 characters)</label>
<input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
</div>
<div>
<input type="submit" name="" value="Submit" />
</div>
</fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
print $response;
}
?>
//Footer stuff
loginprocess.php
//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
//Here we concatenate the return values of your validation functions.
$response .= validate_fname();
$response .= validate_email();
$response .= validate_username();
$response .= validate_pw();
}
//...or footer stuff.
functions.php
function validate_fname() {
//Note the use of global...
global $firstname;
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if(strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)){
$fname = htmlentities($_POST['fname']);
//..and the setting of the global.
$firstname = $fname;
//Change all your 'echo' to 'return' in other functions.
return"<p>You entered full name: $fname</p>";
} else {
return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
}
}
}
I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.
Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.

php form validation of option field depending on radio field value select from option

I have a form that when on my radio field value they select yes a new field appears to select a city. The drop down options of city starts with select from. I need the first option value which is select from to be empty. So the validation on the specific field only happens when the user selects yes from the radio option and it validates to force the user to select a value.
The html part of the form:
<li>
<label for="printed">Printed:</label>
No<input type="radio" name="printed" value="no" class="morefrom" checked >
Yes<input type="radio" name="printed" value="yes" class="morefrom">
</li>
<li>
<div id="collectfrom">
<label for="fromstore">Collect From:</label>
<select name="fromstore">
<option value=" ">Choose from</option>
<option value="nicosia">Nicosia</option>
<option value="limassol">Limassol</option>
<option value="paphos">Paphos</option>
</select>
</div>
</li>
The jquery to show the option values if yes is selected:
$(document).ready(function(){
$('#collectfrom').css('display','none');
$('.morefrom').click(function(){
if ($('input[name=printed]:checked').val() == "yes" ) {
$('#collectfrom').slideDown(); //Slide Down Effect
} else {
$('#collectfrom').slideUp(); //Slide Up Effect
}
});
});
And the validation in php
if($printed == "yes"){
if(empty($fromstore)){ $action['result'] = 'error'; array_push($text,'You forgot your city'); }
}
Obviously the php validation is wrong. Any help?
NEW EDIT:
Hi,
here is the complete index.php:
//setup some variables/arrays
$action = array();
$action['result'] = null;
$text = array();
//check if the form has been submitted
if(isset($_POST['signup'])){
//cleanup the variables
//prevent mysql injection
$name = mysql_real_escape_string($_POST['name']);
$surname = mysql_real_escape_string($_POST['surname']);
$address = mysql_real_escape_string($_POST['address']);
$postcode = mysql_real_escape_string($_POST['postcode']);
$contactnumber = mysql_real_escape_string($_POST['contactnumber']);
$email = mysql_real_escape_string($_POST['email']);
$mobile = mysql_real_escape_string($_POST['mobile']);
$hypernumber = mysql_real_escape_string($_POST['hypernumber']);
$fromstore = mysql_real_escape_string($_POST['fromstore']);
$hcardnumber = mysql_real_escape_string($_POST['hcardnumber']);
//quick/simple validation
if(empty($name)){ $action['result'] = 'error'; array_push($text,'You forgot your name'); }
if(empty($surname)){ $action['result'] = 'error'; array_push($text,'You forgot your surname'); }
if(empty($address)){ $action['result'] = 'error'; array_push($text,'You forgot your address'); }
if(empty($postcode)){ $action['result'] = 'error'; array_push($text,'You forgot your postcode'); }
if(empty($contactnumber)){ $action['result'] = 'error'; array_push($text,'You forgot your contact number'); }
if(empty($email)){ $action['result'] = 'error'; array_push($text,'You forgot your email'); }
if(empty($mobile)){ $action['result'] = 'error'; array_push($text,'You forgot your mobile'); }
if($printed == "yes"){
if(empty($_POST['fromstore'])){ $action['result'] = 'error'; array_push($text,'You forgot your city'); }
}
if($action['result'] != 'error'){
if($printed == "yes")
{
if($fromstore == "nicosia")
{
$file = file("nicosia.txt");
list($hcardnumber) = explode(",", $file[0]);
$fp = fopen("nicosia.txt", "w+");
for($i = 1; $i < sizeof($file); ++$i) {
fwrite($fp, trim($file[$i]) . "\n");
}
fclose($fp);
echo "Your card number is: $hcardnumber.";
}else if ($fromstore == "limassol")
{
$file = file("limassol.txt");
list($hcardnumber) = explode(",", $file[0]);
$fp = fopen("limassol.txt", "w+");
for($i = 1; $i < sizeof($file); ++$i) {
fwrite($fp, trim($file[$i]) . "\n");
}
fclose($fp);
echo "Your card number is: $hcardnumber.";
}else if ($fromstore == "paphos")
{
$file = file("paphos.txt");
list($hcardnumber) = explode(",", $file[0]);
$fp = fopen("paphos.txt", "w+");
for($i = 1; $i < sizeof($file); ++$i) {
fwrite($fp, trim($file[$i]) . "\n");
}
fclose($fp);
echo "Your card number is: $hcardnumber.";
}
}else if ($printed == "no"){
$file = file("all.txt");
list($hcardnumber) = explode(",", $file[0]);
$fp = fopen("all.txt", "w+");
for($i = 1; $i < sizeof($file); ++$i) {
fwrite($fp, trim($file[$i]) . "\n");
}
fclose($fp);
echo "Your card number is: $hcardnumber.";
}
//add to the database
$add = mysql_query("INSERT INTO `users` VALUES(NULL,'$name','$surname','$address','$postcode','$contactnumber','$email','$mobile','$hypernumber','$printed','$fromstore',0,'$hcardnumber')");
if($add){
//get the new user id
$userid = mysql_insert_id();
//create a random key
$key = $name . $email . date('mY');
$key = md5($key);
//add confirm row
$confirm = mysql_query("INSERT INTO `confirm` VALUES(NULL,'$userid','$key','$email')");
if($confirm){
//include the swift class
include_once 'inc/php/swift/swift_required.php';
//put info into an array to send to the function
$info = array(
'name' => $name,
'email' => $email,
'key' => $key,
'hcardnumber' => $hcardnumber);
//send the email
if(send_email($info)){
//email sent
$action['result'] = 'success';
array_push($text,'Thanks for signing up. Please check your email for confirmation!');
}else{
$action['result'] = 'error';
array_push($text,'Could not send confirm email');
}
}else{
$action['result'] = 'error';
array_push($text,'Confirm row was not added to the database. Reason: ' . mysql_error());
}
}else{
$action['result'] = 'error';
array_push($text,'User could not be added to the database. Reason: ' . mysql_error());
}
}
$action['text'] = $text;
}
?>
<?php
include 'inc/elements/header.php'; ?>
<?= show_errors($action); ?>
<form method="post" action="">
<fieldset>
<ul>
<li>
<label for="name">Name:</label>
<input type="text" name="name" />
</li>
<li>
<label for="surname">Surname:</label>
<input type="surname" name="surname" />
</li>
<li>
<label for="address">Address:</label>
<input type="address" name="address" />
</li>
<li>
<label for="postcode">Post Code:</label>
<input type="postcode" name="postcode" />
</li>
<li>
<label for="contactnumber">Contact Number:</label>
<input type="contactnumber" name="contactnumber" />
</li>
<li>
<label for="email">Email:</label>
<input type="text" name="email" />
</li>
<li>
<label for="mobile">Mobile:</label>
<input type="mobile" name="mobile" />
</li>
<li>
<label for="hypernumber">Hypercard Number:</label>
<input type="hypernumber" name="hypernumber" />
</li>
<li>
Printed:
<label for="printed_no">No</label>
<input type="radio" name="printed" value="no" class="morefrom" checked="checked" id="printed_no">
<label for="printed_yes">Yes</label>
<input type="radio" name="printed" value="yes" class="morefrom">
</li>
<li>
<div id="collectfrom">
<label for="fromstore">Collect From:</label>
<select name="fromstore" id="fromstore">
<option value="">Choose from</option>
<option value="nicosia">Nicosia</option>
<option value="limassol">Limassol</option>
<option value="paphos">Paphos</option>
</select>
</div>
</li>
<li>
<input type="hidden" name="hcardnumber" value="<?php echo $hcardnumber ?>"/>
</li>
<li>
<input type="submit" value="Signup Now" class="large blue button" name="signup" />
</li>
</ul>
</fieldset>
</form>
I still cant get the form to validate and check if radio button checked yes then check the fromstore if option value has been selected.
For a start, the value of $fromstore is always going to be at least a space character and never empty in your example, as you're providing it with a text value in your HTML (even a space is still sent as a text value). Remove the space from what you're sending to PHP and the if(empty()) condition will start evaluating properly.
Secondly, the element is best used when your form input has an associated ID. That way when you click on the label itself, the form element automatically gains focus (far better for accessibility and usability). Each input should have an associated label that describes simply what the input is for / represents.
Modify your HTML to look a bit more like this:
<li>
Printed:
<label for="printed_no">No</label>
<input type="radio" name="printed" value="no" class="morefrom" checked="checked" id="printed_no">
<label for="printed_yes">Yes</label>
<input type="radio" name="printed" value="yes" class="morefrom">
</li>
<li>
<div id="collectfrom">
<label for="fromstore">Collect From:</label>
<select name="fromstore" id="fromstore">
<option>Choose from</option>
<option value="nicosia">Nicosia</option>
<option value="limassol">Limassol</option>
<option value="paphos">Paphos</option>
</select>
</div>
</li>
Also, You haven't included the element in your code snippet above, are you definitely setting it and having your PHP script run? I would assume you are, but just want to make sure ;)
Finally, you appear to be relying on PHP's register_globals setting being enabled, which is very old practice and you should be thinking about updating yourself to use more widely accepted methods. Most servers nowadays won't have register_globals enabled and you may find your scripts breaking if you ever migrate from one server to another.
Have a look here for more info:
Why is REGISTER_GLOBALS so bad?
In this case, update your PHP to:
if($_POST['printed'] == "yes"){
if(empty($_POST['fromstore'])){
$action['result'] = 'error';
/* I assume $text used below is a variable instantiated
* somewhere else in this script and isn't sent from the
* form. Thus I've left it as $text instead of $_POST['text']
*/
array_push($text,'You forgot your city');
}
}
Hope this helps,
Neal

Categories