header, session, php validation - php

I'm having a big problem with my validation form. Basically I created a form that will, once submitted, redirect to another page. To do this I used header("location: aaaaa.php") and apparently it works. The problem is that by doing this the validation doesn't work anymore, in fact if I don't enter any data and press submit I'll be redirected to the second page without getting the errors. If I delete the header the validation works again.
Moreover I have a big problem with the session method. I tried different way of using it to transfer the data to the second page when pressed the button submit, but it doesn't work and no one until now was able to help me. In the code that I'm gonna put below I deleted the session method and I was hoping that you would help me with that.
London Flight Agency
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name =($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["surname"])) {
$surnameErr = "Surname is required";
} else {
$surname =($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email =($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["telephone"])) {
$telephoneErr = "Number is required";
} else {
$telephone =($_POST["telephone"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[0-9\_]{7,20}/",$telephone)) {
$telephoneErr = "Enter correct telephone number";
}
}
if (empty($_POST["date"])) {
$dateErr = "Date is required";
} else {
$date =($_POST["date"]);
// check if name only contains letters and whitespace
if (!preg_match("~^\\d{1,2}[/.-]\\d{2}[/.-]\\d{4}$~",$date)) {
$dateErr = "Enter correct date of birth";
}
}
if (empty($_POST["luggage"])) {
$luggageErr = "Choose one of the options";
} else {
$luggage =($_POST["luggage"]);
}
$weight = $_POST['weight'];
$height = $_POST['height'];
if(isset($_POST['submit']))
{
$total = ($weight+$height)/10;
}
header("Location: thankyou.php");
}
?>
<h2 id="title">London Flight Agency</h2><!-- This tag is used to define HTML heading (h1 to h6), this particular one defines the most important heading -->
<form id="form" method="post" name="myForm" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return validateForm(this);"><!-- The <form> tag is used to create an HTML form for user input -->
<h4 class="subtitle"><strong>Personal Details</strong></h4>
<fieldset>
Enter here all your details (all of them are compulsory.)
<br />
<br />
<select name="Title" id="title" value="<?php echo $title;?>" onblur="validateSelect(name)">
<option value="empty">Title</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="Miss">Miss</option>
<option value="Dr">Dr</option>
</select><br /><br />
<span class="validateError" id="titleError" style="display: none;">You must select a title!</span>
<span id="error8"><?php echo $titleErr;?></span>
<table
<tr>
<td><label for="firstname">First Name:</label></td>
<td><input type="text" name="name" value="<?php echo $name;?>" id="name" onblur="validateName(name)"></td>
<span id="nameError" style="display: none;"></span>
<span id="error1"><?php echo $nameErr;?></span>
</tr>
<tr>
<td><label for="surname">Surname:</label></td>
<td><input type="text" name="surname" value="<?php echo $surname;?>" id="name" onblur="validateSurname(surname)"></td>
<span id="surnameError" style="display: none;"></span>
<span id="error2"><?php echo $surnameErr;?></span>
</tr>
<tr>
<td><label for="email">Email address:</label></td>
<td><input type="text" name="email" value="<?php echo $email;?>" id="email" onblur="validateEmail(email)"></td>
<span id="emailError" style="display: none;"></span>
<span id="error3"><?php echo $emailErr;?></span>
</tr>
<tr>
<td><label for="telephone">Telephone No:</label></td>
<td><input type="text" name="telephone" value="<?php echo $telephone;?>" id="telephone" onblur="validateTelephone(telephone)"></td>
<span id="telephoneError" style="display: none;"></span>
<span id="error4"><?php echo $telephoneErr;?></span>
</tr>
<tr>
<td><label for="date">Date of birth:</label></td>
<td><input type="text" name="date" value="<?php echo $date;?>" id="date" onblur="validateDate(date)"></td>
<span id="dateError" style="display: none;"></span>
<span id="error5"><?php echo $dateErr;?></span>
</tr>
</table>
</fieldset>
<h4 class="subtitle"><strong>Flight Details</strong></h4>
<fieldset>
<p>Hand luggage:</p><br />
<input type="radio" name="luggage" <?php if (isset($luggage) && $luggage=="Yes") echo "checked";?>value="Yes" id = "myRadio" required onblur="myFunction()">Yes
<input type="radio" name="luggage" <?php if (isset($luggage) && $luggage=="No") echo "checked";?>value="No" id = "myRadio" required onblur="myFunction()">No
<span id="luggageError" style="display: none;"></span>
<span id="error6"><?php echo $luggageErr;?></span>
<br /><br />
<label for="extrabag">Include free extra bag</label>
<input type="checkbox" name="extra" id="check" value="bag">
<br />
<br />
<select name="option" id="card" onblur="validatePayment(card)">
<option value="empty">Payment Card</option>
<option value="Visa">Visa Debit Card</option>
<option value="MasterCard">MasterCard</option>
<option value="PayPal">PayPal</option>
<option value="Maestro">Mestro</option>
<option value="Visa Electron">Visa Electron</option>
</select><br />
<span class="validateError" id="cardError" style="display: none;">You must select your payment card!</span>
</fieldset>
<h4 class="subtitle"><strong>Luggage Details</strong></h4>
<fieldset>
<p>Enter weight and height of your luggage.</p>
Your Weight(kg): <input type="text" name="weight" size="7"><br />
Your Height(cm): <input type="text" name="height" size="7"><br />
<span id="error7"><?php echo $measureErr;?></span>
<input type="button" value="Tot. price" onClick="totalPrice()"><br /><br />
Total Price: <input type="text" name="total" value="<?php echo $total?>" size="10"><br /><br />
<input type="reset" value="Reset">
<input type="submit" value="Submit" name="submit">
</fieldset>
</form>
</body>
It doesn't show the first part of the code for I don't know which reason. I'll post it below:
London Flight Agency

The problem Is that you are checking if the method is post then redirect to the new page.
You must check if the your entries are valid then redirect.
For Example You can make an array of data and use array_push to push new data whenever there is something invalid and then check like this :
if( count( $array ) == 0 )
header('Location:YOUR_NEW_PAGE.php');
This is one of the simplest solutions you can implement.
Good luck

Related

PHP isset($_POST["Submit1"])) is not working

So I am trying to run this code and at the if (isset($_POST["Submit1"])) statement for isset, the form will not give the error message whenever I leave my form empty. It is supposed to give the $nameErr whenever the form is left empty, but it is not giving that error message. Whenever I delete the if (isset($_POST["Submit1"])) statement, it will run the else statement fine.
if (isset($_POST["Submit1"]))
{
if (isset($_POST['name']))
{
$name = sanitizeString($_POST['name']);
} else {
$nameErr = "* Your name must consist of letters and whitespace.";
}
}
Here is the submit button code.
<input type="submit" name="Submit1" value="Calculate">
As you can see, the names are the same so I don't think that is the problem.
Here is the rest of my code if you wish to take a look.
<!DOCTYPE html>
<html lang="en">
<head>
<title>GPA Improvement Calculator</title>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<h1>GPA Improvement Calculator</h1>
<p><span class="error">All form fields must be completed for the GPA calculator to function.</span></p>
<?php
function sanitizeString($var)
{
$var = stripslashes($var);
$var = strip_tags($var);
$var = htmlentities($var);
return $var;
}
$name = "";
$nameErr = "";
if (isset($_POST["Submit1"]))
{
if (isset($_POST['name']))
{
$name = sanitizeString($_POST['name']);
} else {
$nameErr = "* Your name must consist of letters and whitespace.";
}
}
?>
<form method="post" action="improveGPA.php">
Name: <input type="text" size="35" name="name" value="<?php echo $name; ?>">
<span class="error"><?php echo $nameErr; ?></span>
<br><br>
E-mail: <input type="text" size="35" name="email" value="">
<span class="error"></span>
<br><br>
<input type="checkbox" name="agree" >
I agree to the terms and conditions of this website.
<span class="error"></span>
<br><br>
Current GPA: <input type="text" size="4" name="currentGPA" value="">
<span class="error"></span>
<br><br>
Current Total Credits: <input type="text" size="3" name="currentCredits" value="">
<span class="error"></span>
<br><br>
I am taking <input type="text" size="3" name="newCredits" value="">
<span class="error"></span> credits this semester.
If I want to raise my GPA
<input type="text" size="4" name="GPAincrease" value="">
<span class="error"></span> points,
I need a <span style="font-weight: bold;">????</span> GPA on my courses this semester.
<br><br>
<input type="submit" name="Submit1" value="Calculate">
</form>
</body>
</html>
It will only start messing up if I have that one if statement in and just won't show that error message at all, when the form is empty or filled in.

PHP form not validating form field properly

I'm learning some more PHP and after PHP itself to work, I can't seem to get it to validate any form field correctly. My goal is to check if the firstname field is empty, and if it is, it will give a message in a red color. The message in the red works, but only because the echo script is being called by the form submission, not because it has detected any empty field, because when I made an else statement to say "wassup" if its not empty, I got the same message for when the field is empty. Also, is there a way to check off multiple input fields at once like you could with JavaScript? For example if input1 == '' || input2 == '' and so on. Here is my HTML:
<html>
<head>
<title>Welcome</title>
</head>
<body>
<form action="welcome.php" method="post">
<fieldset>
<legend>Personal Info</legend>
First name <input name="name" type="text">
Middle name <input name="middlename" type="text">
Surname <input name="lastname" type="text">
Age <input name="age" type="number">
Date of birth <input name="dob" type="date">
</fieldset>
<fieldset>
<legend>Regional & location info</legend>
Continent
<select>
<option value="europe">Europe</option>
<option value="americas">America</option>
<option value="africa">Africa</option>
<option value="asia">Asia</option>
<option value="australia">Australia</option>
<option value="eurasia">Eurasia</option>
</select>
Country <input name="country" type="text"> State <input type="text">
City <input name="city" type="text">
Street number <input name="streetno" type="number">
Street name <input name="streetname" type="text"> <br><br>
Suburb <input name="suburb" type="text"> Postcode <input name="postcode" type="number">
If none of these apply to your accommodations, enter a typed location here <input type="text">
</fieldset>
<fieldset>
<legend>Previous lifestyle accommodations</legend>
Previous &/or most recent job title <input name="job" type="text">
First time job seeker <input type="checkbox" name="check1" value="ftjb">
I'm a student <input type="checkbox" name="check2" value="ias">
Previous &/or most recent acedemic title <input name="school" type="text">
First time applying for a qualification <input type="checkbox" name="check3" value="ftafaq">
I have work experience <input type="checkbox" name="check4" value="ihwe">
</fieldset>
<fieldset>
<legend>Details of arrival</legend>
Reason for arrival <input name="reason" type="text">
Date of arrival <input name="arrival" type="date">
Amount of stay expectancy
<input type="checkbox" name="check3">Temporary
<input type="checkbox" name="check4">Longterm
</fieldset>
<fieldset>
<legend>Signiture</legend>
<input name='signiture' type="text">
</fieldset>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Here is my PHP code:
<?php
$firstname = $_POST['name'];
$lastname = $_POST['lastname'];
$age = $_POST['age'];
$dob = $_POST['dob'];
$country = $_POST['country'];
$city = $_POST['city'];
$suburb = $_POST['suburb'];
$postcode = $_POST['postcode'];
$streetno = $_POST['streetno'];
$streetname = $_POST['streetname'];
$suburb = $_POST['suburb'];
$job = $_POST['job'];
$school = $_POST['school'];
$reason = $_POST['reason'];
$arrival = $_POST['arrival'];
$signiture = $_POST['signiture'];
if (isset($_POST['submit'])) {
if (empty($_POST[$firstname])) {
echo '<p style="color: red; text-align: center">Your first name is required</p>';
} else {
echo "wassaup";
}
}
?>
In your if statement, you need to do this:
if (empty($_POST['name'])) { //Or replace $_POST['name'] with $firstname
echo '<p style="color: red; text-align: center">Your first name is required</p>';
} else {
echo "wassaup";
}
You have a wrong syntax if (empty($_POST[$firstname])). You should use ' ' single paranthesis in firstname and remove this sign $.
change this if (empty($_POST[$name])) { to if (empty($_POST['firstname'])) { and check again. your syntax is wrong that's why it is not working.
Change in your code
if (!isset($_POST['firstname'] || empty($_POST['firstname'])) {
echo '<p style="color: red; text-align: center">Your first name is required</p>';
} else {
echo "wassaup";
}
First you can create error array where you will put all yours errors
$error = array();
then when you check for multiple fields
if (empty($_POST['firstname'])) $error[] = "First name can't be empty";
if (empty($_POST['lastname'])) $error[] = "Last name can't be empty";
// and so on
after you do all of this make statement to check if error array is empty, if not display errors
if (empty($error)) {
// do something
} else {
// error exists you want to display all errors
foreach ($error as $value) {
echo '<ul><li>'.$value.'</li></ul>';
}
}
in the html form, you have to add the attribute required in html tag and without using the PHP processing
First name <input name="name" type="text" required="required">
and if the user doesn't enter his First name, he will get the error message (that the first name is required)

file should handle reporting all errors

I am fairly new at PHP. I have an assignment which requires me to make two separate files. On called input.html and the other handle.php.
The input.html file has a for that will receive user input and then send it to the handle.php file.
The input.html should look like
and if all the fields are filed in then I should display this
The complication that I'm having is with the required filed. If the fields do not have text or the radio is not checked then it should warn users but with me it keep sending them to the PHP file and showing an error.
My code for input.html is
<!doctype html>
<html lang="en">
<head>
<title> Feedback Form </title>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $responseErr = $commentErr = "";
$name = $email = $response = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
//Check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)){
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
//Check if email address is well-formated
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
}
if (empty($_POST["response"])) {
$responseErr = "Response is required";
} else {
$response = test_input($_POST["response"]);
}
if (empty($_POST["comment"])) {
$commentErr = "Comment is required";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p>Please complete this form to submit your feedback:</p>
<p><span class="error">* required field</span></p>
<!-- Start of the form -->
<form method="post" action="handle.php">
Name: <select name="prefix">
<option>Mr. </option>
<option>Mrs. </option>
<option>Ms. </option>
</select> <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Email Address: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Response: This is...
<input type="radio" name="response" value="excellent">excellent
<input type="radio" name="response" value="okay">okay
<input type="radio" name="response" value="boring">boring
<span class="error">* <?php echo $responseErr;?></span>
<br><br>
Comments: <textarea name="comment" rows="5" cols="40"></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br><br>
<input type="submit" value="Send My Feedback">
</form>
<!-- End of the form -->
</body>
</html>
and my code for handle.php is
<html>
<head></head>
<body>
Thank you, <?php echo $_POST["prefix"] ?> <?php echo $_POST["name"]; ?> for your comment.<br><br>
You stated that you found this example to be '<?php echo $_POST["response"]; ?>'<br>
and added: <br>
'<?php echo $_POST['comment'];?>'<br>
</body>
</html>
So when I leave all the fields blank instead of it warning me that they are blank i get this
I tried to use w3shool as a guide line but it did not work. I would really appreciate some help and thank you to everything that is taking their time to attempt to help me. :)
You can use required to solve your problem. required stops the form from submitting if the required field is empty or not selected.
<form method="post" action="handle.php">
Name:
<select name="prefix">
<option>Mr. </option>
<option>Mrs. </option>
<option>Ms. </option>
</select>
<input type="text" name="name" required>
<span class="error">* <?php echo $nameErr;?></span>
<br>
<br> Email Address:
<input type="email" name="email" required>
<span class="error">* <?php echo $emailErr;?></span>
<br>
<br> Response: This is...
<input type="radio" name="response" value="excellent" required>excellent
<input type="radio" name="response" value="okay" required>okay
<input type="radio" name="response" value="boring" required>boring
<span class="error">* <?php echo $responseErr;?></span>
<br>
<br> Comments:
<textarea name="comment" rows="5" cols="40" required></textarea>
<span class="error">* <?php echo $commentErr;?></span>
<br>
<br>
<input type="submit" value="Send My Feedback">
</form>
I also recommend to use 'email' as type for email input field. This will make sure the input data is a valid email format.

Why is my php files not responding to the css file linked to it?

I'm trying to change to color of the error alerts on this php file. By my css files doesn't seems to respond. Can you help me figure out the reason? I'd like to make my alerts blue and bigger.
Here's the form :
<div id="dv_global_form">
<form action="index.php" method="post">
<p class="required">Required fields *</p>
Name:<input type="text" name="name" <?php echo"value='$nameValue'"?>> <span class="required"> *</span><?php echo"<span class='required'> $nameErr</span>" ;?></span><br>
Surname:<input type="text" name="surname"<?php echo"value=$surnameValue"?>><span class="required"> *</span><?php echo"<span class='required'> $surnameErr</span>" ;?></span><br>
Date of Birth:<select name="dob">
<?php dob()?>
</select><span class="required"> *</span><?php echo"<span class='required'> $dobErr</span>" ;?><br>
Email:<input type="email" name="email" <?php echo"value=$emailValue"?>><span class="required"> *</span><?php echo"<span class='required'> $emailErr</span>" ;?>
<h3>Gender<span class="required"> * </span></h3>
<input type="radio" name="gender" value="male">Male<br>
<input type="radio" name="gender" value="female">Female<br>
<input type="submit" value="submit">
</form>
<?php echo"<p class='required' > $genderErr</p>" ;?>
</div>
Here's the php file containing the functions:
function dob(){
echo "<option></option>";
for($i=1989;$i<2001;$i++){
if($i==$_POST['dob']){
echo "<option selected='selected'>$_POST[dob]</option>";
}else{
echo "<option>$i</option>";
}
}
}
// Validate fields
$nameErr= $surnamErr=$emailErr= $dobErr=$sexErr=$genderErr="";
$nameValue=$surnameValue=$dobValue=$emailValue="";
if($_SERVER["REQUEST_METHOD"]==POST){
if(empty($_POST['name'])){
$nameErr="Name is required field";
}else{
if(!preg_match("/^[a-zA-Z\s]*$/",$_POST['name'])){
$nameErr="Only letters and white space allowed";
}else{
$nameValue=$_POST['name'];
}
}
if(empty($_POST['surname'])){
$surnameErr="Surname is required field";
}else{
if(!preg_match("/^[a-zAZ]*$/",$_POST['surname'])){
$surnameErr="Only letters and white space allowed";
}else{
$surnameValue=$_POST['surname'];
}
}
if(empty($_POST['dob'])){
$dobErr="Date of birth is required field";
}
if(empty($_POST['email'])){
$emailErr="Email is a required filed";
}else{
if(!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)){
$emailErr="This email format is not valid";
}
$emailValue=$_POST['email'];
}
if(empty($_POST['gender'])){
$genderErr="Gender is a required field";
}else{
}
}
And here's the css :
.required{
color:blue;
}
#gender{
color:blue;
}

How to automatically focus cursor on input field after PHP validation

How can I automatically focus the cursor on an input field after PHP validation. If user enters an incorrect answer, I want to focus on that field when the page loads.
I'm new to PHP. How can I do this in PHP?
Contact Form:
<form method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset style="width:960px; background-color:#FFF; border-radius:10px; padding:50px;">
<legend><h2>Contact Us</h2></legend>
<br />
<fieldset style="border-radius:10px; padding:50px 0px 50px 50px;;";>
<div style="width:275px; height:300px; float:right; padding:30px"><img src="images/contactus.jpg" width="275" height="300" alt="contactus" /></div>
<label>Name:</label>
<input class="txt" type="text" name="name" value="<?php echo isset($_POST['name']) ? htmlentities($_POST['name']) : ''; ?>"/><span class="error"><?php echo $nameErr?></span><br /><br />
<label>Email:</label>
<input class="txt" type="text" name="email" value="<?php echo isset($_POST['email']) ? htmlentities($_POST['email']) : ''; ?>"/><span class="error"><?php echo $emailErr?></span><br /><br />
<label>Mobile No:</label>
<input class="txt" type="text" name="mobileno" value="<?php echo isset($_POST['mobileno']) ? htmlentities($_POST['mobileno']) : ''; ?>"/><span class="error"><?php echo $mobilenoErr?></span><br /><br />
<label>Message:</label>
<textarea class="txt" name="message"rows="5"><?php echo $message?></textarea><span class="error"><?php echo $messageErr?></span><br /><br />
<input style="margin-left:100px; padding:5px 20px 5px 20px; border-radius:5px" type="submit" value = "Submit" />
</fieldset>
</fieldset>
</form>
Contact form validation in PHP:
<?php
if(isset($_POST['name']))
{
include_once("config.php");
$name=$email=$mobileno=$message=="";
$nameErr=$emailErr=$mobilenoErr=$messageErr="";
function test_input($data)
{
$data=trim($data);
$data-stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
if($_SERVER['REQUEST_METHOD']=="POST")
{
$valid=true;
//name validaton
if(empty($_POST["name"]))
{
$nameErr="* Name is Required";
$valid=false;
}
else
{
$name=test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = " Only letters and white space allowed";
$valid=false;
}
}
//Email Address validaton
if(empty($_POST["email"]))
{
$emailErr="* Email is Required";
$valid=false;
}
else
{
$email=test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr=" Enter a valid Email ID";
$valid=false;
}
}
//Mobile no validaton
if(empty($_POST["mobileno"]))
{
$mobilenoErr="* Mobile no is Required";
$valid=false;
}
else
{
$mobileno=test_input($_POST["mobileno"]);
if(!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$mobileno))
{
$mobilenoErr="*Enter a valid contact no";
$valid=false;
}
}
//bank name validation
if(empty($_POST["message"]))
{
$messageErr="* Message is Required";
$valid=false;
}
else
{
$message=test_input($_POST["message"]);
}
}
if($valid)
{
echo "Send mail code";
}
}
?>
You can try autofocus (http://diveintohtml5.info/forms.html):
<input class="txt" type="text" name="name"
value="<?php echo isset($_POST['name']) ? htmlentities($_POST['name']) : ''; ?>"
<?php if(!empty($nameErr)) { ?> autofocus <?php } ?>
/>
<span class="error"><?php echo $nameErr?></span><br /><br />
This is just the html option autofocus.
Here you can find a good explanation
<input type="text" name="fname" autofocus>
Or you can do it with javascript, if the IE makes some problems or you arn't coding with html5:
<body OnLoad='document.getElementById("txt").focus();'>
But if you want to do it like this, you must set an id to your inputfield.
The HTML5 autofocus feature with if logic as suggested by Ramesh is correct; however the code is not quite right for an if statement mixed with html. Instead of the normal braces, you need to use a colon and add the php endif statement. Try this:
<input class="txt" type="text" name="name"
value="<?php echo isset($_POST['name']) ? htmlentities($_POST['name']) : ''; ?>"
<?php if(!empty($nameErr)): ?> autofocus <?php endif; ?>
/>
<span class="error"><?php echo $nameErr; ?></span><br /><br />

Categories