4.1 Creating a webpage using Form controls, Accessing data from web page.
4.5 Working with multiple Forms:
Form Control:
It is a field used inside HTML form tag to take input from user and store it in a variable called parameter.
Following are the Form Controls used in form tag <form>:
1. Text Field: Here input type isastring, stored in a variable “username”.
Example:
<input type=”text” name=”username”>
2. Password Field:Here input type is a hidden string shown by *, stored in a variable “passwd”.
Example:
<input type=”password” name=”passwd” >
3. Textarea Field: Here input type is a paragraph, stored in a variable “textpara”. It will display paragraph upto 10 lines with 30 column width. Later it becomes scrollable.
Example:
<textarea name=" textpara " rows="10" cols="30"> Write Here</textarea>
4. Drop Down List Field: Here input types are Item list in a drop down form,selected item will be stored in variable name “state”.
Example:
<select name=" state ">
<option value="MH">Maharashtra</option>
<option value="MP">Madhya Pradesh</option>
<option value="GJ">Gujarat</option>
<option value="RJ">Rajasthan</option>
</select>
5. Button field: It is used to trigger action based on click event.
Example:
<button type="button" onclick="alert('Hello!')">Click! </button>
These all fields are used inside a form tag which itself uses three attributes frequently:
1. Action: It is an attribute of form tag which is used to decide where to go after form submission.
2. Method: It is an attribute of a form tag which is used to select a way to send data either through GET or POST.
3. Name: It is an attribute of form tag used to give name of form and this in turn help developer to access field values of that form using dot [.] operator.
Accessing data from web page (HTML)
PHP has set of variables which are globally accessible and following variables are called as superglobal variables used to access data from web page:
1. $_SERVER:It keeps information about header, path and scripts.
2. $GLOBALS:It is used to keep variables and objects accessible from anywhere in script.
3. $_REQUEST: It is used to receive data from submitted html form.
4. $_POST: It is frequently used to access data from submitted form when post method is used in form.
5. $_GET:It is frequently used to access data from submitted form when get method is used in form.
6. $_FILES: To Handle file related activities.
7. $_ENV: To set environmental variables so that php shell libraries can be used.
8. $_COOKIE: It is used to create and access a temporary file stored at client machine. It stores and deletes common user information related with site.
9. $_SESSION: It is used to keep track of user identity and its details while surfing any website.
4.2 Browser Role-GET and POST methods:
In the form of difference between GET and POST
GET
|
POST
|
1. It is faster than POST
|
1. It is slower than GET
|
2. It shows all field values.
|
2. It hides all field values.
|
3. It does not encrypt data
|
3. It encrypts data.
|
4. It is used for general communication
|
4. It is used for confidential communication.
|
Example Form tag:
<form name =”Example” action=”welcome.php” method=”POST”>
<!-- This is used for Comment in HTML -->
</form>
4.3 Server Role:
1. For the purpose of web hosting means saving all your web application in a remote computer and use a program called Server Software to access web application through url.
2. It is used to connect with database.
3. It is used to access database.
4. It is used to protect access from confidential data.
5. Control bandwidth and regulate network traffic.
6. Example of PHP Server is XAMPP, LAMP, WAMP etc.
4.4 Web Page Validation:
Validation: To check logical correctness of data.
Example: username should not be empty, Email id syntax should be correct, password must have number etc.
In PHP following variables and functions are used to validate form data.
1. htmlspecialchars() : Used to convert html special tags like “<”, “>” character into < ,> to prevent it from attackers.
2. $_SERVER["REQUEST_METHOD"] : Used to check method is post or get.
3. trim($data): Used to remove left and right spaces in a string.
4. stripslashes(): Removes backslashes.
5. empty($data): check the value in variable is empty or not.
6. preg_match(): Used to check required string pattern.
7. filter_var($email, FILTER_VALIDATE_EMAIL): To check $email variable has correct syntax of email: xxx@yyy.zzz
Regular Expression:Used to make pattern rule.
Example:String with No Number, Only Vowels, Only start with A etc.
Preg_match(), Preg_split() and Preg_replace() follows some notations which should be used to make our own string pattern rule.
1. / start with slash…..end with slash /
2. “.” Dot means any single character Ex: /./ any single character.
3. ^ Carat means match from beginning character. Ex: /^A/ any string starting from “A”.
5. * Asterisk means zero or more character Ex: D* Doctor, Department.
6. + plus means preceding character match. Ex: a+tejas, date, has etc having ‘a’.
7. \ backslash means escape character for double single quotes.
8. […] character set. Ex : /[in]/ sachin, chinmayetc
9.a-z lower a to z Ex : /a-z/ as, and etc
10. 0-9 any number Ex: /0-9/ 235, 457 etc
11.A-Z any upper case. Ex /A-Z/ ABC,AAA etc
*Form Submission:
It is happened in 4 steps:
1. Form creation using html tags.
2. Pass Form values using $_POST[] to functions after submission of form.
3.Check each post field data and create error message if any, and save it in error variable.
4. Write all error variables again beside form Fields.
1st step:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<html>
<head>
</head>
<body>
<h2>Step 1 To create Form</h2>
<form method="post" action="">
Name: <input type="text" name="name"><br><br>
E-mail: <input type="text" name="email"> <br><br>
Review: <textarea name="review" rows="4" cols="20"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
<form method="post" action="">
Name: <input type="text" name="name"><br><br>
E-mail: <input type="text" name="email"> <br><br>
Review: <textarea name="review" rows="4" cols="20"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
2nd step:
<?php
// define variables and set to empty values
$name = "";
$email = "";
$gender = "";
$review = "";
//Errors message will be added later.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = removespecialChar($_POST["name"]);
$email = removespecialChar($_POST["email"]);
$review = removespecialChar($_POST["review"]);
$gender = removespecialChar($_POST["gender"]);
}
function removespecialChar($var) {
$var = htmlspecialchars($var);
$var = trim($var);
$var = stripslashes($var);
return $var;
}
?>
*Refer www.w3school.com for detail validation
3rd step:
<?php
// Error handling variables
$nameError = "";
$emailError = "";
$genderError = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameError = "Name is required";
} else {
$name = removespecialChar($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailError = "Email is required";
} else {
$email = removespecialChar($_POST["email"]);
}
if (empty($_POST["gender"])) {
$genderError = "Gender is required";
} else {
$gender = removespecialChar($_POST["gender"]);
}
}
4th step:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span style="color:red;">* <?php echo $nameError;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span style="color:red;">* <?php echo $emailError;?></span>
<br><br>
Review: <textarea name="review" rows="4" cols="20"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span style=”color:red;”>* <?php echo $genderError;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Name: <input type="text" name="name">
<span style="color:red;">* <?php echo $nameError;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span style="color:red;">* <?php echo $emailError;?></span>
<br><br>
Review: <textarea name="review" rows="4" cols="20"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span style=”color:red;”>* <?php echo $genderError;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Combine All:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = "";
$email = "";
$gender = "";
$review = "";
$nameError = "";
$emailError = "";
$genderError = "";
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameError = "Name is required";
} else {
$name = removespecialChar($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailError = "Email is required";
} else {
$email = removespecialChar($_POST["email"]);
}
if (empty($_POST["gender"])) {
$genderError = "Gender is required";
} else {
$gender = removespecialChar($_POST["gender"]);
}
}
function removespecialChar($var) {
$var = htmlspecialchars($var);
$var = trim($var);
$var = stripslashes($var);
return $var;
}
?>
<h2>Step 1 To create Form</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name">
<span style="color:red;">* <?php echo $nameError; ?></span>
<br><br>
E-mail: <input type="text" name="email">
<span style="color:red;">* <?php echo $emailError; ?></span>
<br><br>
Review: <textarea name="review" rows="4" cols="20"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span style="color:red;">* <?php echo $genderError; ?></span><br><br>
<input type="submit" name="submit" value="Submit">
</form>
<!--Display all form details:-->
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $review;
echo "<br>";
echo $gender;
?>
</body></html>
4.5 Working with multiple Forms:
If more than 1 form is used in a web page it is called as multi Form Page and it may have more than 1 submit button also.
To handle multiform:
1. Use different ‘id’ attribute value in form tag to differentiate among many forms.
2. Use different name attribute value of submit input tag to differentiate among many submit buttons.
3. Use isset to check which submit is clicked.
Example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h2>Form 1</h2>
<form id="form1" method="post" action="">
Name: <input type="text" name="name"><br><br>
<input type="submit" name="submit1" value="Submit">
</form>
<h2>Form 2</h2>
<form id="form2" method="post" action="">
Name: <input type="text" name="name"><br><br>
<input type="submit" name="submit2" value="Submit">
</form>
<?php
//isset is used to check submit is clicked or not.
if (isset($_POST['submit1'])) {
if ($_POST['submit1']) {
echo "Form 1 Submitted ";
echo "Name from Form 1 is :" . $_POST["name"];
}
}
if (isset($_POST['submit2'])) {
if ($_POST['submit2']) {
echo "Form 2 Submitted ";
echo "Name from Form 2 is :" . $_POST["name"];
}
}
?>
</body>
</html>
4.6 Cookies –
Use of cookies: It is a small file saving temporary data of user in the user’s machine when visit any website. It is used to identify user.
Attributes of cookies: Following are the attributes or arguments used in cookie creation:
1. name:This is used to set name of cookie file and this is stored in a variable HTTP_COOKIE_VARS.
2. value: Set value of the named variable.
3. expire: Decide the Time when cookie become invalid.
4. path: It give information about valid directory.
5. domain: To Mention the domain name.
6. security:Set 1 to send through secure line https else 0 to send it by http also.
Create cookies:Usingsetcookie(name,value,expire,path,domain,security) function you can create cookie.
Example :
<!DOCTYPE HTML>
<?php
setcookie("name", "Satish", time()+3600, "/","", 0);
setcookie("city", "Mumbai", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Cookie Example </title>
</head>
<body>
<?php echo "Cookies are Created Now"?>
</body>
</html>
Retrieve cookies: To access cookies we can use $_COOKIE variables.
Example:
<!DOCTYPE HTML>
<html>
<head>
<title>Retrieving Cookie</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
echo $_COOKIE["city"] . "<br />";
?>
</body>
</html>
Modify cookies value:To modify cookie just call setcookie() function again that will overwrite all variables and its values.
Delete cookies: To delete the cookies just set time before current time so it will not be accessible.
Example:
<!DOCTYPE HTML>
<?php
setcookie( "name", "", time()- 60, "/","", 0);//Means Cookie Expire already.
?>
<html>
<head>
<title>Delete Cookie Example</title>
</head>
<body>
<?php echo "Cookies Deleted" ?>
</body>
</html>
4.7 Session
Use of session:
1. To identify user.
2. To keep track of visitors and its activity.
3. Toaccessdatain all the web pageswhilesurfinginbetween login and logout duration.
4. To Perform Multi User task by keeping temporary user specific data separately in server.
Start session and set and get session value:
Following steps are used to start session:
1. To start session, session_start() function is called at the beginning of the page.
2. Use isset() function to check whether session is set or not.
3. Assign and Store data using $_SESSION[] variable.
4. Get data using $_SESSION[] variable.
Modify PHP session variable: Just overwrite the $_SESSION[] variable’s value with the new value can change its session value.
Example:
<?php
session_start();
if( isset( $_SESSION['num'] ) ) {
$_SESSION['num'] = $_SESSION['num']+1; //By overwriting we can change session value
}else {
$_SESSION['num'] = 1;
}
$show = "Visit Number in Current Session is ". $_SESSION['num'];
?>
<html>
<head>
<title>Session Example</title>
</head>
<body>
<?php echo $show; ?>
</body>
</html>
Destroy session: To destroy session there are two ways.
1. To destroy single variable use unset() function
2. To destroy whole session usesession_destroy()
Example:
<?php
unset($_SESSION['username']); //To destroy single variable inside session
session_destroy(); // To Destroy whole session.
?>
4.8 Sending Email: Steps to send email are as follows:
1.Set the sender details in php.ini present in server folder of php folder. [For details of configurationsetting, check practical notes]
2. Use mail( to, subject, message, headers, parameters ) function to send email. Following the description of parameter used in mail functions:
1. to: Receiver’s Email Id
2. subject: Subject of the email.
3. message: The email body which generally consist of 70 characters.
4. headers: It is used to add Carbon Copy(CC) or Blind Carbon Copy(BCC) . This should be separated by \r\n.
5. Parameters: It is an optional one. It can be used to add other information about email.
Example:
<html>
<head>
<title>Email Using PHP</title>
</head>
<body>
<?php
$to = "abc@xyz.pqr";
$subject = "Your Subject";
$message = "<b>Your message in html form</b>";
$header = "From:abc@xyz.pqr \r\n";
$header .= "Cc:def@yyy.pqr \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$isSent = mail ($to,$subject,$message,$header);
if( $isSent == true ) {
echo "Successfully Sent.";
}else {
echo "Failed to send";
}
?>
</body>
</html>
No comments:
Post a Comment