[go: up one dir, main page]

0% found this document useful (0 votes)
33 views41 pages

Hypertext Preprocessor: Government College of Engineering, Yavatmal

Jmsnsnbsjsn

Uploaded by

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

Hypertext Preprocessor: Government College of Engineering, Yavatmal

Jmsnsnbsjsn

Uploaded by

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

PHP(Hypertext Preprocessor)

A
SEMINAR
REPORT
ON
“PHP(Hypertext Preprocessor)”

Under the guidance


of PROF. S.
JUNGHARE
,PROF.R.THAKARE
&

PROF. R. DAHIWADE

DEPARTMENT OF COMPUTER ENGINEERING


GOVERNMENT COLLEGE OF
ENGINEERING, YAVATMAL
2024-2025
Computer Department GCOEY 2024-2025
PHP(Hypertext Preprocessor)

CERTIFICATE

This is to certify that the Seminar report entitled

“PHP”
is a bonafide work and it is submitted to Government College of Engineering, Yavatmal

SUBMITTED BY:

The report has been approved as it satisfies the academic requirements in respect of
seminar work prescribed the course.

Prof. S.Junghare Prof.C.V.Andhare


& (Head of the
Prof. R.Dahiwade Department)
(Seminar Guide) Department of Computer Engineering
Department of Computer Government College of Engineering,
Engineering Yavatmal
Government College of Engineering,
Yavatmal

Dr.
V.B.Waghmare
(Principal)
Government College of Engineering, Yavatmal

DEPARTMENT OF COMPUTER ENGINEERING


GOVERNMENT COLLEGE OF
Computer Department GCOEY 2024-2025
PHP(Hypertext Preprocessor)
ENGINEERING, YAVATMAL
2024-2025

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

DEPARTMENT OF COMPUTER
ENGINEERING GOVERNMENT COLLEGE OF
ENGINEERING, YAVATMAL

This is to certify that the seminar report entitled

“PHP”
SUBMITTED BY:

ROLL NO.:37,38,39,40,41,42,43,44

in the partial fulfillment for the award of B. Tech in COMPUTER


ENGINEERING. This Seminar report is reward of the work carried out
by themunder our Guidance and supervision during the year 2023-2024

PROF.
(Seminar Guide)
Department of Computer
Engineering Government College of
Engineering,
Yavatmal

Internal Examiner External Examiner

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

ACKNOWLEDGEMENT

I would like to express our deepest appreciation to all those who provided us the
possibility to complete this seminar report. A special gratitude I give to our f i r s t year
seminar mentor, Prof. Shital Gawarle, whose contribution in stimulating suggestions and
encouragement helped us to coordinate our project. He gave us support from the start to the
end of this project and kept us on the correct path.
I would like to express my special thanks to Prof. Shital Gawarle, Seminar In-
Charge of Computer Engineering and Prof. Prof.C.V.Andhare, Head of the Department,
Computer Engineering, Government College of Engineering, Yavatmal who have
invested her full effort in guiding the team in achieving the goal for all the timely support and
valuable suggestions during the period of project.
I would like to express our sincere thanks to Dr. V.B.Waghmare, Principal
of Government College of Engineering Yavatmal, for providing the Working facilities
in college.
We are equally thankful to all the staff members of Computer Engineering
Department, Government College of Engineering, Yavatmal for their valuable suggestions.
Also, I would like to thank all of my friends for the continual encouragement and the
positive support.

Place: Yavatmal
Date:

Name Of Student PRN Signature

SUHANI RAIBOLE 23010121245038


KULDEEP HIWHALE 23010121245039
SAMRUDDHI BHAMKAR 23010121245040
GAYATRI VILAYTKAR 23010121245042
VAISHNAVI SARVE 23010121245043
ANUSHRI BHANGALE 23010121245044
SAMIKSHA AWACHAR 23010121245045
ANJALI SURYAWANSHI 23010121245046

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

TABLE OF CONTENTS

Name Of Topic Roll No. Page No.

Topic 1 Introduction - 6 to 7

Topic 2 PHP basics syntax 54 8

Topic 3 Variable and constant 55 9 to 12

Topic 4 Data types 56 13 to 17

Topic 5 Operators and expressions 57 18 to 22

Topic 6 Handling html form with PHP: capturing form data 58 23 to 27

Topic 7 Dealing with multi value field 59 28 to 29

Topic 8 Redirecting of form after submission 60 30 to 32

