SlideShare a Scribd company logo
1 of 14
Naveen Kumar Veligeti
1
PHP Form Handling
The PHP super globals $_GET and $_POST are used to collect form-data.
PHP - A Simple HTML Form
The example below displays a simple HTML form with two input fields and a submit button:
Example
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
When the user fills out the form above and clicks the submit button, the form data is sent
for processing to a PHP file named "welcome.php". The form data is sent with the HTTP
POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php"
looks like this:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
The output could be something like this:
Welcome John
Your email address is john.doe@example.com
Naveen Kumar Veligeti
2
The same result could also be achieved using the HTTP GET method:
Example
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
and "welcome_get.php" looks like this:
<html>
<body>
Welcome <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>
The code above is quite simple. However, the most important thing is missing. You need to
validate form data to protect your script from malicious code.
GET vs. POST
Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 =>
value3, ...)). This array holds key/value pairs, where keys are the names of the form
controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals, which
means that they are always accessible, regardless of scope - and you can access them from
any function, class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Naveen Kumar Veligeti
3
When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable
names and values are displayed in the URL). GET also has limits on the amount of
information to send. The limitation is about 2000 characters. However, because the
variables are displayed in the URL, it is possible to bookmark the page. This can be useful in
some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!
When to use POST?
Information sent from a form with the POST method is invisible to others (all
names/values are embedded within the body of the HTTP request) and has no limits on the
amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark
the page.
Next; lets see how we can process PHP forms the secure way!
PHP Form Validation
This and the next chapters show how to use PHP to validate form data.
PHP Form Validation
The HTML form we will be working at in these chapters, contains various input fields:
required and optional text fields, radio buttons, and a submit button:
Naveen Kumar Veligeti
4
The validation rules for the form above are as follows:
Field Validation Rules
Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one
First we will look at the plain HTML code for the form:
Text Fields
The name, email, and website fields are text input elements, and the comment field is a
textarea. The HTML code looks like this:
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
Naveen Kumar Veligeti
5
The Form Element
The HTML code of the form looks like this:
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
When the form is submitted, the form data is sent with method="post".
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of
jumping to a different page. This way, the user will get error messages on the same page as
the form.
Big Note on PHP Form Security
The $_SERVER["PHP_SELF"] variable can be used by hackers!
If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site
Scripting (XSS) commands to execute.
Assume we have the following form in a page named "test_form.php":
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Now, if a user enters the normal URL in the address bar like
"http://www.example.com/test_form.php", the above code will be translated to:
<form method="post" action="test_form.php">
So far, so good.
However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/
script%3E
In this case, the above code will be translated to:
Naveen Kumar Veligeti
6
<form method="post"
action="test_form.php"/><script>alert('hacked')</script>
This code adds a script tag and an alert command. And when the page loads, the JavaScript
code will be executed (the user will see an alert box). This is just a simple and harmless
example how the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script> tag! A hacker
can redirect the user to a file on another server, and that file can hold malicious code that
can alter the global variables or submit the form to another address to save the user data,
for example.
How To Avoid $_SERVER["PHP_SELF"] Exploits?
$_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars() function.
The form code should look like this:
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
The htmlspecialchars() function converts special characters to HTML entities. Now if the user
tries to exploit the PHP_SELF variable, it will result in the following output:
<form method="post"
action="test_form.php/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&g
t;">
The exploit attempt fails, and no harm is done!
Validate Form Data With PHP
The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.
When we use the htmlspecialchars() function; then if a user tries to submit the following in
a text field:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code, like this:
&lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;
Naveen Kumar Veligeti
7
The code is now safe to be displayed on a page or inside an e-mail.
We will also do two more things when the user submits the form:
1. Strip unnecessary characters (extra space, tab, newline) from the user input data
(with the PHP trim() function)
2. Remove backslashes () from the user input data (with the PHP stripslashes()
function)
The next step is to create a function that will do all the checking for us (which is much more
convenient than writing the same code over and over again).
We will name the function test_input().
Now, we can check each $_POST variable with the test_input() function, and the script look
like this:
Example
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Notice that at the start of the script, we check whether the form has been submitted using
$_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has
been submitted - and it should be validated. If it has not been submitted, skip the validation
and display a blank form.
Naveen Kumar Veligeti
8
However, in the example above, all input fields are optional. The script works fine even if
the user do not enter any data.
The next step is to make input fields required and create error messages if needed.
PHP Forms - Required Fields
This chapter show how to make input fields required and create error messages if
needed.
PHP - Required Fields
From the validation rules table on the previous page, we see that the "Name", "E-mail", and
"Gender" fields are required. These fields cannot be empty and must be filled out in the
HTML form.
Field Validation Rules
Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one
In the previous chapter, all input fields were optional.
In the following code we have added some new variables: $nameErr, $emailErr, $genderErr,
and $websiteErr. These error variables will hold error messages for the required fields. We
have also added an if else statement for each $_POST variable. This checks if the $_POST
variable is empty (with the PHP empty() function). If it is empty, an error message is stored
in the different error variables, and if it is not empty, it sends the user input data through
the test_input() function:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
Naveen Kumar Veligeti
9
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["website"]))
{$website = "";}
else
{$website = test_input($_POST["website"]);}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
if (empty($_POST["gender"]))
{$genderErr = "Gender is required";}
else
{$gender = test_input($_POST["gender"]);}
}
?>
PHP - Display The Error Messages
Then in the HTML form, we add a little script after each required field, which generates the
correct error message if needed (that is if the user tries to submit the form without filling
out the required fields):
Example
<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>
Naveen Kumar Veligeti
10
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
<label>Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
The next step is to validate the input data, that is "Does the Name field contain only letters
and whitespace?", and "Does the E-mail field contain a valid e-mail address syntax?", and if
filled out, "Does the Website field contain a valid URL?".
PHP Forms - Validate E-mail and URL
This chapter show how to validate names, e-mails, and URLs.
PHP - Validate Name
The code below shows a simple way to check if the name field only contains letters and
whitespace. If the value of the name field is not valid, then store an error message:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
Naveen Kumar Veligeti
11
PHP - Validate E-mail
The code below shows a simple way to check if an e-mail address syntax is valid. If the e-
mail address syntax is not valid, then store an error message:
$email = test_input($_POST["email"]);
if (!preg_match("/([w-]+@[w-]+.[w-]+)/",$email))
{
$emailErr = "Invalid email format";
}
PHP - Validate URL
The code below shows a way to check if a URL address syntax is valid (this regular
expression also allows dashes in the URL). If the URL address syntax is not valid, then store
an error message:
$website = test_input($_POST["website"]);
if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0-
9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
PHP - Validate Name, E-mail, and URL
Now, the script looks like this:
Example
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
Naveen Kumar Veligeti
12
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 e-mail address syntax is valid
if (!preg_match("/([w-]+@[w-]+.[w-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"]))
{$website = "";}
else
{
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also
allows dashes in the URL)
if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0-
9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
if (empty($_POST["gender"]))
{$genderErr = "Gender is required";}
Naveen Kumar Veligeti
13
else
{$gender = test_input($_POST["gender"]);}
}
?>
The next step is to show how to prevent the form from emptying all the input fields when
the user submits the form.
PHP Complete Form Example
This chapter show how to keep the values in the input fields when the user hits the
submit button.
PHP - Keep The Values in The Form
To show the values in the input fields after the user hits the submit button, we add a little
PHP script inside the value attribute of the following input fields: name, email, and website.
In the comment textarea field, we put the script between the <textarea> and </textarea>
tags. The little script outputs the value of the $name, $email, $website, and $comment
variables.
Then, we also need to show which radio button that was checked. For this, we must
manipulate the checked attribute (not the value attribute for radio buttons):
Name: <input type="text" name="name" value="<?php echo $name;?>">
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
Website: <input type="text" name="website" value="<?php echo $website;?>">
Comment: <textarea name="comment" rows="5" cols="40"><?php echo
$comment;?></textarea>
Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
Naveen Kumar Veligeti
14
PHP - Complete Form Example
Here is the complete code for the PHP Form Validation Example:
Example
PHP Form Validation Example
* required field.
Name: *
E-mail: *
Website:
Comment:
Gender: Female Male *
Submit
Your Input:

