!doctype HTML Body Form Input BR Input BR Input /form /body

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

<!

DOCTYPE HTML>
<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>
Output
Welcome John
Your email address is john.doe@example.com

The same result could also be achieved using the HTTP GET method:

<!DOCTYPE HTML>
<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>

GET vs. POST


Both GET and POST create an array (e.g. array( key1 => value1, 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.

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.

Developers prefer POST for sending form data.

Next, lets see how we can process PHP forms the secure way!

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>

<?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;
}
?>

<h2>PHP Form Validation Example</h2>


<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SEL
F"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
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
<input type="radio" name="gender" value="other">Other
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values

//form requried
$nameErr = $emailErr = $genderErr = $websiteErr = "";

$name = $email = $gender = $comment = $website = ""; //form handling

//form particular validations


if ($_SERVER["REQUEST_METHOD"] == "POST")//form handling {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);//form handling
// 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"]);//form handling
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);//form handling
// 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"]);//form handling
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);//form handling
}
}

//form handling
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>


<p><span class="error">* required field</span></p>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SEL


F"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website" value="<?php echo $website;?
>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $commen
t;?></textarea>
<br><br>
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
<input type="radio" name="gender" <?php if (isset($gender) &&
$gender=="other") echo "checked";?> value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

Example (MySQLi Object-oriented)


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

Note: When you create a new database, you must only specify the first three
arguments to the mysqli object (servername, username and password).

Tip: If you have to use a specific port, add an empty string for the database-
name argument, like this: new mysqli("localhost", "username", "password", "",
port)

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Note: The following PDO example create a database named "myDBPDO":

Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

Tip: A great benefit of PDO is that it has exception class to handle any
problems that may occur in our database queries. If an exception is thrown
within the try{ } block, the script stops executing and flows directly to the first
catch(){ } block. In the catch block above we echo the SQL statement and the
generated error message.

Create a MySQL Table Using MySQLi and PDO


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {


echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Program No: 1
Write a Servlet program to validate login.
1) Open an NetBeans.

2) Create New Project->Java web->select webapplication----finish

3) Default a index.html is created in the folder web.

4) Update the below content in the index.html file

<html><head>

<title>Login page</title>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

<form name="f1" action="http://localhost:8080/MyServlet/LoginServlet"


method="get">

username<input type="text" name="uname"><br>

password<input type="password" name="pass"><br>

<input type="submit" value="click">

<input type="reset" value="clear">

</form></body></html>

5) Click on the project→rightclick—>New->servlet

6) Servlet class is created with the methods. Replace the proccessRequest method with service
name.

7) Modify the selvlet content

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {


public void service(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try


(PrintWriter out = response.getWriter()) {

String name=request.getParameter("uname");
String pwd=request.getParameter("pass");
out.println("<html><head><title>Login</title></head>");
out.println("<body bgcolor='pink'>"); if(name.equals("admin")&&
pwd.equals("test"))

out.println("<h2>Login successful</h2>");out.println("<form
action='http://localhost:8080/ServletDemo/NewServlet ' method='get'>");

out.println("<input type='submit' value='proceed'></form>");

else

out.println("<h2>Login unsuccessful</h2>");

out.println("</body></html>");

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left


to edit the code.">

/**

* Handles the HTTP <code>GET</code> method.

* @param request servlet request

* @param response servlet response

* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

/**

* Handles the HTTP <code>POST</code> method.

* @param request servlet request


* @param response servlet response
* @throws ServletException if a servlet-specific error occurs

* @throws IOException if an I/O error occurs

*/

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

/**

* Returns a short description of the servlet.


*

* @return a String containing servlet description

*/

@Override

public String getServletInfo() {

return "Short description";

}// </editor-fold>

8. Build the project.

Date Servlet

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*; import
java.util.*;

public class DateServlet extends


HttpServlet

public void init(){}

public void service(HttpServletRequest req, HttpServletResponse res) throws

ServletException, IOException{

PrintWriter out = res.getWriter();


res.setContentType("text/html"); out.println("Current
date & time"+new Date());

Program No: 2

Write a Servlet program to demonstrate how to access parameters through a servlet.


<html>

<title>"Sample Page</title>
<body>

<center>

<form name = "form2" method = "post" action="http://localhost:8080/DataServlet/cse"> Enter ur Name:


<input type="text" name ="nm">

<br><br>

Enter ur age : <input type ="text" name ="age">

<br><br>

<input type="submit" value="submit">

</form>

</body>

</html>

1) Open another editor & type the following code: ( web.xml)

<web-app>

<servlet>

<servlet-name>DApp</servlet-name>
<servlet-class>DServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>DApp</servlet-name>
<url-pattern>/cse</url-pattern>

</servlet-mapping>

</web-app>

2) Open another editor & type the following Servlet code: ( DServlet.java)

import javax.servlet.*; import


javax.servlet.http.*; import java.io.*;

public class DServlet extends HttpServlet{

public void service(HttpServletRequest req, HttpServletResponse res) throws IOException,


ServletException{

String name = req.getParameter("nm"); String age


= req.getParameter("age");
res.setContentType("text/html"); PrintWriter out =
res.getWriter(); out.println("<B>My Name is:"+name);
out.println("<B>and My age is "+age); out.close();

Program No: 3
Write a Servlet program to demonstrate Color servlet
1) Edit the following code: (Save as Color.html)

<html><body>

<center>

<form name = "Form1" method = "post" action =


"http://localhost:8080/ColorServlet/color">

<b>Color :</b>

<select name="color" size="1">

<option value = "red">Red</option>

<option value = "Green">Green</option>

<option value = "Blue">Blue</option>

</select>

<br><br>

<input type ="submit" value="submit">


</form>
</body></html>

2) type the following code: ( web.xml)

<web-app><servlet>

<servlet-name>CServlet</servlet-name>

<servlet-class>ColorServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>CServlet</servlet-name>

<url-pattern>/color</url-pattern>

</servlet-mapping></web-app>

3) Open another editor & type the following Servlet code: ( ColorServlet.java)

import javax.servlet.*; import


javax.servlet.http.*; import java.io.*;

public class ColorServlet extends HttpServlet{

public void service(HttpServletRequest req, HttpServletResponse res) throws

ServletException, IOException{

String str = req.getParameter("color");


res.setContentType("text/html"); PrintWriter
out = res.getWriter(); out.println("<h1>");

out.println("<b> Selected Color is");

out.println(str);

out.close();

Demonstrate Cookies with relevant example


1) Open and editor & type the following code: (CookieServlet.java)
import javax.servlet.http.*;

import java.io.*;

import java.util.*;

public class CookieServlet extends HttpServlet{

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws IOException{

PrintWriter out = response.getWriter();

Cookie[] c = request.getCookies(); String user = null;


String responseString = null;

if ( c != null ){

for ( int x = 0; x < c.length; x++ ){

String name = c[x].getName();


if ( name.equals("session_id") ){

if((c[x].getValue()).equals("561")){

user = new String("ANUCE");

break;

}
if ( user == null ){

response.addCookie(new Cookie("session_id", "561"));

responseString = new String("Welcome to our site,we have created a session for you.");

}else{

responseString = new String("Hello : " + user);

} out.println("<html>"); out.println("<body>");
out.println(responseString); out.println("</body></html>");

import javax.servlet.http.*;

import java.io.*;

import java.util.*;
public class HttpSessionServlet extends HttpServlet

public void doGet(HttpServletRequest request,HttpServletResponse response)throws

IOException

PrintWriter out = response.getWriter();

String[] movies = null;

HttpSession s = request.getSession();

if ( s != null ){
movies = (String[])s.getAttribute("Movies");

out.print("<html>");

out.print("<body>");

out.print("<H2>Thank you for purchasing:</H2>");


for ( int x = 0; x < movies.length; x++ )

out.print(movies[x] + "<BR>");

out.print("</body></html>");

public void doPost(HttpServletRequest request,HttpServletResponse response)throws

IOException{

PrintWriter out = response.getWriter();

String movies[] = request.getParameterValues("Movies"); HttpSession s =


request.getSession();

if ( s != null ){

s.setAttribute("Movies", movies);

out.print("<html>");

out.println("<body>");

out.println("<h2>Contents of Shopping Cart</h2>");

for ( int x = 0; x < movies.length; x++ ){

out.print(movies[x] + "<br>");

out.println("<form action=\"http://localhost:8888/Session/hss\" method=\"get\">");


out.println("<input type=\"submit\" value=\"Proceed to Checkout\"></form>");
out.println("</body></html>");

1) Create web.xml with the following code:

<web-app>

<servlet>

<servlet-name>hss</servlet-name>
<servlet-class>HttpSessionServlet</servlet-class>
</servlet>

<servlet-mapping>

<servlet-name>hss</servlet-name>

<url-pattern>/hss</url-pattern>

</servlet-mapping>

</web-app>

You might also like