Topic 9 PHP session 61 33 to 35

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

ABSTRACT
PHP (Hypertext Preprocessor) is a widely-used, open-source server-side scripting language designed
for web development. It is embedded into HTML code to create dynamic web pages and applications.
PHP enables developers to generate dynamic content, interact with databases, and manage session
states. As a versatile language, PHP supports various database systems, including MySQL and
PostgreSQL, and can run on multiple platforms such as Windows, Linux, and macOS. PHP has
become one of the core technologies for building interactive websites and web applications due to its
ease of integration with other technologies and frameworks.
The language's flexibility, vast community support, and rich library ecosystem make it a preferred
choice for developers creating content management systems, e-commerce platforms, and custom web
applications. PHP also features extensive security measures, though it requires best practices to
ensure secure coding and protect against vulnerabilities like SQL injection and cross-site scripting
(XSS). This abstract provides a brief overview of PHP's capabilities, its role in modern web
development, and its advantages in creating scalable and dynamic web solutions.

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Topic 1: INTRODUCTION
PHP Introduction

PHP (Hypertext Preprocessor) is a general-purpose, high-level scripting language designed for web
development. Initially created by Rasmus Lerdorf in 1994, it is now maintained by the PHP Group.
PHP was specifically developed to enhance web applications' dynamic functionality, allowing
developers to create content-rich and interactive websites. PHP is renowned for its simplicity and the
ability to integrate seamlessly with databases and other technologies.

History of PHP

PHP was created in “1994” by Rasmus Lerdorf as "Personal Home Page Tools" to track website
visits.
In 1997, Zeev Suraski and Andi Gutmans revamped it, leading to PHP 3.0, renamed "PHP: Hypertext
Preprocessor." PHP 4.0, released in **2000, introduced the Zend Engine, boosting performance.
PHP 5.0 in “2004” added advanced object-oriented programming. PHP 7.0 in
” improved speed and memory usage, while PHP 8.0 in “2020” introduced the JIT compiler for better
performance. Today, PHP powers many websites, including WordPress and Wikipedia.

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

PHP Features
PHP is very popular language because of its simplicity and open source. There are some important
features of PHP given below

Performance:
PHP script is executed much faster than those scripts which are written in other languages such as JSP
and ASP. PHP uses its own memory, so the server workload and loading time is automatically
reduced, which results in faster processing speed and better performance.
Open Source:
PHP source code and software are freely available on the web. You can develop all the versions of
PHP according to your requirement without paying any cost. All its components are free to download
and use.
Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable coding with it.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting –
PHP has predefined error reporting constants to generate an error notice or warning at runtime. E.g.,
E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language:
PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the
time of execution based on the type of data it contains on its value.
Web servers Support:
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS, etc.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to prevent
threads and malicious attacks
Control:
Different programming languages require long script or code, whereas PHP can do the same work in
a few lines of code. It has maximum control over the websites like you can make changes easily
whenever you want.
Computer Department GCOEY 2024-2025
PHP(Hypertext Preprocessor)

Topic 2: PHP basics syntax

PHP, a powerful server-side scripting language used in web development. It’s simplicity and
ease of use makes it an ideal choice for beginners and experienced developers. This article
provides an overview of PHP syntax. PHP scripts can be written anywhere in the document
within PHP tags along with normal HTML.

Basic PHP Syntax


PHP code is executed between PHP tags, allowing the integration of PHP code within HTML.
The most common PHP tag is <?php … ?>, which is used to enclose PHP code. The <?php ….?>
is called Escaping to PHP.

<?php
// code
?>
The script starts with <?php and ends with ?>. These tags are also called ‘Canonical PHP tags’.
Everything outside of a pair of opening and closing tags is ignored by the PHP parser. The open
and closing tags are called delimiters. Every PHP command ends with a semi-colon (;).

Basic Example of PHP

// Here echo command is used to print Echo


“Hello, world!”;

?>

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Topic 3: Variable and constant

TOPIC A: PHP VARIABLES

PHP Variables:
A variable in PHP is the name of the memory location that holds data. In PHP, a variable is
declared using the $ sign followed by the variable name.
PHP Variable Scope
The scope of a variable refers to where it can be accessed within the
code. PHP variables can have local, global, static, or superglobal scope
.
1. Local Scope or Local Variable
Variables declared within a function have local scope and cannot be accessed outside the
function. Any declaration of a variable outside the function with the same name (as within the
function) is a completely different variable.
Example: This example shows the local variable in PHP. PHP
php

$num = 60;

function local_var() {

// This $num is local to this function

// The variable $num outside the function


$num = 50;
echo "Variable num inside function is: $num \n";
}

local_var();

// The $num outside function is a completely


// different from inside local_var()
echo "Variable num outside function is: $num";

Output

Variable num inside function is: 50 Variable


num outside function is: 60

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

2. Global Scope or Global Variable

The variables declared outside a function are called global variables. These
variables can be accessed directly outside a function. To get access within
a function we need to use the “global” keyword before the variable to refer to the global variable.
Example: This example shows the Global Variables in PHP.
PHP
php

$num = 20;

// Function to demonstrate use of global variable


function global_var() {

// We have to use global keyword before


// the variable $num to access within
global $num;

echo "Variable num inside function: $num \n";


}

global_var();

echo "Variable num outside function: $num \n";

Output
Variable num inside function: 20 Variable
num outside function: 20
3. Static Variables
It is the characteristic of PHP to delete the variable. Once it completes its execution and the
memory is freed. But sometimes we need to store the variables even after the completion of
function execution. To do this, we use the static keywords and the variables are then called static
variables. PHP associates a data type depending on the value for the variable.
Example: This example shows the Static variable in PHP.
PHP
php

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

// Function to demonstrate static variables


function static_var() {

// Static Variable
static $num = 5;
$sum = 2;

$sum++;
$num++;

echo $num, "\n";


echo $sum, "\n";
}

// First function call


static_var();

// Second function call


static_var();

Output
6
3
7
3
4. Superglobals
Superglobals are built-in arrays in PHP that are accessible from anywhere in the script,
including within functions. Common superglobals include $_GET, $_POST,
$_SESSION, $_COOKIE, $_SERVER, and $_GLOBALS.
PHP
php

// Using $_SERVER superglobal to


// get server information
echo $_SERVER['SERVER_NAME'];

Variable
•PHP allows us to use dynamic variable names, called variable variables.
•Variable variables are simply variables whose names are dynamically created by
another variable’s value.
Example: This example shows the declaration of a variable by the use of the another variable.
PHP
php
$a = 'hello'; //hello is value of variable $a
$$a = 'World'; //$($a) is equals to $(hello)
echo $hello; //$hello is World i.e. $hello is new variable with value 'World'

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

TOPIC B: PHP CONSTANT

PHP Constant:
In PHP, constants are variables that have a fixed value and cannot be changed during the
execution of a program.

To create a constant, use the define() function.


Syntax define(name,
value); Parameters:
• name: Specifies the name of the constant
• value: Specifies the value of the constant
Example

Get your own PHP Server


Create a constant with a case-sensitive name:
define("GREETING", "Welcome to W3Schools.com!"); echo
GREETING
PHP const Keyword
You can also create a constant by using the const keyword.

Example
Create a case-sensitive constant with the const keyword:
const MYCAR = "Volvo";
echo MYCAR;
PHP Constant Arrays
From PHP7, you can create an Array constant using the define() function.
Example
Create an Array constant:
define("cars", [
"Alfa Romeo",
"BMW",
"Toyota"
]);
echo cars[0]; Constants
are Global
Constants are automatically global and can be used across the entire script.
Example
This example uses a constant inside a function, even if it is defined outside the function:
define("GREETING", "Welcome to W3Schools.com!");

function myTest() {
echo GREETING; }
myTest();

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Topic 4: Data types


In PHP, the data type determines the kind of data a variable can hold. PHP is a loosely typed
language, so you don’t need to declare the type of a variable explicitly. PHP automatically
determines the data type based on the value assigned to the variable.

1. Scalar Data Types


These are the simplest types of data.

A. String

Used to store sequences of characters.

Strings can be enclosed in:

• Single quotes (‘ ‘): No variable parsing, raw text.


• Double quotes (“ “): Allows variable interpolation and escape sequences.
• Example:

$single = ‘Hello, World!’;

$double = “Hello, $single”;

Echo $double; // Output: Hello, Hello, World!

Integer

Represents whole numbers without decimal points.

Must be in the range -2,147,483,648 to 2,147,483,647 on 32-bit systems (or larger


on 64-bit systems).

Can be in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).

Example:
$decimal = 42;

$hex = 0x2A; // Hexadecimal

$octal = 052; // Octal

$binary = 0b101010; // Binary


Echo $decimal; // Output: 42

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

B. Float

Represents numbers with decimal points or numbers in exponential form.

Precision depends on the system, usually 14 decimal digits.

Example:

$pi = 3.14159;

$scientific = 2.5e3; // 2.5 x 10^3


Echo $scientific; // Output: 2500 C.
Boolean
Represents true or false values. Typically
used for conditional testing. Example:
$isLoggedIn = true; If
($isLoggedIn) {
Echo “User is logged in.”;

1. Compound Data Types


A. Array
Stores multiple values in a single variable.

Can be indexed or associative.

• Example:

Indexed Array:

$fruits = [“apple”, “banana”, “cherry”];

Echo $fruits[1]; // Output: banana

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Associative Array:

$ages = [“John” => 30, “Jane” => 25]; Echo


$ages[“Jane”]; // Output: 25 Object
Represents an instance of a class (used in object-oriented programming).

Allows defining properties and methods.

• Example:

Class Car {

Public $brand;

Public function setBrand($brand) {

$this->brand = $brand;

$car = new Car();

$car->setBrand(“Toyota”);

Echo $car->brand; // Output: Toyota

1. Special Data Types


A. NULL
Represents a variable with no value.
variable is NULL if:

• It’s explicitly assigned NULL.


• It’s declared but not assigned.
• It’s been unset.
• Example:

$var = NULL;

Var_dump($var); // Output: NULL

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Resource

Refers to external resources, such as file handles, database connections, or


network sockets.

Special type used for working with external resources.

• Example:

$file = fopen(“example.txt”, “r”);


Var_dump($file); // Output: resource

Reporting Data Types

PHP offers functions to check and report data types:

a. Gettype()

Returns the type of a variable as a string.

$var = “Hello”;

Echo gettype($var); // Output: string

a. Var_dump()

Outputs the type and value of a variable.


Useful for debugging.
$var = 42;

Var_dump($var); // Output: int(42)

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

a. Is_*() Functions

These functions check if a variable is of a specific type. Common ones include:

• Is_int()
• Is_string()
• Is_array()
• Is_null()
• Is_bool()

• Example:

$var = 3.14;

If (is_float($var)) {

Echo “This is a float.”;

Type Casting

PHP allows explicit type conversion using type casting.

• Example:

$var = “10”;

$intVar = (int)$var; // Convert to integer

Echo $intVar; // Output: 10

Dynamic Typing in PHP

PHP is dynamically typed, meaning variables do not have fixed types. The type is determined
by the value assigned.

• Example:

$var = “Hello”; // String

$var = 42; // Now it’s an integer

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Topic 5: Operators and expressions

What is operators?
Operators are used to performing operations on some values. In other words, we can describe
operators as something that takes some values, performs some operation on them, and gives a
result.
1.ARITHMETIC OPERATORS
In PHP, arithmetic operators are used to perform mathematical operations on numeric
values.
OPERATOR NAME EXAMPLE OPERATION
+ Addition $x + $y Sum the product
- Subtraction $x - $y Differences the operands
* Multiplication $x * $y Product of the operands
/ Division $x / $y The quotient of the operand
** Exponentiation $x ** $y $x raised to the power $y
Modulus $x % $y The remainder of the operands
%

2.COMPARISON OPERATORS
Comparison operators are used to compare two values in a Boolean fashion.

OPERATOR NAME EXAMPLE OPERATION


== Equal to $x == $y Checks if two values are equal
!== Not equal to $x !== $y Checks if two values are not equal.
=== Identical to $x === $y Checks if two values are equal and of
the same type.

> Greater than $x > $y Checks if the left operand is greater


than the right.
< Less than $x < $y Checks if the left operand is less than
the right.
>= Greater than or $x >= $y Checks if the left operand is greater
equal to than or equal to the right.

<= Less than or $x <= $y Checks if the left operand is less than
equal to or equal to the right.

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

3.LOGICAL OPERATORS
They are basically used to operate with conditional statements and expressions.
Conditional statements are based on conditions

OPERATOR NAME EXAMPLE OPERATION


&& AND $x && $y Returns true if both conditions are
true.
|| OR $x || $y Returns true if at least one
condition is true.
! NOT Returns true if the condition is
$x ! $y false, and false if the condition is
true.

4.ARRAY OPERATORS
These operators are used in the case of arrays

OPERATOR NAME EXAMPLE OPERATION


+ union Combines two arrays. If they have
the same keys, the second array
overwrites the first array's value.
== Equality $x == $y Returns true if two arrays have the
same key-value pairs, but the order of
the elements does not matter.

!= Inequality $x != $y Returns True if both are unequal


=== Identity $x === $y Returns True if both have the same
key-value pair in the same order and
of the same type
!== Non-Identity $x !== $y Returns True if both are not identical
to each other
<> Inequality $x <> $y Returns True if both are unequal

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

5.STRING OPERATORS
This operator is used for the concatenation of 2 or more strings using the concatenation operator
(‘.’). We can also use the concatenating assignment operator (‘.=’) to append the argument on the
right side to the argument on the left side.

OPERATOR NAME EXAMPLE OPERATION


. Concatenation $x.$y It joins two string operands
(characters of right hand string
appended to left hand string)
and returns a new string.
.= Concatenation and $x.=$y First concatenate $x and $y,
assignment then assign the concatenated
string to $x, e.g. $x = $x . $y

6.BITWISE OPERATORS

The bitwise operators are used to perform bit-level operations on operands. These operators allow the
evaluation and manipulation of specific bits within the integer.

OPERATOR NAME EXAMPLE OPERATION


& And $x & $y Bits that are 1 in both $x
and $y are set to 1,
otherwise 0.
| Or (Inclusive or) $x | $y Bits that are 1 in either $x
or $y are set to 1
^ Xor (Exclusive or) Bits that are 1 in either $x
$x ^ $y or $y are set to 0.
~ Not ~ $y Bits that are 1 set to 0 and
bits that are 0 are set to 1
<< Shift left $x << $y Left shift the bits of
operand $x $y steps
>> Shift right $x >> $y Right shift the bits of $x
operand by $y number of
places

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)
• REGULAR EXPRESSION:

• A regular expression is a sequence of characters that forms a search pattern. When you
search for data in a text, you can use this search pattern to describe what you are
searching for.
• 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 = "/helloworld/i";

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

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

1.Regular Expression Functions:

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Topic 6: Handling html form with php: capturing form data

Capturing form data is a fundamental aspect of web development, enabling


interaction between users and the server.
HTML forms allow users to input data and submit it to the server for processing. PHP is
commonly used to capture, validate, and manipulate this data. Capturing data correctly ensures
the integrity of applications and prevents potential vulnerabilities.

1.Capturing Form Data with PHP

HTML Form Example

Here is a simple HTML form for user registration:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8”>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>
<title>Form Example</title>
</head>
<body>
<form action=”capture_form_data.php” method=”post”>
<label for=”username”>Username:</label>
<input type=”text” id=”username” name=”username” required><br><br>
<label for=”email”>Email:</label>
<input type=”email” id=”email” name=”email” required><br><br>
<label for=”password”>Password:</label>
<input type=”password” id=”password” name=”password” required><br><br>
<button type=”submit”>Register</button>
</form>
</body>
</html>

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Capturing Form Data in PHP


The PHP script to handle the submitted data:

<?php
// Check if the form was submitted
If ($_SERVER[“REQUEST_METHOD”] === “POST”) {
// Capture form data
$username = $_POST[‘username’];
$email = $_POST[‘email’];
$password = $_POST[‘password’];

// Display captured data (for demonstration purposes)


Echo “Username: “ . htmlspecialchars($username) . “<br>”;
Echo “Email: “ . htmlspecialchars($email) . “<br>”;
Echo “Password: “ . htmlspecialchars($password) . “<br>”;
}
?>

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)
<?

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

1. Explanation of Key Elements

1. HTTP Methods:

POST: Sends data securely in the request body.

GET: Appends data to the URL (less secure and limited in size).

1. Global Variables:

$_POST: Captures form data submitted using the POST method.

$_GET: Captures data submitted using the GET method.

1. Input Validation: Use htmlspecialchars() to escape special characters, preventing


XSS attacks.

1. Example: Using GET Method: Modify the form to use method=”get”, and access data via
$_GET:

$username = $_GET[‘username’];

$email = $_GET[‘email’];

1. Validating and Sanitizing Input

Validation

Validate the captured data to ensure correctness.

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

If (empty($username)) {
Die(“Username is required.”);
}

If (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
Die(“Invalid email address.”);
}

2.Sanitization
Sanitize data to remove unwanted characters.

$username = filter_var($username, FILTER_SANITIZE_STRING);


$email = filter_var($email, FILTER_SANITIZE_EMAIL);

1. Best Practices for Capturing Form Data

1. Use Prepared Statements: When storing data in a database, use prepared statements
to prevent SQL injection.

$stmt = $pdo->prepare(“INSERT INTO users (username, email, password)


VALUES (?, ?, ?)”);

$stmt->execute([$username, $email, password_hash($password,


PASSWORD_BCRYPT)]);

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

2. Input Length Limits: Enforce length limits in both the form and server-side validation.

If (strlen($username) > 50) {

Die(“Username cannot exceed 50 characters.”);

3. Secure Passwords: Hash passwords before storing them.

$hashedPassword = password_hash($password, PASSWORD_BCRYPT);

4. Error Handling: Provide user-friendly error messages to guide users in correcting


their inputs.

5. CSRF Protection: Add a CSRF token to the form to prevent Cross-Site Request
Forgery attacks.

<input type=”hidden” name=”csrf_token” value=”<?= $_SESSION[‘csrf_token’]


?>”>

Capturing HTML form data using PHP is a straightforward process, but ensuring data validity
and security is critical. By combining proper input validation, sanitization, and secure coding
practices, developers can build robust web applications that safely handle user input.

This foundational knowledge can be extended to advanced use cases like file uploads, session
handling, and AJAX-based forms.

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Topic 7: Dealing with multi value field

Dealing with Multi-Value Fields in PHP


Handling multi-value fields in PHP is essential when working with grouped data such as lists,
arrays, or JSON objects. These fields frequently appear in scenarios like form submissions, API
data handling, or complex database interactions. PHP provides robust tools such as arrays, loops,
and JSON manipulation functions to simplify and manage these tasks effectively.

What are Multi-Value Fields?


Multi-value fields are variables or storage structures that can hold multiple related values.
Instead of creating separate fields for each value, multi-value fields allow you to store and
manage grouped data compactly and efficiently.
Common Examples:
Form Inputs:
Checkboxes or multiple-select dropdowns storing multiple selected values.
API Responses:
JSON data containing arrays or lists of objects.
Shopping Carts:
Lists of items and their attributes like quantity and price.
Tags:
Associating a blog post with multiple categories or keywords.

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Working with Multi-Value Fields


Accessing Values:Values in arrays can be accessed using their keys (associative arrays) or
indexes
(indexed arrays).
Example:
phpCopy code$skills = ["PHP", "JavaScript", "Python"];echo $skills[0]; // Outputs: PHP
b) Iterating Through Multi-Value Fields
Loops are essential for processing multi-value fields.
Using foreach:
phpCopy codeforeach ($skills as $skill)
{
echo $skill . "<br>";
}
Using for:
phpCopy codefor ($i = 0; $i < count($skills); $i++){ echo
$skills[$i] . "<br>";
}

Common Methods for Storing Multi-Value


FieldsFlat Storage (Comma-Separated Values):Stores multiple values as a single string with a
delimiter (e.g., "red,green,blue").
JSON Storage:Uses JSON-encoded strings to represent structured data (e.g., arrays).
Relational Tables (Normalization):Stores multi-value data across multiple rows in a
separate table, linking it to the original record

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Topic 8: Redirecting of form after submission

Redirecting a user after form submission is a common practice in web development. It ensures
better user experience by preventing duplicate submissions caused by browser refreshes and
allows the developer to guide users to specific pages, such as a thank-you page or a confirmation
screen.

Why Redirect After Form Submission?

1. Prevent Duplicate Submissions:


If a user refreshes the page, the form may resubmit. A redirect avoids this by sending
the user to a new page.

2. Improve User Exeperince:


a. Redirecting can inform users that their submission was successful, often leading to more
polished flow.

3 .Separate Logic and UI:


Redirects help in separating the processing logic from the user interface,
maintaining
clean code structure.

Implementation in PHP

PHP provides several methods to redirect users. The most common way is using the header()
function.

Example 1: Basic Redirect

If ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
// Process the form data
$name = $_POST[‘name’];
$email = $_POST[‘email’];

// Save to database or perform other actions

// Redirect after successful submission Header(‘Location:


thank_you.php’);
Exit; // Ensure no further code is executed
}

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Example 2: Redirect with Query Parameters


Sometimes, it is useful to pass information via URL parameters.

If ($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
// Process the form data
$success = true;

// Redirect with query parameters


Header(‘Location: thank_you.php?success=’ . $success); Exit;
}

In this example, a success message can be displayed on the redirected page based on the query
parameter.

Example 3: Redirecting Back to the Form with Error Messages

If validation fails, redirect the user back to the form with error messages. If

($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
$errors = [];

// Validate input
If (empty($_POST[‘name’])) {
$errors[] = ‘Name is required’;
}

If (!empty($errors)) {
// Redirect back to the form with errors
$query = http_build_query([‘errors’ => $errors]);
Header(‘Location: form.php?’ . $query);
Exit;
}

// Process form and redirect to thank you page


Header(‘Location: thank_you.php’);
Exit;
}

Note: Error messages can be retrieved using $_GET[‘errors’] on the form page.

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Common Issues and Solutions

1. Headers Already Sent Error:


Ensure no output (like HTML or echo) occurs before calling header(). Use ob_start()
and ob_end_clean() if needed.

2. Redirect Fails in Some Browsers:

Use HTTP response status code 302 explicitly if necessary.


Header(‘Location: thank_you.php’, true, 302);
Exit;

3. Security Concerns:

Always sanitize input to prevent security risks like XSS or SQL injection. Use HTTPS

for secure data transmission.

Alternatives to PHP Redirects

4. JavaScript Redirects:

<script>
Window.location.href = ‘thank_you.php’;
</script>

However, these rely on client-side scripts and are not ideal for critical redirects.

5. Meta Tag Redirects:

<meta http-equiv=”refresh” content=”0;url=thank_you.php”> This is less

secure and should be avoided for sensitive operations.

Redirecting users after form submission in PHP ensures a smooth user experience and protects
against duplicate submissions. By leveraging the header() function and properly handling
validation and errors, developers can build robust and user- friendly web applications.

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Topic 9: PHP session

PHP sessions are a way to store data across multiple pages during a user's visit to a
website. Sessions allow you to maintain state and store user-specific information, such as
login credentials, preferences, or shopping cart contents, without relying on cookies or
URL parameters.

How Sessions Work


Session Start:
When a session is initiated, PHP generates a unique session ID for the user. This ID is
typically stored in a cookie on the user's browser or passed via URL parameters.
Session Data Storage:
Data can be stored in the $_SESSION superglobal array, which is accessible across
different pages during the session.
Session End:
Sessions can be ended by either closing the browser, explicitly calling the
session_destroy() function, or after a specified timeout period.

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

Basic Session Usage


1. Starting a Session
To start a session, you need to call the session_start() function at the beginning of your script.
This function must be called before any output is sent to the browser.

2. Storing Session Variables


You can store data in the $_SESSION superglobal array.

3. Accessing Session Variables


You can access the session variables on any page where the session is started.

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

4. Modifying Session Variables


You can modify session variables just like any other variable

5. Unsetting Session Variables


To remove a specific session variable, you can use the unset() function

6. Destroying a Session
To completely destroy a session and remove all session data, use the
session_destroy() function. This is usually done when a user logs out.

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

CONCLUSION

In summary, we have covered the essential aspects of PHP that form the backbone of
dynamic web development. We started with an introduction to PHP, then explored its
basic syntax, variables, and constants, which are fundamental for data manipulation. We
examined various data types and the use of operators and expressions for performing
operations on data.

We also learned how to handle HTML forms in PHP, capturing user input and managing
multi-value fields effectively. Redirecting users after form submission enhances user
experience, and PHP sessions allow us to maintain user state across different pages.

By understanding these core concepts, you are equipped to build dynamic and interactive
web applications. As you progress, delving into more advanced topics will further
enhance your PHP skills and enable you to create sophisticated web solutions.

Computer Department GCOEY 2024-2025


PHP(Hypertext Preprocessor)

REFERENCE

1. www.google.com
2. https://www.w3schools.com/php/default.asp
3. www.chatgpt.com
4. https://www.php.net/
5. https://www.geeksforgeeks.org/php
6. https://www.w3schools.com/PHP
7. https://www.javatpoint.com
8. https://blog.hubspot.com/website/php-array-functions
9. https://corporatefinanceinstitute.com/resources/data-science/.
10. https://www.tutorialspoint.com/php/index.htm

Computer Department GCOEY 2024-2025

You might also like