More Related Content

What's hot

Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHPNisa Soomro
 
Chapter 07 php forms handling
Chapter 07   php forms handlingChapter 07   php forms handling
Chapter 07 php forms handlingDhani Ahmad
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String FunctionsAvanitrambadiya
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)WebStackAcademy
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...Edureka!
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arraysmussawir20
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NETRajkumarsoy
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validationMaitree Patel
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and ArraysWebStackAcademy
 

What's hot (20)

Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 
Chapter 07 php forms handling
Chapter 07   php forms handlingChapter 07   php forms handling
Chapter 07 php forms handling
 
php
phpphp
php
 
GET and POST in PHP
GET and POST in PHPGET and POST in PHP
GET and POST in PHP
 
Statements and Conditions in PHP
Statements and Conditions in PHPStatements and Conditions in PHP
Statements and Conditions in PHP
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String Functions
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
CSS
CSSCSS
CSS
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
Popup boxes
Popup boxesPopup boxes
Popup boxes
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validation
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 

Similar to Php forms and validations by naveen kumar veligeti

Working with data.pptx
Working with data.pptxWorking with data.pptx
Working with data.pptxSherinRappai
 
Web Development Course: PHP lecture 2
Web Development Course: PHP lecture 2Web Development Course: PHP lecture 2
Web Development Course: PHP lecture 2Gheyath M. Othman
 
Lecture7 form processing by okello erick
Lecture7 form processing by okello erickLecture7 form processing by okello erick
Lecture7 form processing by okello erickokelloerick
 
Php, mysq lpart4(processing html form)
Php, mysq lpart4(processing html form)Php, mysq lpart4(processing html form)
Php, mysq lpart4(processing html form)Subhasis Nayak
 
Html advanced-reference-guide for creating web forms
Html advanced-reference-guide for creating web formsHtml advanced-reference-guide for creating web forms
Html advanced-reference-guide for creating web formssatish 486
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingAhmed Swilam
 
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5Salvatore Iaconesi
 
Web Application Development using PHP Chapter 5
Web Application Development using PHP Chapter 5Web Application Development using PHP Chapter 5
Web Application Development using PHP Chapter 5Mohd Harris Ahmad Jaal
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.pptGiyaShefin
 
04 Html Form Get Post Login System
04 Html Form Get Post Login System04 Html Form Get Post Login System
04 Html Form Get Post Login SystemGeshan Manandhar
 
Forms With Ajax And Advanced Plugins
Forms With Ajax And Advanced PluginsForms With Ajax And Advanced Plugins
Forms With Ajax And Advanced PluginsManuel Lemos
 

Similar to Php forms and validations by naveen kumar veligeti (20)

forms.pptx
forms.pptxforms.pptx
forms.pptx
 
Working with data.pptx
Working with data.pptxWorking with data.pptx
Working with data.pptx
 
Web Development Course: PHP lecture 2
Web Development Course: PHP lecture 2Web Development Course: PHP lecture 2
Web Development Course: PHP lecture 2
 
Lecture7 form processing by okello erick
Lecture7 form processing by okello erickLecture7 form processing by okello erick
Lecture7 form processing by okello erick
 
Php, mysq lpart4(processing html form)
Php, mysq lpart4(processing html form)Php, mysq lpart4(processing html form)
Php, mysq lpart4(processing html form)
 
Html advanced-reference-guide for creating web forms
Html advanced-reference-guide for creating web formsHtml advanced-reference-guide for creating web forms
Html advanced-reference-guide for creating web forms
 
web2_lec6.pdf
web2_lec6.pdfweb2_lec6.pdf
web2_lec6.pdf
 
PHP-Part4
PHP-Part4PHP-Part4
PHP-Part4
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
 
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
Sperimentazioni di Tecnologie e Comunicazioni Multimediali: Lezione 5
 
Html forms
Html formsHtml forms
Html forms
 
Web Application Development using PHP Chapter 5
Web Application Development using PHP Chapter 5Web Application Development using PHP Chapter 5
Web Application Development using PHP Chapter 5
 
Html forms
Html formsHtml forms
Html forms
 
Html forms
Html formsHtml forms
Html forms
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
 
04 Html Form Get Post Login System
04 Html Form Get Post Login System04 Html Form Get Post Login System
04 Html Form Get Post Login System
 
PHP Tutorials
PHP TutorialsPHP Tutorials
PHP Tutorials
 
PHP Tutorials
PHP TutorialsPHP Tutorials
PHP Tutorials
 
Forms With Ajax And Advanced Plugins
Forms With Ajax And Advanced PluginsForms With Ajax And Advanced Plugins
Forms With Ajax And Advanced Plugins
 
introduction_php.ppt
introduction_php.pptintroduction_php.ppt
introduction_php.ppt
 

More from Naveen Kumar Veligeti

.Net framework components by naveen kumar veligeti
.Net framework components by naveen kumar veligeti.Net framework components by naveen kumar veligeti
.Net framework components by naveen kumar veligetiNaveen Kumar Veligeti
 
Basic CSS concepts by naveen kumar veligeti
Basic CSS concepts by naveen kumar veligetiBasic CSS concepts by naveen kumar veligeti
Basic CSS concepts by naveen kumar veligetiNaveen Kumar Veligeti
 
Why use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiWhy use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiNaveen Kumar Veligeti
 
Types of sql commands by naveen kumar veligeti
Types of sql commands by naveen kumar veligetiTypes of sql commands by naveen kumar veligeti
Types of sql commands by naveen kumar veligetiNaveen Kumar Veligeti
 
Sql data types for various d bs by naveen kumar veligeti
Sql data types for various d bs by naveen kumar veligetiSql data types for various d bs by naveen kumar veligeti
Sql data types for various d bs by naveen kumar veligetiNaveen Kumar Veligeti
 
.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligeti.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligetiNaveen Kumar Veligeti
 

More from Naveen Kumar Veligeti (8)

.Net framework components by naveen kumar veligeti
.Net framework components by naveen kumar veligeti.Net framework components by naveen kumar veligeti
.Net framework components by naveen kumar veligeti
 
Basic CSS concepts by naveen kumar veligeti
Basic CSS concepts by naveen kumar veligetiBasic CSS concepts by naveen kumar veligeti
Basic CSS concepts by naveen kumar veligeti
 
Why use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiWhy use .net by naveen kumar veligeti
Why use .net by naveen kumar veligeti
 
Types of sql commands by naveen kumar veligeti
Types of sql commands by naveen kumar veligetiTypes of sql commands by naveen kumar veligeti
Types of sql commands by naveen kumar veligeti
 
Sql data types for various d bs by naveen kumar veligeti
Sql data types for various d bs by naveen kumar veligetiSql data types for various d bs by naveen kumar veligeti
Sql data types for various d bs by naveen kumar veligeti
 
Beginners introduction to asp.net
Beginners introduction to asp.netBeginners introduction to asp.net
Beginners introduction to asp.net
 
Clauses in sql server
Clauses in sql serverClauses in sql server
Clauses in sql server
 
.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligeti.Net framework by naveen kumar veligeti
.Net framework by naveen kumar veligeti
 

Recently uploaded

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 

Recently uploaded (20)

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 

Php forms and validations by naveen kumar veligeti

  • 1. Naveen Kumar Veligeti 1 PHP Form Handling The PHP super globals $_GET and $_POST are used to collect form-data. PHP - A Simple HTML Form The example below displays a simple HTML form with two input fields and a submit button: Example <html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html> When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method. To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this: <html> <body> Welcome <?php echo $_POST["name"]; ?><br> Your email address is: <?php echo $_POST["email"]; ?> </body> </html> The output could be something like this: Welcome John Your email address is john.doe@example.com
  • 2. Naveen Kumar Veligeti 2 The same result could also be achieved using the HTTP GET method: Example <html> <body> <form action="welcome_get.php" method="get"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html> and "welcome_get.php" looks like this: <html> <body> Welcome <?php echo $_GET["name"]; ?><br> Your email address is: <?php echo $_GET["email"]; ?> </body> </html> The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect your script from malicious code. GET vs. POST Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user. Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. $_GET is an array of variables passed to the current script via the URL parameters. $_POST is an array of variables passed to the current script via the HTTP POST method.
  • 3. Naveen Kumar Veligeti 3 When to use GET? Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. GET may be used for sending non-sensitive data. Note: GET should NEVER be used for sending passwords or other sensitive information! When to use POST? Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send. Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server. However, because the variables are not displayed in the URL, it is not possible to bookmark the page. Next; lets see how we can process PHP forms the secure way! PHP Form Validation This and the next chapters show how to use PHP to validate form data. PHP Form Validation The HTML form we will be working at in these chapters, contains various input fields: required and optional text fields, radio buttons, and a submit button:
  • 4. Naveen Kumar Veligeti 4 The validation rules for the form above are as follows: Field Validation Rules Name Required. + Must only contain letters and whitespace E-mail Required. + Must contain a valid email address (with @ and .) Website Optional. If present, it must contain a valid URL Comment Optional. Multi-line input field (textarea) Gender Required. Must select one First we will look at the plain HTML code for the form: Text Fields The name, email, and website fields are text input elements, and the comment field is a textarea. The HTML code looks like this: Name: <input type="text" name="name"> E-mail: <input type="text" name="email"> Website: <input type="text" name="website"> Comment: <textarea name="comment" rows="5" cols="40"></textarea> Radio Buttons The gender fields are radio buttons and the HTML code looks like this: Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male
  • 5. Naveen Kumar Veligeti 5 The Form Element The HTML code of the form looks like this: <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> When the form is submitted, the form data is sent with method="post". So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page. This way, the user will get error messages on the same page as the form. Big Note on PHP Form Security The $_SERVER["PHP_SELF"] variable can be used by hackers! If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute. Assume we have the following form in a page named "test_form.php": <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>"> Now, if a user enters the normal URL in the address bar like "http://www.example.com/test_form.php", the above code will be translated to: <form method="post" action="test_form.php"> So far, so good. However, consider that a user enters the following URL in the address bar: http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/ script%3E In this case, the above code will be translated to:
  • 6. Naveen Kumar Veligeti 6 <form method="post" action="test_form.php"/><script>alert('hacked')</script> This code adds a script tag and an alert command. And when the page loads, the JavaScript code will be executed (the user will see an alert box). This is just a simple and harmless example how the PHP_SELF variable can be exploited. Be aware of that any JavaScript code can be added inside the <script> tag! A hacker can redirect the user to a file on another server, and that file can hold malicious code that can alter the global variables or submit the form to another address to save the user data, for example. How To Avoid $_SERVER["PHP_SELF"] Exploits? $_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars() function. The form code should look like this: <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> The htmlspecialchars() function converts special characters to HTML entities. Now if the user tries to exploit the PHP_SELF variable, it will result in the following output: <form method="post" action="test_form.php/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&g t;"> The exploit attempt fails, and no harm is done! Validate Form Data With PHP The first thing we will do is to pass all variables through PHP's htmlspecialchars() function. When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field: <script>location.href('http://www.hacked.com')</script> - this would not be executed, because it would be saved as HTML escaped code, like this: &lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;
  • 7. Naveen Kumar Veligeti 7 The code is now safe to be displayed on a page or inside an e-mail. We will also do two more things when the user submits the form: 1. Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function) 2. Remove backslashes () from the user input data (with the PHP stripslashes() function) The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again). We will name the function test_input(). Now, we can check each $_POST variable with the test_input() function, and the script look like this: Example <?php // define variables and set to empty values $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); $email = test_input($_POST["email"]); $website = test_input($_POST["website"]); $comment = test_input($_POST["comment"]); $gender = test_input($_POST["gender"]); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> Notice that at the start of the script, we check whether the form has been submitted using $_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has been submitted - and it should be validated. If it has not been submitted, skip the validation and display a blank form.
  • 8. Naveen Kumar Veligeti 8 However, in the example above, all input fields are optional. The script works fine even if the user do not enter any data. The next step is to make input fields required and create error messages if needed. PHP Forms - Required Fields This chapter show how to make input fields required and create error messages if needed. PHP - Required Fields From the validation rules table on the previous page, we see that the "Name", "E-mail", and "Gender" fields are required. These fields cannot be empty and must be filled out in the HTML form. Field Validation Rules Name Required. + Must only contain letters and whitespace E-mail Required. + Must contain a valid email address (with @ and .) Website Optional. If present, it must contain a valid URL Comment Optional. Multi-line input field (textarea) Gender Required. Must select one In the previous chapter, all input fields were optional. In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and $websiteErr. These error variables will hold error messages for the required fields. We have also added an if else statement for each $_POST variable. This checks if the $_POST variable is empty (with the PHP empty() function). If it is empty, an error message is stored in the different error variables, and if it is not empty, it sends the user input data through the test_input() function: <?php // define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = "";
  • 9. Naveen Kumar Veligeti 9 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["website"])) {$website = "";} else {$website = test_input($_POST["website"]);} if (empty($_POST["comment"])) {$comment = "";} else {$comment = test_input($_POST["comment"]);} if (empty($_POST["gender"])) {$genderErr = "Gender is required";} else {$gender = test_input($_POST["gender"]);} } ?> PHP - Display The Error Messages Then in the HTML form, we add a little script after each required field, which generates the correct error message if needed (that is if the user tries to submit the form without filling out the required fields): Example <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>
  • 10. Naveen Kumar Veligeti 10 E-mail: <input type="text" name="email"> <span class="error">* <?php echo $emailErr;?></span> <br><br> Website: <input type="text" name="website"> <span class="error"><?php echo $websiteErr;?></span> <br><br> <label>Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <span class="error">* <?php echo $genderErr;?></span> <br><br> <input type="submit" name="submit" value="Submit"> </form> The next step is to validate the input data, that is "Does the Name field contain only letters and whitespace?", and "Does the E-mail field contain a valid e-mail address syntax?", and if filled out, "Does the Website field contain a valid URL?". PHP Forms - Validate E-mail and URL This chapter show how to validate names, e-mails, and URLs. PHP - Validate Name The code below shows a simple way to check if the name field only contains letters and whitespace. If the value of the name field is not valid, then store an error message: $name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; }
  • 11. Naveen Kumar Veligeti 11 PHP - Validate E-mail The code below shows a simple way to check if an e-mail address syntax is valid. If the e- mail address syntax is not valid, then store an error message: $email = test_input($_POST["email"]); if (!preg_match("/([w-]+@[w-]+.[w-]+)/",$email)) { $emailErr = "Invalid email format"; } PHP - Validate URL The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message: $website = test_input($_POST["website"]); if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0- 9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } PHP - Validate Name, E-mail, and URL Now, the script looks like this: Example <?php // define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = "";
  • 12. Naveen Kumar Veligeti 12 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 e-mail address syntax is valid if (!preg_match("/([w-]+@[w-]+.[w-]+)/",$email)) { $emailErr = "Invalid email format"; } } if (empty($_POST["website"])) {$website = "";} else { $website = test_input($_POST["website"]); // check if URL address syntax is valid (this regular expression also allows dashes in the URL) if (!preg_match("/b(?:(?:https?|ftp)://|www.)[-a-z0- 9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } } if (empty($_POST["comment"])) {$comment = "";} else {$comment = test_input($_POST["comment"]);} if (empty($_POST["gender"])) {$genderErr = "Gender is required";}
  • 13. Naveen Kumar Veligeti 13 else {$gender = test_input($_POST["gender"]);} } ?> The next step is to show how to prevent the form from emptying all the input fields when the user submits the form. PHP Complete Form Example This chapter show how to keep the values in the input fields when the user hits the submit button. PHP - Keep The Values in The Form To show the values in the input fields after the user hits the submit button, we add a little PHP script inside the value attribute of the following input fields: name, email, and website. In the comment textarea field, we put the script between the <textarea> and </textarea> tags. The little script outputs the value of the $name, $email, $website, and $comment variables. Then, we also need to show which radio button that was checked. For this, we must manipulate the checked attribute (not the value attribute for radio buttons): Name: <input type="text" name="name" value="<?php echo $name;?>"> E-mail: <input type="text" name="email" value="<?php echo $email;?>"> Website: <input type="text" name="website" value="<?php echo $website;?>"> Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea> Gender: <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
  • 14. Naveen Kumar Veligeti 14 PHP - Complete Form Example Here is the complete code for the PHP Form Validation Example: Example PHP Form Validation Example * required field. Name: * E-mail: * Website: Comment: Gender: Female Male * Submit Your Input: