0% found this document useful (0 votes)
8 views

Chapter 2 - PHP Forms

Chapter Two covers PHP forms, detailing how to send form data using HTML and PHP. It explains the importance of the action and method attributes in forms, how to handle data with PHP superglobals $_GET and $_POST, and emphasizes the need for form validation to ensure data integrity. The chapter also introduces regular expressions for pattern matching and validation in PHP.

Uploaded by

beshahh21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Chapter 2 - PHP Forms

Chapter Two covers PHP forms, detailing how to send form data using HTML and PHP. It explains the importance of the action and method attributes in forms, how to handle data with PHP superglobals $_GET and $_POST, and emphasizes the need for form validation to ensure data integrity. The chapter also introduces regular expressions for pattern matching and validation in PHP.

Uploaded by

beshahh21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Chapter Two

PHP Forms
Sending form data
⚫ An HTML form on a web page is nothing more than a

convenient user-friendly way to configure an HTTP request


to send data to a server.

⚫ This enables the user to provide information to be

delivered in the HTTP request.

⚫ The <form> element defines how the data will be sent.

⚫ All of the <form> attributes are designed to let you


configure the request to be sent when the form is submitted.
⚫ The action and method attributes are the most important
as they define where to send the data and how to send it.
The action attribute
⚫ The action attribute defines where the data gets sent.
⚫ Its value must be a valid relative or absolute URL.
⚫ Example, the data is sent to an absolute URL:
https://example.com
⚫ <form action="https://example.com">…</form>
⚫ Example, a relative URL where the data is sent to a
different URL on the same origin
⚫ <form action="/somewhere_else">…</form>
⚫ If the action attribute isn't provided, the data will be sent
to the URL of the page containing the form, which is the
current page.
The action attribute cont’d
⚫ The action value should be a file on the server that can
handle the incoming data, including ensuring server-side
validation.
⚫ The server then responds, generally handling the data and
loading the URL defined by the action attribute, causing a
new page load
⚫ or a refresh of the existing page, if the action points to the
same page
⚫ The method attribute is what determines how the data is sent
The method attribute
⚫ Despite the HTTP protocol offering various request
methods such as GET, POST, PUT, DELETE, and PATCH,
⚫ HTML forms are designed to support only GET and POST.
⚫ This limitation comes from the original purpose of HTML
forms, which was to facilitate simple data submission and
retrieval in web applications.
⚫ An example HTTP request
PHP Form Handling
⚫ PHP can handle data submitted through HTML forms
⚫ PHP uses the superglobals $_GET and $_POST to collect
form-data
⚫ Some predefined variables in PHP are "superglobals", which
means that they are always accessible, regardless of scope
⚫ $_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.
Example
PHP $_POST
⚫ $_POST contains an array of variables received via the
HTTP POST method.
⚫ There are two main ways to send variables via the HTTP
Post method:
⚫ HTML forms
⚫ JavaScript HTTP requests
⚫ A HTML form submits information via the HTTP POST
method if the form's method attribute is set to "POST“
⚫ When a user clicks the submit button, the form data is sent
to a PHP file specified in the action attribute of the <form>
tag.
⚫ In the action file we can use the $_POST variable to collect
the value of the input field.
$_POST in JavaScript HTTP Requests
PHP $_GET
⚫ $_GET contains an array of variables received via the
HTTP GET method.
⚫ There are two main ways to send variables via the HTTP
GET method:
⚫ Query strings in the URL
⚫ HTML Forms
⚫ A query string is data added at the end of a URL.
⚫ Example,
⚫ <a href="demo.php?subject=PHP&web=W3schools.com">Test
$GET</a>
⚫ everything after the ? sign is part of the query
⚫ In the PHP file we can use the $_GET variable to collect
the value of the query string
⚫ Echo $_GET['subject'] ;
$_GET in HTML Forms
⚫ A HTML form submits information via the HTTP GET
method if the form's method attribute is set to "GET".
Handling Different Input Types
⚫ Dropdown Selection using <select>
Handling Different Input Types
⚫ Checkboxes (Multiple Selections)
Takeaway questions
1. Create a form that accepts a name and displays
"Welcome, [Name]!" after submission.
2. Create a form with a dropdown list of three
programming languages. When the user submits the
form, display the selected language.
Handling Different Input Types
⚫ Radio Buttons (Single Selection)
Takeaway questions
1. Create a form with three checkbox options (HTML, CSS,
PHP). Display the selected options after submission.
2. Create a simple login form with username and password
fields. Validate that both fields are longer than 5
characters
3. Build a contact form that takes name, email, phone
number and message. Please check if the required fields
are filled using php. below is the screenshot of the work
you need to do.
⚫ The code should be one single contact.php file.
PHP Form Validation

⚫ Form validation is a crucial step that needs to be


completed before submitting data to the database.
⚫ This process is performed to prevent any errors or faulty
data from being inserted into the database.
⚫ The HTML form includes various input fields such as
email, text, checkbox, radio button, etc.
⚫ These input fields must be validated to ensure that the
user enters only the intended values and not incorrect
ones.
String Validation
⚫ String validation is the process of checking whether a
given string (a sequence of characters) meets specific
rules or criteria.
⚫ These rules can include format, length, allowed
characters, and patterns.
⚫ Common Use Cases for String Validation:
⚫ User Input Validation – Ensure fields like names,
emails, and phone numbers follow the correct format.
⚫ Security – Prevent malicious input such as SQL
injection and cross-site scripting (XSS).
⚫ Data Integrity – Ensure consistency and correctness in
databases (e.g., validating dates, IDs).
⚫ Form Submission – Validate fields before allowing a
user to submit a form.
⚫ System Integration – Ensure incoming data from
Empty Field Validation

⚫ This is used to check if user has added any data in the


required input field. Here, empty() is used to check if a
variable is empty or not.
if (empty($_POST["UserName"]))
{
$errorMsg = "User Name is required";
}
else
{
$userName = input_data($_POST["UserName"]);
}
String Matching
⚫ This is used to check if user has added valid string in the
required input field. Here, preg_match() is used for
pattern matching.

$userName = $_POST["userName"];

if (!preg_match("/^[a-zA-Z0-9_]*$/", $userName))
{
$errorMsg = "Only alphabets, numbers, and underscores are
allowed for User Name";
}
Else
{
echo $userName;
}
Number Validation
• Number validation in an HTML form ensures that users enter valid
numeric input in a form field.
• HTML provides built-in attributes and methods to validate numbers
without
Attributerequiring JavaScript.
Description Example
min Minimum value allowed. <input type="number" min="1">
max Maximum value allowed. <input type="number" max="100">
Defines the interval between
step <input type="number" step="5">
valid values.
Ensures the field is
required <input type="number" required>
mandatory.
value Sets a default number. <input type="number" value="10">
Defines a custom regex
<input type="text" pattern="[0-9]+"
pattern pattern (for <input
required>
type="text">).
Number Validation
⚫ The following example checks whether the user has
added only numbers in the required input field.

$age = $_POST["age"];

if (!preg_match("/^[0-9]*$/", $age))
{
$errorMsg = "Only numeric values are allowed!!";
}
Else
{
echo $age;
}
Email Validation
⚫ This is used to check if user has added a valid email in the
required input field.
$emailID = $_POST["emailID"];

$pattern =
"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})
$^";
if (!preg_match($pattern, $emailID) )
{
$errorMsg = "Invalid Email ID format";
}
Else
{
echo $emailID;
}
Count Length
⚫ This is used to check if the length of the string is in valid range.
Here, strlen() is used to find the length of the string.

$phoneNo = $_POST["phoneNo"];

if (strlen($phoneNo) != 10)
{
$errorMsg = "Please provide a phone number of 10 digits!!";
}
Else
{
echo $phoneNo;
}
URL Validation
⚫ This is used to check if user has added a valid URL in the required input
field.

$url = $_POST["url"];
$pattern =
"/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i"
if (!preg_match($pattern, $url))
{
$errorMsg = "You entered an INVALID URL";
}
else
{
echo $url;
}
Sending Values to a Script Manually
⚫ There are two different ways you can pass variables and
values to a PHP script, both worth knowing.
⚫ The first is to make use of HTML's hidden input type:

<input type="hidden" name="name"


value="Brian” />

⚫ The second method is to append a value to the PHP script's


URL:

www.dmcinsights.com/page.php?name=Brian
PHP Regular Expressions

⚫ A regular expression is a sequence of characters that forms a search


pattern.
⚫ A regular expression can be a single character, or a more complicated
pattern.
⚫ Regular expressions can be used to perform all types of text search
and text replace operations.
Syntax:
$exp = "/win/i";
Regular Expression Functions

⚫ The most common expression functions are

Function Description
preg_match() Returns 1 if the pattern was found in the string
and 0 if not
preg_match_all() Returns the number of times the pattern was
found in the string, which may also be 0

preg_replace() Returns a new string where matched patterns


have been replaced with another string
Using preg_match() Using preg_match_all()

$str = "Don’t trouble trouble unless it


$str = "Visit LinkedIn";
troubles you ";
$pattern = "/LinkedIn/i";
$pattern = "/rou/i";
echo preg_match($pattern,
$str);
echo preg_match_all($pattern, $str);

Using preg_replace()

$str = "Visit LinkedIn!";


$pattern = "/LinkedIn/i";
echo preg_replace($pattern, “Instagram", $str);
Regular Expression Modifiers
Modifier Description

i Performs a case-insensitive search

m Performs a multiline search (patterns that search


for a match at the beginning or end of a string will
now match the beginning or end of each line)
u Enables correct matching of UTF-8 encoded
patterns
Regular Expression Patterns

Expression Description
[abc] Find one or many of the characters inside the
brackets
[^abc] Find any character NOT between the brackets
[a-z] Find any character alphabetically between two
letters
[A-z] Find any character alphabetically between a
specified upper-case letter and a specified
lower-case letter
[A-Z] Find any character alphabetically between two
upper-case letters.
[123] Find one or many of the digits inside the brackets
Metacharacters
Metacharacter Description
| Find a match for any one of the patterns separated by | as
in: cat|dog|fish
. Find any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find any digits
\D Find any non-digits
\s Find any whitespace character
\S Find any non-whitespace character
\w Find any alphabetical letter (a to Z) and digit (0 to 9)
\W Find any non-alphabetical and non-digit character
\b Find a match at the beginning of a word like this: \bWORD,
or at the end of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal
number xxxx
Quantifiers
Quantifier Description
n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more


occurrences of n
n? Matches any string that contains zero or one
occurrences of n
n{3} Matches any string that contains a sequence
of 3 n's
n{2, 5} Matches any string that contains a sequence of at
least 2, but not more that 5 n's
n{3,} Matches any string that contains a sequence of at
least 3 n's
Takeaway Questions
1. Write a PHP script that checks if a string contains
another string.

2. Write a PHP script that removes the last word from


a string.

Sample string : 'The quick brown fox‘

Expected Output : The quick brown


3. Write a PHP script that removes the whitespaces
from a string.

Sample string : 'The quick " " brown fox'


Expected Output : Thequick""brownfox
End of Chapter 2

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy