Form Handling in PHP

Last updated on May 31 2022
Aridam Das

Table of Contents

Form Handling in PHP

Dynamic Websites

The Websites provide the functionalities that can use to store, update, retrieve, and delete the data in a database.

What is the Form?

A Document that containing black fields, that the user can fill the data or user can select the data.Casually the data will store in the data base

Example

Below example shows the form with some specific actions by using post method.

<html>      

<head>      

<title>PHP Form Validation</title>   

</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>Tecklearn Absolute classes registration</h2>            

<form method = "post" action = "/php/php_form_introduction.htm">         

<table>            

<tr>               

<td>Name:</td>                

<td><input type = "text" name = "name"></td>           

 </tr>                        

<tr>               

<td>E-mail:</td>               

<td><input type = "text" name = "email"></td>           

 </tr>                        

<tr>               

<td>Specific Time:</td>               

<td><input type = "text" name = "website"></td>           

 </tr>                        

<tr>               

<td>Class details:</td>               

<td><textarea name = "comment" rows = "5" cols = "40"></textarea></td>            

</tr>                       

 <tr>               

<td>Gender:</td>              

 <td>                  

<input type = "radio" name = "gender" value = "female">Female                 

 <input type = "radio" name = "gender" value = "male">Male               

</td>            

</tr>                     

<tr>               

<td>                  

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

</td>            

</tr>         

</table>      

</form>            

<?php        

 echo "<h2>Your Given details are as :</h2>";        

 echo $name;         

echo "<br>";                 

 echo $email;         

echo "<br>";                  

echo $website;        

 echo "<br>";                 

 echo $comment;         

echo "<br>";                  

echo $gender;      

?>         

</body>

</html>

PHP – Validation Example

Required field will check whether the field is filled or not in the proper way. Most of cases we will use the * symbol for required field.

What is Validation ?

Validation means check the input submitted by the user. There are two types of validation are available in PHP. They are as follows −

  • Client-Side Validation − Validation is performed on the client machine web browsers.
  • Server Side Validation − After submitted by data, The data has sent to a server and perform validation checks in server machine.

Some of Validation rules for field

Field Validation Rules
Name Should required letters and white-spaces
Email Should required @ and .
Website Should required a valid URL
Radio Must be selectable at least once
Check Box Must be checkable at least once
Drop Down menu Must be selectable at least once

Valid URL

Below code shows validation of URL

$website = input($_POST["site"]); 
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) 
{   
$websiteErr = "Invalid URL"; 
}

Above syntax will verify whether a given URL is valid or not. It should allow some keywords as https, ftp, www, a-z, 0-9,..etc..

Valid Email

Below code shows validation of Email address

$email = input($_POST["email"]); 
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) 
{
$emailErr = "Invalid format and please re-enter valid email"
; 
}

Above syntax will verify whether given Email address is well-formed or not.if it is not, it will show an error message.

Example

Example below shows the form with required field validation

<html>      
<head>      
<style>         
.error {color: #FF0000;}      
</style>   
</head>      
<body>      
<?php         
// 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"])) 
{              
 $nameErr = "Name is required";            
}
else 
{               
$name = test_input($_POST["name"]);           
}                        
if (empty($_POST["email"])) 
{               
$emailErr = "Email is required";            
}else
 {              
 $email = test_input($_POST["email"]);                             
 // 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"]);            
}                        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"]);           
 }         
}                 
function test_input($data) 
{            
$data = trim($data);           
$data = stripslashes($data);           
$data = htmlspecialchars($data);           
return $data;         
}      
?>           
<h2>Absolute classes registration</h2>           
<p><span class = "error">* required field.</span></p>          
 <form method = "post" action = "
<?php          
echo htmlspecialchars($_SERVER["PHP_SELF"]);
?>">         
<table>            
<tr>               
<td>Name:</td>               
<td><input type = "text" name = "name">                  
<span class = "error">* <?php echo $nameErr;?></span>               
</td>            
</tr>                       
<tr>              
<td>E-mail: </td>               
<td><input type = "text" name = "email">                  
<span class = "error">* <?php echo $emailErr;?></span>               
</td>            
</tr>                       
<tr>               
<td>Time:</td>               
<td> <input type = "text" name = "website">                  
<span class = "error"><?php echo $websiteErr;?></span>              
</td>            
</tr>                       
<tr>               
<td>Classes:</td>               
<td> <textarea name = "comment" rows = "5" cols = "40"></textarea></td>            
</tr>                        
<tr>               
<td>Gender:</td>              
 <td>                  
<input type = "radio" name = "gender" value = "female">Female                 
 <input type = "radio" name = "gender" value = "male">Male                 
 <span class = "error">* <?php echo $genderErr;?></span>              
 </td>            
</tr>                                                                         
<td>               
<input type = "submit" name = "submit" value = "Submit">             
</td>                                                                      
</table>                                                   
</form>            
<?php         
echo "<h2>Your given values are as:</h2>";         
echo $name;         
echo "<br>";                  
echo $email;         
echo "<br>";                 
echo $website;         
echo "<br>";                
echo $comment;         
echo "<br>";                 
echo $gender;      
?>      
</body>
</html>

It will produce the following result −

28

PHP – Complete Form

This page explains about time real-time form with actions. Below example will take input fields as text, radio button, drop down menu, and checked box.

Example

 <html>

  

   <head>

      <style>

         .error {color: #FF0000;}

      </style>

   </head>

  

   <body>

      <?php

         // define variables and set to empty values

         $nameErr = $emailErr = $genderErr = $websiteErr = "";

         $name = $email = $gender = $class = $course = $subject = "";

        

         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"]);

              

               // check if e-mail address is well-formed

               if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

                  $emailErr = "Invalid email format";

               }

            }

           

            if (empty($_POST["course"])) {

               $course = "";

            }else {

               $course = test_input($_POST["course"]);

            }

           

            if (empty($_POST["class"])) {

               $class = "";

            }else {

               $class = test_input($_POST["class"]);

            }

           

            if (empty($_POST["gender"])) {

               $genderErr = "Gender is required";

            }else {

               $gender = test_input($_POST["gender"]);

            }

           

            if (empty($_POST["subject"])) {

               $subjectErr = "You must select 1 or more";

            }else {

               $subject = $_POST["subject"];             

            }

         }

        

         function test_input($data) {

            $data = trim($data);

            $data = stripslashes($data);

            $data = htmlspecialchars($data);

            return $data;

         }

      ?>

                              

      <h2>Absolute classes registration</h2>

     

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

     

      <form method = "POST" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

         <table>

            <tr>

               <td>Name:</td>

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

                  <span class = "error">* <?php echo $nameErr;?></span>

               </td>

            </tr>

           

            <tr>

               <td>E-mail: </td>

               <td><input type = "text" name = "email">

                  <span class = "error">* <?php echo $emailErr;?></span>

               </td>

            </tr>

           

            <tr>

               <td>Time:</td>

               <td> <input type = "text" name = "course">

                  <span class = "error"><?php echo $websiteErr;?></span>

               </td>

            </tr>

           

            <tr>

               <td>Classes:</td>

               <td> <textarea name = "class" rows = "5" cols = "40"></textarea></td>

            </tr>

           

            <tr>

               <td>Gender:</td>

               <td>

                  <input type = "radio" name = "gender" value = "female">Female

                  <input type = "radio" name = "gender" value = "male">Male

                  <span class = "error">* <?php echo $genderErr;?></span>

               </td>

            </tr>

           

            <tr>

               <td>Select:</td>

               <td>

                  <select name = "subject[]" size = "4" multiple>

                     <option value = "Android">Android</option>

                     <option value = "Java">Java</option>

                     <option value = "C#">C#</option>

                     <option value = "Data Base">Data Base</option>

                     <option value = "Hadoop">Hadoop</option>

                     <option value = "VB script">VB script</option>

                  </select>

               </td>

            </tr>

            

            <tr>

               <td>Agree</td>

               <td><input type = "checkbox" name = "checked" value = "1"></td>

               <?php if(!isset($_POST['checked'])){ ?>

               <span class = "error">* <?php echo "You must agree to terms";?></span>

               <?php } ?>

            </tr>

           

            <tr>

               <td>

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

               </td>

            </tr>

           

         </table>

      </form>

     

      <?php

         echo "<h2>Your given values are as :</h2>";

         echo ("<p>Your name is $name</p>");

         echo ("<p> your email address is $email</p>");

         echo ("<p>Your class time at $course</p>");

         echo ("<p>your class info $class </p>");

         echo ("<p>your gender is $gender</p>");

        

         for($i = 0; $i < count($subject); $i++) {

            echo($subject[$i] . " ");

         }

      ?>

     

   </body>

</html>

 

 

29

PHP – Login Example

PHP login with session

Php login script is used to provide the authentication for our web pages. the Script executes after submitting the user login button.

Login Page

Login page should be as follows and works based on session. If the user close the session, it will erase the session data.

 

<?php

   ob_start();

   session_start();

?>




<?

   // error_reporting(E_ALL);

   // ini_set("display_errors", 1);

?>




<html lang = "en">

  

   <head>

      <title>Tecklearn.com</title>

      <link href = "css/bootstrap.min.css" rel = "stylesheet">

     

      <style>

         body {

            padding-top: 40px;

            padding-bottom: 40px;

            background-color: #ADABAB;

         }

        

         .form-signin {

            max-width: 330px;

            padding: 15px;

            margin: 0 auto;

            color: #017572;

         }

        

         .form-signin .form-signin-heading,

         .form-signin .checkbox {

            margin-bottom: 10px;

         }

        

         .form-signin .checkbox {

            font-weight: normal;

         }

        

         .form-signin .form-control {

            position: relative;

            height: auto;

            -webkit-box-sizing: border-box;

            -moz-box-sizing: border-box;

            box-sizing: border-box;

            padding: 10px;

            font-size: 16px;

         }

        

         .form-signin .form-control:focus {

            z-index: 2;

         }

        

         .form-signin input[type="email"] {

            margin-bottom: -1px;

            border-bottom-right-radius: 0;

            border-bottom-left-radius: 0;

            border-color:#017572;

         }

        

         .form-signin input[type="password"] {

            margin-bottom: 10px;

            border-top-left-radius: 0;

            border-top-right-radius: 0;

            border-color:#017572;

         }

        

         h2{

            text-align: center;

            color: #017572;

         }

      </style>

     

   </head>

              

   <body>

     

      <h2>Enter Username and Password</h2>

      <div class = "container form-signin">

        

         <?php

            $msg = '';

           

            if (isset($_POST['login']) && !empty($_POST['username'])

               && !empty($_POST['password'])) {

                                                            

               if ($_POST['username'] == 'tecklearn' &&

                  $_POST['password'] == '1234') {

                  $_SESSION['valid'] = true;

                  $_SESSION['timeout'] = time();

                  $_SESSION['username'] = 'tecklearn';

                 

                  echo 'You have entered valid use name and password';

               }else {

                  $msg = 'Wrong username or password';

               }

            }

         ?>

      </div> <!-- /container -->

     

      <div class = "container">

     

         <form class = "form-signin" role = "form"

            action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);

            ?>" method = "post">

            <h4 class = "form-signin-heading"><?php echo $msg; ?></h4>

            <input type = "text" class = "form-control"

               name = "username" placeholder = "username = tecklearn"

               required autofocus></br>

            <input type = "password" class = "form-control"

               name = "password" placeholder = "password = 1234" required>

            <button class = "btn btn-lg btn-primary btn-block" type = "submit"

               name = "login">Login</button>

         </form>

                                             

         Click here to clean <a href = "logout.php" tite = "Logout">Session.

        

      </div>

     

   </body>

</html>

Logout.php

It will erase the session data.

<?php

   session_start();

   unset($_SESSION["username"]);

   unset($_SESSION["password"]);

  

   echo 'You have cleaned session';

   header('Refresh: 2; URL = login.php');

?>

So, this brings us to the end of blog. This Tecklearn ‘Form Handling in PHP’ blog helps you with commonly asked questions if you are looking out for a job in PHP Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

 

0 responses on "Form Handling in PHP"

Leave a Message

Your email address will not be published. Required fields are marked *