Course Reference Material
Course Reference Material
Course Content
Course Code
Course Title Web Programming-II
Course Credit and Hours 4 Credits - 4 hrs/wk
Facilitator Dr.Ripal Ranpara
Table of Contents
Topic 1: Web Development Overview ....................................................................................................... 1
Topic 2: Introduction to Webpage | Website | Difference Between Static and Dynamic Website .......... 2
Topic 3: Programming Language and Scripting Language ......................................................................... 4
Topic 4: Client-Side vs. Server-Side ............................................................................................................ 5
Topic 5: History and Purpose of php .......................................................................................................... 5
Topic 6: Introduction to php ...................................................................................................................... 6
Topic 7: Introduction to Web servers | XAMPP |LAMPP | Php.ini............................................................ 8
Topic 8: Web Hosting: ................................................................................................................................ 8
Topic 9: HTTP / HTTPS ................................................................................................................................ 9
Topic 10: Writing and Executing Your First PHP Script .............................................................................. 9
Topic 11: Structure of Php Script ............................................................................................................. 11
Topic 12: Comments in php ..................................................................................................................... 11
Topic 13: Variables in php ........................................................................................................................ 13
Topic 14: Operators in php ...................................................................................................................... 17
Topic 15: Difference Between echo and Print ......................................................................................... 23
Topic 16: Constants .................................................................................................................................. 24
Topic 17: Conditional Statements ............................................................................................................ 26
Topic 18: Looping Structures ................................................................................................................... 28
Topic 19: Functions .................................................................................................................................. 31
Topic 20: Expression ................................................................................................................................ 35
Topic 21: Variable Scope .......................................................................................................................... 37
Topic 22: Arrays ....................................................................................................................................... 40
Topic 23: Form Submission with GET | POST | REQUEST ........................................................................ 46
Topic 24: File Uploading ........................................................................................................................... 47
Topic 25: File Handling ............................................................................................................................. 48
Topic 26: Cookies ..................................................................................................................................... 50
Topic 27: Session ...................................................................................................................................... 50
Topic 28: Regular Expression ................................................................................................................... 52
Topic 29: MySQL ...................................................................................................................................... 54
Topic 30: MySQL Php Functions............................................................................................................... 55
Topic 31: CRUD OPERATION in php ......................................................................................................... 59
Front-End Development
• Involves creating the user interface that users interact with directly.
• It includes designing layouts, user experience, and visual elements.
• Technologies used: HTML (structure), CSS (styling), JavaScript (interactivity).
• Focuses on ensuring responsiveness and compatibility across different devices and screen
sizes.
Back-End Development
• Handles server-side logic and data management.
• It involves processing data, interacting with databases, and performing server-related tasks.
• Technologies used: Scripting languages (e.g., PHP, Python, Ruby), databases (e.g., MySQL,
PostgreSQL), server management tools.
Technology Stack
• A web development technology stack is a combination of tools, languages, and frameworks
used to build a web application.
• Front-End Stack: HTML, CSS, JavaScript; libraries and frameworks like React, Angular, Vue.
• Back-End Stack: Scripting languages (e.g., PHP, Python, Ruby), databases (e.g., MySQL,
PostgreSQL), server frameworks (e.g., Express, Django, Ruby on Rails).
Introduction to Webpage
A webpage is a single document or resource on the World Wide Web that can be accessed
through a web browser. It is typically composed of various elements, including text, images,
hyperlinks, multimedia, and styling through HTML (Hypertext Markup Language), CSS
(Cascading Style Sheets), and sometimes JavaScript. Webpages are the building blocks of
websites and serve as the content that users interact with on the internet.
Introduction to Website
A website is a collection of related webpages that are typically identified by a common domain
name and are accessible on the internet. Websites serve various purposes, such as providing
information, facilitating communication, conducting e-commerce, or offering interactive
services. Websites are hosted on web servers and can be accessed by users worldwide through
their web browsers.
Static Website: A static website consists of fixed, unchanging content. The content is directly
coded into HTML files, and each page represents a separate HTML document. Static websites
are easy to create and host but are limited in terms of interactivity and customization for users.
Dynamic Website: A dynamic website, on the other hand, generates content on-the-fly, often
using server-side scripting languages like PHP, Python, or Ruby. Dynamic websites can pull
information from databases, respond to user inputs, and adapt content based on various
factors. They are more complex to develop but offer greater interactivity and personalization.
Programming Language
A programming language is like a special set of instructions that people use to tell
computers what to do. It's a bit like giving really clear and specific directions to a robot.
This language lets you create all sorts of things, from fun games to helpful apps and even
big software programs. People write code using this language, and computers read and
follow that code to do what we want them to do. It's a bit like using magic words that
computers understand to make them work the way we want!
Scripting Language
A scripting language is like a helper language for computers. It's used to create short and
simple sets of instructions that make tasks easier. Imagine if you had a helper who could
quickly organize your toys or sort your books – that's what a scripting language does for
computers! It's not for making big programs, but rather for doing small jobs quickly. People
write these short instructions, and the computer follows them step by step, just like a
helpful friend.
History
• Creation: PHP was created by Rasmus Lerdorf in 1994. Originally, it was a set of tools for
tracking visits to his online resume.
• Hypertext Preprocessor: In 1995, he added the ability to create dynamic web pages, and
PHP (Personal Home Page) gained the full form "Hypertext Preprocessor."
• Version Progression: Over the years, PHP went through different versions, with PHP 3
introducing the first official version, and PHP 4 bringing significant improvements in
performance and functionality.
• Zend Engine: In 1999, PHP 4 introduced the Zend Engine, which boosted performance and
became the foundation for future versions.
Purpose
Introduction
PHP (Hypertext Preprocessor) is a scripting language primarily used for server-side web
development. It allows developers to embed dynamic and interactive functionality within HTML
pages. PHP executes on the web server, generating dynamic content that can change based on
user input, database interactions, and other conditions. It's open-source, widely used, and a
fundamental component in creating dynamic web applications and websites.
What is PHP?
PHP stands for Hypertext Preprocessor. It's a scripting language used for web development to
create dynamic and interactive web pages.
Server-Side Scripting:
Facilitator: Dr. Ripal Ranpara, Atmiya University 6|Page
Course Name: Web development using PHP
Course Content
Unit-1
PHP is mainly used for server-side scripting. This means the PHP code is executed on the web
server before the webpage is sent to the client's browser.
Embedding PHP in HTML:
PHP code is embedded within HTML using special tags: <?php and ?>.
This allows mixing PHP code with HTML content seamlessly in a single file.
Dynamic Web Pages:
PHP allows you to create web pages that can change content and behavior based on user
interactions, database queries, and other factors.
What PHP Can Do:
• Generate dynamic content, like personalized greetings or real-time data.
• Collect form data and process user inputs.
• Interact with databases to store and retrieve information.
• Create user authentication systems for secure access.
• Generate and manipulate images, files, and documents.
Popular CMS and Frameworks:
PHP powers popular content management systems (CMS) like WordPress, Joomla, and
Drupal.It's also the backbone of various frameworks like Laravel, Symfony, and CodeIgniter that
simplify web application development.
Open Source:
PHP is open-source and has a large community of developers contributing to its growth and
improvement.
Its accessibility and community support make it a versatile choice for developers.
Compatibility:
PHP is compatible with various web servers (like Apache, Nginx) and databases (like MySQL,
PostgreSQL).It can run on different operating systems, including Windows, Linux, and macOS.
Learning Curve:
PHP has a relatively gentle learning curve, making it a good choice for beginners in web
development.
The wealth of online resources and tutorials makes it easy to find help when learning.
Getting Started:
To start using PHP, you need a web server (like XAMPP, WAMP) and a text editor or integrated
development environment (IDE) for writing PHP code.
You write PHP scripts in .php files and access them through web browsers.
A web server is software or hardware that serves as a platform for hosting, processing, and
delivering web content to users over the internet. It handles incoming requests from client
devices, such as web browsers, and responds by providing the requested resources, which are
typically web pages, images, stylesheets, scripts, or other multimedia content.
Apache: Apache is one of the most popular open-source web server software. It's highly
configurable and works on various operating systems. Apache is responsible for handling
incoming HTTP requests and serving web pages to users' browsers. It supports various modules
that can be used to extend its functionality.
XAMPP: X – Cross platform | A – APACHE | M – MYSQL | P – PHP | P – PERL
WAMP: W – Windows| A – APACHE | M – MYSQL | P – PHP
W=LAMP: W – Linux| A – APACHE | M – MYSQL | P – PHP
Web hosting refers to the service that allows individuals and organizations to make their
websites or web applications accessible on the internet. Web hosting providers offer the
technology and infrastructure needed to store and deliver website content to users. Hosting
involves storing website files, databases, and other resources on servers that are connected to
the internet.
Key Points:
• Server Storage: Web hosting providers allocate space on servers to store website files,
databases, and other related content.
• Connectivity: These servers are connected to the internet, enabling users to access the
hosted websites from anywhere in the world.
• Types of Hosting: Different types of web hosting include shared hosting, virtual private
server (VPS) hosting, dedicated hosting, and cloud hosting, each with its own features and
resource allocation.
• Domain Name: Websites hosted on these servers are typically associated with a domain
name (e.g., www.ripalranpara.com)
HTTP, or Hypertext Transfer Protocol, is a protocol used for transmitting hypertext (text with
links) over the internet. It is the foundation of any data exchange on the Web and is used for
fetching web pages and other resources.
HTTPS is the secure version of HTTP. It adds a layer of security by encrypting the data exchanged
between the user's browser and the web server, ensuring that sensitive information remains
private.
Aspect HTTP HTTPS
Security Data is sent in plain text Encrypts data for secure transfer
Protocol Standard Hypertext Transfer Hypertext Transfer Protocol Secure
Protocol
URL Prefix http://www.atmiyauni.ac.in https://www. atmiyauni.ac.in
Data Integrity No data integrity checks Ensures data integrity through
encryption
Security Indicator Not secure icon in browser Secure padlock icon in browser
Encryption No encryption Uses SSL/TLS encryption for data
security
Data Protection Vulnerable to interception and Protects against eavesdropping and
tampering data tampering
Port Operates on port 80 Operates on port 443
SEO Impact No preference for SEO rankings Google may give a slight ranking boost
to secure sites
Use Cases Suitable for non-sensitive data Essential for secure transactions, login
or public information pages, and sensitive data exchange
Before you start writing PHP code, you need a development environment. You can use tools
like XAMPP, WAMP, or MAMP, which provide a web server, PHP interpreter, and database.
These tools make it easy to test your PHP scripts locally.
Open a text editor (like Notepad on Windows or Visual Studio Code) and create a new file with
a .php extension. For example, name it first_script.php.
Inside the first_script.php file, you'll write your PHP code. Let's start with a simple "Hello,
World!" example:
Explanation:
<?php and ?>: These are PHP tags that enclose your PHP code. PHP code must be inside these
tags to be recognized by the interpreter.
echo: This is a PHP function used to output text or content to the browser. In this case, it will
display "Hello, World!" on the webpage.
After writing the code, save the file. Make sure to save it with a .php extension. Choose a
location where your development environment can access it.
Open your XAMPP, WAMP, or MAMP control panel and start the Apache web server. This will
allow your PHP script to be processed by the server.
Open your web browser and type in the address bar: http://localhost/first_script.php. Replace
first_script.php with the actual filename if you named it differently.
Explanation:
http://localhost: This is the address where your local web server is running.
/first_script.php: This is the path to the PHP script you want to access.
The structure of a PHP script follows a specific pattern. Here's the basic structure of a PHP script:
This basic structure is used for embedding PHP code within HTML or other text-based content.
It's important to note that when PHP is used for server-side scripting, only the content within
the PHP tags is processed by the server. Everything outside the PHP tags is treated as regular
HTML or text.
In PHP, comments are used to add explanations or notes within your code. Comments are not
executed by the server and do not affect the functionality of your script. They are solely meant
for developers to provide context, explanations, or reminders about the code. There are two
types of comments in PHP: single-line comments and multi-line comments.
Single-Line Comments
Single-line comments are used for adding comments on a single line. Anything after the //
symbols is considered a comment and is ignored by the server.
Multi-Line Comments
Multi-line comments are used for adding comments that span multiple lines. Anything
between /* and */ symbols is treated as a comment block.
In this example, I've enclosed the text within /* and */ symbols to create a multi-line comment.
This type of comment can span multiple lines and is often used for more detailed explanations
or notes.
In PHP, variables are used to store and manage data. They allow you to give a name to a piece
of information, making it easier to work with and manipulate that information in your code.
Here's how you declare and use variables in PHP:
Declaring Variables
In PHP, you declare a variable using the $ symbol followed by the variable name. Variable names
start with a letter or underscore, followed by letters, numbers, or underscores. They are case-
sensitive.
Using Variables
You can use variables in PHP by simply referencing their names. They can be used in various
contexts, such as in strings, calculations, and function calls.
Variable Types
PHP variables are loosely typed, meaning their data type can change based on the value
assigned to them. Common data types include strings, integers, floating-point numbers,
Booleans, and more.
Variable Concatenation
You can concatenate (combine) variables and strings using the . Operator.
• A variable must start with a dollar ($) sign, followed by the variable name.
• It can only contain alpha-numeric characters and underscores (A-z, 0-9, _).
• A variable name must start with a letter or underscore (_) character.
• A PHP variable name cannot contain spaces.
• One thing to be kept in mind is that the variable name cannot start with a number or special
symbols.
• PHP variables are case-sensitive, so $name and $NAME both are treated as different
variables.
Datatypes
Data Type Description Example
Integer Represents whole numbers without decimal $age = 25;
points.
Float Represents numbers with decimal points or $price = 10.99;
scientific notation.
String Represents a sequence of characters $name = "John";
enclosed in quotes.
Boolean Represents true (true) or false (false) values. $isStudent = true;
Array Represents a collection of values with keys or $colors = ["Red", "Green",
indexes. "Blue"];
Object Represents an instance of a user-defined $person = new Person();
class.
Resource Represents a reference to an external $dbConnection =
resource. mysqli_connect(...);
Null Represents the absence of a value. $variable = null;
Callable Represents a callable function or method. $callback = function($x)
{...};
Iterable Represents a collection of values for $numbers = [1, 2, 3];
iteration.
Mixed Represents a value with multiple possible $value = 10; // or "Hello" or
data types. true
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Increment/Decrement Operators
Increment and decrement operators are used to increase or decrease a variable's value.
Operator Description Example Result
++$x Pre-increment ++$x Increments x by 1, then returns x
$x++ Post-increment $x++ Returns x, then increments x by 1
--$x Pre-decrement --$x Decrements x by 1, then returns x
$x-- Post-decrement $x-- Returns x, then decrements x by 1
String Operators
In this example, the variable $isRaining is set to true. The conditional operator (? :) is used to
determine whether it's raining. If it is raining ($isRaining is true), the message "Bring an
umbrella." is assigned to the variable $message. Otherwise, if it's not raining, the message
"Enjoy the sunshine." is assigned. The resulting message is displayed using echo.
Facilitator: Dr. Ripal Ranpara, Atmiya University 22 | P a g e
Course Name: Web development using PHP
Course Content
Unit-1
echo:
A constant in PHP is a value that remains unchanged throughout the script's execution.
Constants are used to store data that doesn't need to be modified and is the same every time
the script runs. Constants are particularly useful for storing configuration settings,
mathematical constants, or any value that shouldn't be altered.
Defining Constants
Constants are defined using the define() function or the const keyword. The naming convention
for constants is to use uppercase letters and underscores to separate words.
Accessing Constants
Once defined, constants can be accessed throughout the script without the need to redeclare
or modify their values.
Benefits of Constants
• Readability and Maintenance: Constants make your code more readable by giving
meaningful names to values, improving code maintenance and collaboration.
• Avoid Magic Numbers: Constants help avoid using "magic numbers" (unnamed constants)
directly in your code, making your code more maintainable.
• Global Scope: Constants are available in the global scope, making them accessible from
anywhere in your script.
Constants are case-sensitive by default. If you want case-insensitive constants, you can use the
define() function with the third argument set to true.
Predefined Constants
PHP also has many predefined constants that provide useful information about
the server, environment, and PHP itself. For example:
• PHP_VERSION: Current PHP version.
• PHP_OS: Operating system PHP is running on.
• __LINE__: Current line number.
• __FILE__: Current file's path.
When you run this code, you'll get output similar to the following:
In this example, we've used various predefined constants to provide information about the
current line number, file path, PHP version, operating system, and integer value limits. This
demonstrates how useful predefined constants can be for accessing such information within
your PHP scripts.
Conditional statements in PHP allow you to control the flow of your code based on certain
conditions. These statements help your program make decisions and execute specific blocks of
code depending on whether a given condition is true or false. There are three primary types of
conditional statements in PHP: if, else if, and else. Let's explore them in detail:
if Statement:
The if statement allows you to execute a block of code only if a specified condition evaluates to
true. If the condition is false, the block of code is skipped.
Example:
else if Statement:
The else if statement allows you to provide an alternative condition to check if the initial if
condition is false. It can be used to handle multiple conditions sequentially.
Example:
else Statement:
The else statement is used to execute a block of code if the preceding if and else if conditions
are all false. It provides a default option for when none of the specified conditions are met.
Example:
Looping structures in PHP allow you to repeat a block of code multiple times, which is especially
useful for performing repetitive tasks, iterating over arrays, and processing data. There are
mainly four types of looping structures in PHP: for, while, do-while, and foreach. Let's explore
each of them:
for Loop:
The for loop is used when you know the number of iterations in advance. It consists of three
parts: initialization, condition, and iteration expression.
Example:
while Loop:
The while loop continues executing the code block as long as the specified condition is true.
The condition is checked before the code block is executed.
Example:
do-while Loop:
The do-while loop is similar to the while loop, but it guarantees that the code block is executed
at least once, even if the condition is false.
Example:
foreach Loop:
The foreach loop is used exclusively for iterating over arrays and objects. It automatically
assigns the current array element's value to a variable in each iteration.
Example:
A function in PHP is a block of code that performs a specific task. Functions help organize code
into reusable and modular pieces, making your code base more maintainable and easier to
understand.
Types of Function
Functions can be categorized into different types based on their purpose and behaviour. Here
are some common types of functions:
Built-in Functions: These are functions that are provided by PHP itself. They perform a wide
range of tasks, from string manipulation to mathematical calculations and file operations.
Examples include strlen(), str_replace(), count(), time(), and many more.
Built-in Functions
Mathematical Functions
Function Description Example
abs($number) Returns the absolute value of a number. echo abs(-5);
sqrt($number) Returns the square root of a number. echo sqrt(16);
rand($min, $max) Generates a random number within a range. echo rand(1, 100);
round($number) Rounds a floating-point number to the nearest integer. echo round(3.7);
ceil($number) Rounds a floating-point number up to the nearest echo ceil(3.2);
integer.
floor($number) Rounds a floating-point number down to the nearest echo floor(3.8);
integer.
pow($base, Raises a number to the power of another number. echo pow(2, 3);
$exponent)
max($values) Returns the highest value in an array or list of arguments. echo max(5, 8, 3);
min($values) Returns the lowest value in an array or list of arguments. echo min(5, 8, 3);
String Functions
Function Description Example
strlen($string) Returns the length of a string. echo strlen("Hello, World!");
strpos($haystack, Finds the position of a substring in a echo strpos("Hello, World!",
$needle) string. "World");
str_replace($search, Replaces occurrences of a substring with echo str_replace("World",
$replace, $string) another substring in a string. "Universe", "Hello, World!");
substr($string, $start, Returns a portion of a string. echo substr("Hello, World!", 0, 5);
$length)
trim($string) Removes whitespace (or other echo trim(" Hello, World! ");
characters) from the beginning and end
of a string.
Miscellaneous Functions
Function Description Example
echo($string) Outputs one or more strings to the echo "Hello, World!";
browser or output stream.
print($string) Outputs a string. print "Hello, World!";
var_dump($value) Dumps information about a variable, var_dump($array);
including its type and value.
isset($variable) Checks if a variable is set and not null. if (isset($name)) { echo "Name is set.";
}
empty($value) Checks if a variable is empty. if (empty($string)) { echo "String is
empty."; }
is_numeric($value) Checks if a value is numeric. if (is_numeric($number)) { echo "It's a
number."; }
is_string($value) Checks if a value is a string. if (is_string($name)) { echo "It's a
string."; }
is_array($value) Checks if a value is an array. if (is_array($data)) { echo "It's an
array."; }
is_bool($value) Checks if a value is a boolean. if (is_bool($flag)) { echo "It's a
boolean."; }
is_null($value) Checks if a value is null. if (is_null($data)) { echo "It's null."; }
gettype($value) Returns the type of a value. $type = gettype($value); echo "Type:
$type";
Facilitator: Dr. Ripal Ranpara, Atmiya University 32 | P a g e
Course Name: Web development using PHP
Course Content
Unit-2
A user-defined function in PHP is a reusable block of code that performs a specific task. It allows
you to encapsulate a set of statements under a single name, making your code modular,
organized, and easier to maintain.
Example:
• We define a user-defined function named calculateSum that takes two parameters, $num1
and $num2.
• Inside the function, we calculate the sum of the two numbers and store it in the variable
$sum.
• We use the return statement to specify that the calculated sum should be returned as the
result of the function.
• We then call the function by passing the values $a and $b, and the returned result is stored
in the variable $result.
• Finally, we use the echo statement to display the result as output in the browser.
• When you open this PHP file in a web browser, you will see the output: "The sum of 5 and 3
is: 8". This example illustrates how to define, call, and utilize a user-defined function in PHP.
Variable scope in PHP refers to the context in which a variable is accessible and can be used
within the code. PHP supports several levels of variable scope, each determining where a
variable can be accessed and modified. The two primary scopes are global scope and local
scope.
Global Scope:
Variables declared outside of functions or classes have global scope. They can be accessed from
anywhere in the script, including within functions and classes.
Local Scope:
Variables declared within functions or blocks have local scope. They can only be accessed within
the function or block where they are declared.
Static Scope:
A static variable maintains its value across function calls. It's created and initialized only once,
and the value persists between function calls.
Access Specifiers:
Access specifiers are used in object-oriented programming languages to define the visibility or
accessibility of class members (properties and methods). These specifiers determine whether
a class member can be accessed from outside the class or only within the class itself. Access
specifiers include public, private, protected, and sometimes package-private (default).
In PHP, access specifiers are used in classes to control the visibility of properties and methods:
Arrays in PHP are versatile data structures that allow you to store and manipulate collections
of values. Arrays can hold multiple values of various data types, such as integers, strings, and
even other arrays. PHP supports several types of arrays, including indexed arrays, associative
arrays, and multidimensional arrays. Let's delve into each type in detail:
Indexed Arrays
An indexed array is a collection of values where each value is assigned a numeric index (starting
from 0) to identify its position in the array.
Accessing Values:
You can access array values using their corresponding numeric indices.
Foreach Loop:
The foreach loop is especially convenient for iterating through indexed arrays.
Associative Arrays
An associative array uses named keys instead of numeric indices. Each value is associated with
a specific key.
Accessing Values:
You can access array values using their corresponding keys.
Modifying Values:
You can modify values in an associative array by specifying their keys.
Multidimensional Arrays
A multidimensional array is an array that contains one or more arrays as its elements. This
creates a matrix-like structure, allowing you to represent data in rows and columns.
Accessing Values:
You can access values in a multidimensional array by specifying both the outer and inner
indices.
Modifying Values:
You can modify values in a multidimensional array by specifying both the outer and inner
indices.
You can use nested loops, such as two foreach loops, to iterate through multidimensional
arrays.
Array Functions
Indexed Array Functions
function Description Example
count($array) Returns the number of elements in count($colors) returns 3
an array.
array_push($array, Adds one or more elements to the array_push($numbers, 8) adds 8
$value) end of an array. to the end
array_pop($array) Removes and returns the last array_pop($numbers) returns 10
element of an array.
array_merge($array1, Combines two or more arrays into array_merge($array1, $array2)
$array2) a single array.
POST Method: Sends data in the body of the HTTP request. It is more secure for sensitive
information as the data is not visible in the URL.
REQUEST Method: PHP super global that combines data from both GET and POST requests. It
can be used to access form data regardless of the submission method.
Create an HTML form that allows users to choose a file for upload. Ensure that the form has the
enctype attribute set to "multipart/form-data" to handle file uploads.
Create a PHP script that handles the uploaded file. This script will move the file
from the temporary directory to a specified location on the server.
File handling in PHP allows you to read from and write to files on your server or local machine.
PHP provides a variety of functions to perform file-related operations. Let's explore file handling
in detail with examples:
Opening a File
You can use the fopen() function to open a file in different modes (r for reading, w for writing,
a for appending, etc.).
Writing to a File:
You can use functions like fwrite() to write data to an opened file.
Closing a File:
Always close the file using the fclose() function after performing operations.
Appending to a File:
You can use the file_put_contents() function with the FILE_APPEND flag to append data to a
file.
Deleting a File:
You can use the unlink() function to delete a file.
Cookies are small pieces of data that are stored on the client's browser and sent back to the
server with each subsequent request. They are commonly used to store user-specific
information, such as preferences, shopping cart contents, or login details. Cookies are helpful
for maintaining state across different pages and sessions. You can set a cookie using the
setcookie() function. This function takes several parameters:
Sessions are a server-side mechanism used to store and manage user data across multiple
requests and pages during a browsing session. Unlike cookies, which are stored on the client-
side, session data is stored on the server. Sessions are essential for maintaining user
authentication, user preferences, and other user-specific information.
Session ID
The session ID is a unique identifier assigned to each user's session. It's used to track and
manage the user's session data on the server. The session ID is crucial for associating a user's
data with their specific session and ensuring that the correct session data is retrieved.
Generating a Session ID: When you start a session using session_start(), PHP generates a
session ID for the user if one doesn't already exist. This ID is usually a combination of letters
and numbers.
Storing the Session ID: The session ID is often stored in a cookie on the client's side, specifically
the PHPSESSID cookie. This cookie is sent back to the server with every subsequent request,
allowing the server to identify and retrieve the correct session data for that user.
Customizing the Session ID: You can also set a custom session ID using the session_id() function
before starting the session.
Regular expressions (regex) are powerful patterns that allow you to match, search, and
manipulate strings. They are commonly used for tasks such as validating and formatting text,
email addresses, phone numbers, and more in PHP. Here, I'll provide explanations and
examples for validating text, email, and phone numbers using regular expressions in PHP.
preg_match():The preg_match function in PHP is used for performing pattern matching using
regular expressions. It checks if a specified pattern matches a given string (subject). The
function returns true if the pattern is found in the string, and false otherwise.
Here's the syntax for the preg_match function:
Explanation:
/^[a-zA-Z]+$/: This regular expression checks if the entire string (^ and $ denote the start and
end of the string) consists of one or more alphabetic characters.
Explanation:
/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/: This regular expression checks if the string
represents a valid email address.
Explanation:
/^\+?[0-9()-]+$/: This regular expression checks if the string represents a valid phone number,
allowing digits, parentheses, hyphens, and an optional plus sign at the beginning.
• Database: A database is a structured collection of data organized into tables. Each table
consists of rows and columns.
• Table: A table is a collection of related data organized in rows and columns. Each column
has a specific data type and a name.
• Column: A column represents a specific piece of data within a table. Columns have names
and data types.
• Row: A row represents a single record within a table. It contains data related to each column.
• Primary Key: A primary key is a unique identifier for each row in a table. It ensures data
integrity and enables efficient data retrieval.
• SQL (Structured Query Language): SQL is a domain-specific language used for managing and
manipulating relational databases. It includes commands for creating, querying, updating,
and deleting data.
• Basic SQL Commands:
o SELECT: Retrieves data from one or more tables.
o INSERT: Adds new rows of data into a table.
o UPDATE: Modifies existing data in a table.
o DELETE: Removes rows from a table.
o CREATE: Creates a new table.
o ALTER: Modifies the structure of an existing table.
o DROP: Deletes a table.
Command Description Syntax
SELECT Retrieves data from one or more SELECT column1, column2 FROM tablename;
tables.
INSERT Adds new rows of data into a INSERT INTO tablename (column1, column2) VALUES
table. (value1, value2);
UPDATE Modifies existing data in a table. UPDATE tablename SET column1 = value1, column2
= value2 WHERE condition;
DELETE Removes rows from a table. DELETE FROM tablename WHERE condition;
CREATE Creates a new table. CREATE TABLE tablename (column1 datatype,
column2 datatype);
ALTER Modifies the structure of an ALTER TABLE tablename ADD column datatype;
existing table.
DROP Deletes a table. DROP TABLE tablename;
AUTO_INCREME
NT column.
mysqli_multi_query Performs mysqli_multi_query(connecti php
() multiple queries on, query) mysqli_multi_query($con
in a single call. n, "SELECT * FROM table;
INSERT INTO table
(column) VALUES
('value');");
mysqli_num_fields( Returns the mysqli_num_fields(result) php $num_fields =
) number of mysqli_num_fields($resul
columns in a t);
result set.
mysqli_num_rows() Returns the mysqli_num_rows(result) php $num_rows =
number of rows mysqli_num_rows($result
in a result set. );
Example
Before proceeding, make sure you have created a MySQL database and a table
named users with appropriate columns (e.g., id, username, email, password).
During this topic the facilitator will explain each function in detail
Click here to download the file (Facilitator will explain in detail during session)
https://drive.google.com/file/d/11dyiv87VwaEeXHcFde_VXBiKdzeqKKG3/view?u
sp=drive_link