Chapter 4 Creating and Validating Forms
Chapter 4 Creating and Validating Forms
certain resources.
●It is responsible for encrypting and compressing
data.
● Web server manages multiple domains and URLs.
Attribute Description
action It specifies the URL where the form should be submitted
method It specifies the HTTP methods such as GET,POST
name This attribute denotes the name of the form.
target It specifies the target of the address in the action attribute
The target attribute specifies a name or a keyword that indicates
where to display the response that is received after submitting the
form.
The target attribute defines a name of, or keyword for, a browsing
context (e.g. tab, window, or inline frame).
Value Description
<br/>
<input type="submit" value="Submit"/>
<form>
<?php
if(isset($_POST['submit']))
{
echo"<h4> you have selected..</h4>";
if(!empty($_POST['check_list']))
foreach($_POST['check_list'] as $selected)
{
echo "$selected </br>";
}
}
?>
List :
The List box displays all the items at once in a text area
Example :
Create a form in some HTML file as follows- Input.html
<html>
<body>
<div>
<form action="index.php" method="post">
<p><select name="products[]" multiple="multiple">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select></p>
<p><input type="submit" value="hit it!" /></p>
</form>
</div>
</body>
</html>
Now the index.php program can be as follws-
<?php
if (is_array ( $_POST ['products'] )) {
print "<p>Your product choices are:</p>";
foreach ( $_POST ['products'] as $value ) {
print "$value\n";
}
print "</ul>";
}
?>
Combo Box :
The combo box displays only one item at a time
The Combo box is a combination of a text box in which the user
enters an item and a drop-down list from which the user selects an
item.
Example :
Create a form in some HTML file as follows- Input.html
<html>
<body>
<form action="index.php" method="post">
<p><select name="products[]“>
<option>option1</option>
<option>option2</option>
<option>option3</option>
</select>
<p><input type="submit" value="hit it!" /></p>
</body>
</html>
Now the index.php program can be as follws-
<?php
if (is_array ( $_POST ['products'] )) {
print "<p>Your choices is:</p>";
foreach ( $_POST ['products'] as $value ) {
print "$value\n";
}
print "</ul>";
}
?>
Hidden Control
A hidden field lets web developers include data that cannot be seen or modified by
users when a form is submitted.
A hidden field often stores what database record that needs to be updated when the
form is submitted.
Note: While the value is not displayed to the user in the page's content, it is visible (and
can be edited) using any browser's developer tools or "View Source" functionality. Do
not use hidden inputs as a form of security!
Hidden Control
Create a form in some HTML file as follows- Input.html
<html>
<body>
<h1>Define a hidden input field:</h1>
<form action="actionpage.php" method="POSt">
<input type="hidden" name="custId" value="3487">
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
if(isset($_POST["custId"]))
{
echo "Cust ID:".$_POST['custId'];
}
?>
Working with multiple Forms:
<html>
<head>
</head>
<body>
<form name="mailform" method="post" action="ind.php">
<input type="text " name="email" id="email"/>
<input type="submit" name="mail-submit" value="Send Mail"/>
</form>
<form name="mobileform" method="post" action="ind.php">
<input type="text" name="mobileno" id="mobileno"/>
<input type="submit" name="mob-submit" value="Send Contact"/>
</form>
</body>
</html>
<?php
if($_SERVER['REQUEST_METHOD']=="POST")
if(!empty($_POST['mail-submit'])){
echo "Your mail is:".$_POST['email'];
}
else if(!empty($_POST["mob-submit"])){
echo "Your no is:".$_POST['mobileno'];
}
?>
Working with multiple Submit button :
Create a form in some HTML file as follows- Input.html
<html>
<head>
</head>
<body>
<form name="mailform" method="post" action="ind.php">
<input type="text " name="no1" id="no1" />
<input type="text" name="no2" id="no2" />
<input type="submit" name="addno" value="Add" />
<input type="submit" name="subno" value="Sub" />
</form>
</body>
</html>
Now the ind.php program can be as follws-
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
if(isset($_POST['addno'])){
echo "Addition:".((int)$_POST['no1']+(int)$_POST['no2']);
}
else if(isset($_POST['subno'])){
echo "Subtraction:".((int)$_POST['no1']-(int)$_POST['no2']);
}
}
?>
Web Page Validation :
Validation means check the input submitted by the user.
There are two types of validation are available in PHP:
Client side validation : Validation is performed on the client machine web browsers.
Server side validation : After submitted the data, the data has sent to a server and
perform validation check in server machine.
Some of validation rules for fields :
<?php
if($_SERVER['REQUEST_METHOD']==='POST')
{
if(!empty($_POST['name']))
{
echo "Name cant be blank<br/>";
}
if(!is_numeric($_POST['mob']))
{
echo "Enter valid Mobile Number<br/>";
}
$pattern='/\b[\w.-]+@[\w.-]+\[A-Za-z]{2,6}\b';
if(!preg_match($pattern,$_POST['email']))
{
echo "Enter valid Email ID<br/>";
}
}
?>
Cookies
• PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in
remote browser and thus tracking or identifying return users. Cookies are part of the
HTTP header.
• Cookie is created at server side and saved to client browser.
• A cookie is a small file with the maximum size of 4KB that the web server stores on the
client computer.
• Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
Note: The setcookie() function must appear BEFORE the <html> tag.
Name - This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value -This sets the value of the named variable and is the content that you actually want
to store.
Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After
this time cookie will become inaccessible. If this parameter is not set then cookie will
automatically expire when the Web Browser is closed.
Path -This specifies the directories for which the cookie is valid. A single forward slash
character permits the cookie to be valid for all directories.
Domain - This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. All cookies are only valid for the host and domain
which created them.
Security - This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular
HTTP.
Example:
cookie.php
<?php
//setcookie(name, value, expire);
setcookie('actor_name', 'joaquin phoenix', time()+30);
setcookie('age', '44', time()+30);
echo "The cookie has been set for 30 seconds";
?>
cookie_view.php
<?php
$actor_name = $_COOKIE['actor_name'];
$actor_age = $_COOKIE['age'];
echo "$actor_name";
echo " $actor_age";
?>
Types of Cookies
Tip: If you need a permanent storage, you may want to store the data in a database.
Start a PHP Session
• A session is started with the session_start() function.
• Session variables are set with the PHP global variable: $_SESSION.
• Now, let's create a new page called "demo_session1.php". In this page, we start a new
PHP session and set some session variables:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Get PHP Session Variable Values
• Next, we create another page called "demo_session2.php". From this page, we will
access the session information we set on the first page ("demo_session1.php").
• Notice that session variables are not passed individually to each new page, instead they
are retrieved from the session we open at the beginning of each page (session_start()).
• Also notice that all session variable values are stored in the global $_SESSION variable:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Modify a PHP Session Variable
• To change a session variable, just overwrite it:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
Destroy a PHP Session
• To remove all global session variables and destroy the session,
use session_unset() and session_destroy():
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>
Cookies Session
Cookies are client side file that Session are Sever side file that
contain user information contain user information
Cookies are stored in users browser sessions are not
A cookie can keep information in the session is that when you close your
users browser until deleted browser you also lose the session
If you set variables to cookies then If you set variables to session then
your users will not have to login each user activity will be tracked using
time they enter your community browser session and your users will
have to login each time they reopen
the browser
Cookies can only store Strings Store our object in sessions
Save cookie in future reference Session could not. User close their
Email :
The mail() function allows you to send emails directly from a script.
Syntax
mail(to,subject,message,headers,parameters);
Parameter Description
subject Required. Specifies the subject of the email. Note: This parameter cannot contain
any newline characters
message Required. Defines the message to be sent. Each line should be separated with a LF
(\n). Lines should not exceed 70 characters.
Windows note: If a full stop is found on the beginning of a line in the message, it
might be removed. To solve this problem, replace the full stop with a double dot:
<?php
?>
headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional
headers should be separated with a CRLF (\r\n).
Note: When sending an email, it must contain a From header. This can be set with
this parameter or in the php.ini file.
parameters Optional. Specifies an additional parameter to the sendmail program (the one
defined in the sendmail_path configuration setting). (i.e. this can be used to set the
<?php
// the message
$msg = "First line of text\nSecond line of text";
// send email
mail("[email protected]","My subject",$msg);
?>