0% found this document useful (0 votes)
6 views62 pages

Course Reference Material

The document outlines the course content for 'Web Programming-II' facilitated by Dr. Ripal Ranpara, covering server-side programming, PHP functions, form submission, and MySQL database operations. It includes an overview of web development, the differences between static and dynamic websites, and the roles of programming and scripting languages. The course aims to equip students with the skills to create dynamic web applications and manage databases effectively.

Uploaded by

vanditajoshi9
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)
6 views62 pages

Course Reference Material

The document outlines the course content for 'Web Programming-II' facilitated by Dr. Ripal Ranpara, covering server-side programming, PHP functions, form submission, and MySQL database operations. It includes an overview of web development, the differences between static and dynamic websites, and the roles of programming and scripting languages. The course aims to equip students with the skills to create dynamic web applications and manage databases effectively.

Uploaded by

vanditajoshi9
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/ 62

Course Name: Web Programming-II

Course Content

Facilitator: Dr. Ripal Ranpara

Course Code
Course Title Web Programming-II
Course Credit and Hours 4 Credits - 4 hrs/wk
Facilitator Dr.Ripal Ranpara

CO No. CO Statement Bloom’s Taxonomy


Level (K1 to K6)
CO1 Understand server-side programming works on the web with K1
Dynamic Web Site Design and Publishing.
CO2 Implement PHP built-in functions and creating custom functions. K1, K2
CO3 Understanding POST and GET in form submission with regular K2
expression and file handling.
CO4 Demonstrate various MySQL database queries with MySQLi. K3
CO5 Implementation of different relational database operations using K3
MySQLi with PHP.

Facilitator: Dr. Ripal Ranpara, Atmiya University


Course Name: Web Programming-II
Course Content

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

Facilitator: Dr. Ripal Ranpara, Atmiya University


Course Name: Web development using PHP
Course Content
Unit-1

Topic 1: Web Development Overview


 Introduction to Web Development
• Web development is the process of creating websites and web applications that users can
access through web browsers.
• It plays a crucial role in the modern digital landscape, facilitating communication, e-
commerce, entertainment, and information sharing.

 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).

 Web Development Life Cycle


The web development process follows a cycle:
• Requirements Gathering: Understanding client needs and project goals.
• Planning: Defining project scope, features, and technologies to be used.
• Design: Creating wireframes, mock-ups, and user interfaces.
• Development: Writing code, implementing functionality, and integrating design elements.
• Testing: Debugging, quality assurance, and ensuring proper functionality.
• Deployment: Launching the application on a web server for public access.
• Maintenance: Regular updates, bug fixes, and improvements after deployment.

Facilitator: Dr. Ripal Ranpara, Atmiya University 1|Page


Course Name: Web development using PHP
Course Content
Unit-1

Topic 2: Introduction to Webpage | Website | Difference Between Static and


Dynamic Website

 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.

• A webpage is a single document accessible through a web browser.


• It can contain text, images, multimedia, and other elements.
• HTML, CSS, and JavaScript are commonly used to structure, style, and add interactivity to
webpages.

 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.

• A website is a collection of interconnected webpages.


• It is identified by a common domain name (e.g., www.atmiyauni.ac.in).
• Websites can serve different purposes, including information dissemination,
communication, and online transactions.

 Difference between static website and dynamic website

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 2|Page


Course Name: Web development using PHP
Course Content
Unit-1

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.

Feature Static Website Dynamic Website


Content Fixed content; manual modification Dynamic content; automatic updates based
Updates on various factors (user input, database
changes, etc.)
Interactivity Limited interactivity; basic user Higher interactivity; supports user accounts,
engagement real-time updates, and personalized content
Development Simple development; suitable for Complex development; involves server-side
Complexity smaller projects scripting and potentially database
integration
Examples Brochure websites, small business Social media platforms, e-commerce sites,
sites content management systems (CMS)
Scalability Generally less scalable for large or More scalable, especially for sites with
complex sites frequent updates and user interactions
Hosting Can be hosted on static file servers Requires server support for server-side
Requirements scripting languages and database hosting

Facilitator: Dr. Ripal Ranpara, Atmiya University 3|Page


Course Name: Web development using PHP
Course Content
Unit-1

Topic 3: Programming Language and Scripting Language

 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.

Aspect Programming Language Scripting Language


Purpose Used to create full-fledged software. Used for automating tasks and
quick jobs.
Nature Typically used for larger and complex Often used for smaller, specific
tasks. tasks.
Execution Programs are compiled before Scripts are interpreted line by line.
execution.
Usage Develops applications, games, Automates tasks, data processing,
software. scripts.
Examples C++, Java, Python, C# for making Bash, Python, JavaScript for
software. scripting.
Software Creates applications like Photoshop, Automates backups, updates, file
Excel. management.
Compilation Longer time to compile before Quick, no separate compilation
Time running. needed.
Execution Requires a compiler to create Uses an interpreter to execute
Method executable code. code.

Facilitator: Dr. Ripal Ranpara, Atmiya University 4|Page


Course Name: Web development using PHP
Course Content
Unit-1

Topic 4: Client-Side vs. Server-Side


 Client-Side Processing
• Processing that occurs in the user's browser.
• Involves rendering HTML, CSS, and JavaScript to create the user interface.
• Enhances user interactivity and experience.
• Common tasks: form validation, animations, dynamic content updates.
 Server-Side Processing
• Processing that occurs on the web server.
• Involves handling data, generating dynamic content, and interacting with databases.
• Used for user authentication, database queries, business logic implementation.
• Server-side scripts generate HTML, JSON, or other data that's sent to the client.
Aspect Client-Side Scripting Server-Side Scripting
Location of Executed on the user's browser. Executed on the web server.
Execution
Languages Used HTML, CSS, JavaScript PHP, Python, Ruby, Java,
Node.js, ASP.NET, etc.
Processing Scope Focuses on user interface and Handles data processing,
interactivity. storage, security.
Use Cases Validating form inputs, animations, Handling user authentication,
DOM changes. database access.
Interaction Immediate interaction with user. Indirect interaction, response
sent to client.
Load on Server Lighter load as most processing is Heavier load due to data
local. processing.
Client Impact Faster responsiveness, less server Slower response time, depends
reliance. on server load.
Security Limited security as scripts are More secure due to server
exposed. control.
Examples - Form validation: ensuring valid email - User registration: storing data
format. in DB.
- Image sliders: changing images on - Generating dynamic content
click. based on user.

Topic 5: History and Purpose of php

 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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 5|Page


Course Name: Web development using PHP
Course Content
Unit-1

• Zend Engine: In 1999, PHP 4 introduced the Zend Engine, which boosted performance and
became the foundation for future versions.

 Purpose

• Server-Side Scripting: PHP's primary purpose is server-side scripting. It was designed to


handle tasks on the web server, such as generating dynamic content and interacting with
databases.
• Dynamic Web Pages: PHP enables the creation of web pages that change content based on
user inputs and other conditions. This dynamic behavior enhances user experience.
• Form Handling: PHP is commonly used to process form data submitted by users. It validates
inputs, performs actions, and stores data.
• Database Interaction: PHP seamlessly interacts with databases like MySQL, allowing for
tasks such as querying, inserting, updating, and deleting data.
• User Authentication: It enables the creation of secure login systems and user authentication
processes, ensuring access control to web applications.
• CMS and Frameworks: PHP powers various content management systems (like WordPress)
and frameworks (like Laravel) that simplify web development.
• Integration with HTML: PHP can be embedded within HTML code, making it easy to mix
dynamic and static content within a single file.
• Image and File Handling: PHP can manipulate images, generate files (e.g., PDFs), and
manage file uploads.
• Community and Open Source: PHP's open-source nature and large community contribute
to its continuous improvement and a wealth of resources.
• Web Development Ecosystem: It's a vital part of the web development ecosystem, playing
a significant role in creating a wide range of web applications, from simple websites to
complex platforms.

Topic 6: Introduction to php

 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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 7|Page


Course Name: Web development using PHP
Course Content
Unit-1

Topic 7: Introduction to Web servers | XAMPP |LAMPP | Php.ini

 Introduction to web server

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

Topic 8: Web Hosting:

 Introduction to web server

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 8|Page


Course Name: Web development using PHP
Course Content
Unit-1

• 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)

Topic 9: HTTP / HTTPS

 Introduction to HTTP | HTTPS

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

Topic 10: Writing and Executing Your First PHP Script

 Step 1: Set Up a Development Environment:

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.

 Step 2: Create a New PHP File:

Facilitator: Dr. Ripal Ranpara, Atmiya University 9|Page


Course Name: Web development using PHP
Course Content
Unit-1

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.

 Step 3: Write Your PHP Code:

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.

 Step 4: Save the File:

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.

 Step 5: Start Your Web Server:

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.

 Step 6: Access the PHP Script in Your Browser:

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.

Step 7: View the Output:


After accessing the URL, you should see the output of your PHP script in the browser. It will
display "Hello, World!" on the webpage.

Facilitator: Dr. Ripal Ranpara, Atmiya University 10 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

Topic 11: Structure of Php Script

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.

Topic 12: Comments in php

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 11 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

 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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 12 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

Topic 13: Variables in php

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 13 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

 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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 14 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

 Variable Concatenation

You can concatenate (combine) variables and strings using the . Operator.

Facilitator: Dr. Ripal Ranpara, Atmiya University 15 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

Rules of Naming Variables

• 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

Facilitator: Dr. Ripal Ranpara, Atmiya University 16 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

Topic 14: Operators in php


An operator in programming is a symbol or keyword that represents an action or operation to
be performed on one or more operands. Operands are the values or variables on which the
operator acts. Operators are an essential part of programming languages as they allow you to
perform various tasks, such as performing mathematical calculations, comparing values,
assigning values, and more.

 Arithmetic Operators

Arithmetic operators perform mathematical calculations on values.


Operator Description Example Result
+ Addition $x + $y Sum of x and y
- Subtraction $x - $y Difference between x and y
* Multiplication $x * $y Product of x and y
/ Division $x / $y Quotient of x divided by y
% Modulus (remainder) $x % $y Remainder of x divided by y
** Exponentiation (power) $x ** $y x raised to the power of y

Facilitator: Dr. Ripal Ranpara, Atmiya University 17 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

 Assignment Operators

Assignment operators are used to assign values to variables.


Operator Description Example Equivalent To
= Assign value $x = 5 $x = 5
+= Add and assign $x += 3 $x = $x + 3
-= Subtract and assign $x -= 2 $x = $x - 2
*= Multiply and assign $x *= 4 $x = $x * 4
/= Divide and assign $x /= 2 $x = $x / 2
%= Modulus and assign $x %= 5 $x = $x % 5
**= Exponentiation and assign $x **= 3 $x = $x ** 3

Facilitator: Dr. Ripal Ranpara, Atmiya University 18 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

 Comparison Operators

Comparison operators are used to compare values.


Operator Description Example Result
== Equal to $x == $y True if x is equal to y
=== Identical (equal and $x === $y True if x is equal to y and they are of the same type
same type)
!= Not equal to $x != $y True if x is not equal to y
!== Not identical $x !== $y True if x is not equal to y, or they are not of the
same type
< Less than $x < $y True if x is less than y
> Greater than $x > $y True if x is greater than y
<= Less than or equal to $x <= $y True if x is less than or equal to y
>= Greater than or equal to $x >= $y True if x is greater than or equal to y

Facilitator: Dr. Ripal Ranpara, Atmiya University 19 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

 Logical Operators

Logical operators are used to combine or negate conditions.


Operator Description Example Result
&& or and Logical AND $x && $y True if both x and y are true
|| or or Logical OR $x || $y True if either x or y is true
! Logical NOT (negation) ! $x True if x is false, and false if x is true

Facilitator: Dr. Ripal Ranpara, Atmiya University 20 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

 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

Facilitator: Dr. Ripal Ranpara, Atmiya University 21 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

 String Operators

String operators are used to concatenate strings.


Operator Description Example Result
. Concatenation $str1 . $str2 Concatenates str1 and str2

 Conditional (Ternary) Operator

The conditional operator provides a shorthand way of writing if-else statements.


Operator Description Example Result
?: Ternary (conditional) $condition ? $value1 Returns $value1 if $condition is true,
operator : $value2 otherwise returns $value2

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

Topic 15: Difference Between echo and Print

echo:

• Language construct for outputting strings and variables.


• Can be used without parentheses for a single string or with parentheses for multiple items.
• Doesn't have a return value; cannot be used within expressions.
• Commonly used for quick output.
print:

• Built-in function for outputting a single string or variable.


• Requires parentheses for the value to be printed.
• Returns a value (1 for success, 0 for failure); can be used within expressions.
• Less common; used when return value matters or simpler syntax is preferred for single-
value output.

Aspect echo print


Type Language construct Function
Return Value None (no return value) Returns 1 (successful) or 0
(failure)
Arguments Multiple arguments separated by commas Single argument
Usable in Yes (can be part of expressions) No (can't be part of expressions)
Expressions
Speed Faster Slower
Example echo "Hello", " World"; print "Hello World";

Facilitator: Dr. Ripal Ranpara, Atmiya University 23 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

Topic 16: Constants

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.

Using the define() Function

Using the const Keyword

 Accessing Constants

Once defined, constants can be accessed throughout the script without the need to redeclare
or modify their values.

Facilitator: Dr. Ripal Ranpara, Atmiya University 24 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

 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.

Note on Case Sensitivity:

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:

Facilitator: Dr. Ripal Ranpara, Atmiya University 25 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

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.

Topic 17: Conditional Statements

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:

Facilitator: Dr. Ripal Ranpara, Atmiya University 26 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

 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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 27 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

Example:

 Nested Conditional Statements:


You can also nest conditional statements within each other to handle more complex decision-
making situations.

Topic 18: Looping Structures

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 28 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 29 | P a g e


Course Name: Web development using PHP
Course Content
Unit-1

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:

Facilitator: Dr. Ripal Ranpara, Atmiya University 30 | P a g e


Course Name: Web development using PHP
Course Content
Unit-2

Topic 19: Functions

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.

User-Defined Functions: These are functions created by the programmer to perform


specific tasks. They help organize code, improve readability, and enable code reuse. User-
defined functions are created using the function keyword.

 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)

Facilitator: Dr. Ripal Ranpara, Atmiya University 31 | P a g e


Course Name: Web development using PHP
Course Content
Unit-2

strtolower($string) Converts a string to lowercase. echo strtolower("Hello, World!");

strtoupper($string) Converts a string to uppercase. echo strtoupper("Hello, World!");

ucfirst($string) Converts the first character of a string to echo ucfirst("hello, world!");


uppercase.
strrev($string) Reverses a string. echo strrev("Hello, World!");

trim($string) Removes whitespace (or other echo trim(" Hello, World! ");
characters) from the beginning and end
of a string.

Date & Time Functions


date($format, $timestamp) Formats a local date and time. echo date("Y-m-d H:i:s");
time() Returns the current Unix echo time();
timestamp.
strtotime($time, $now) Converts a date/time string echo strtotime("2023-08-01");
into a Unix timestamp.
gmdate($format, Formats a GMT/UTC date and echo gmdate("Y-m-d H:i:s");
$timestamp) time.
mktime($hour, $minute, Creates a Unix timestamp. echo mktime(12, 0, 0, 8, 1, 2023);
$second, $month, $day,
$year)
date_default_ Sets the default timezone. date_default_
timezone_set($timezone) timezone_set("America/New_York");

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

File include Function


Feature include require
Purpose Includes a file and continues execution if Includes a file and halts execution if the
the file is not found. file is not found.
Execution Continues execution even if the included Halts execution if the included file is
Continuation file is missing. missing.
Error Handling Generates a warning and continues Generates a fatal error and stops
execution if the file is not found. execution if the file is not found.
Syntax include 'filename'; require 'filename';
Example include 'header.php'; require 'config.php';

Feature include require include_once require_once


Purpose Includes a file and Includes a file and Includes a file only if itIncludes a file
continues halts execution if has not been included only if it has
execution if the file the file is not before. not been
is not found. found. included
before.
Execution Continues Halts execution if Continues execution if Halts execution
Continuation execution even if the included file is the included file has if the included
the included file is missing. been included before. file has been
missing. included
before.
Error Handling Generates a Generates a fatal Generates a warning Generates a
warning and error and stops and continues fatal error and
continues execution if the execution if the file has stops
execution if the file file is not found. been included before. execution if the
is not found. file has been
included
before.
Use Case Suitable for files Suitable for files Useful when a file might Useful when a
that enhance the that are essential be included multiple file might be
script but are not for the script's times within the script. included
critical. functionality. multiple times
within the
script.
Syntax include 'filename'; require 'filename'; include_once require_once
'filename'; 'filename';

 User Defined Functions

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 33 | P a g e


Course Name: Web development using PHP
Course Content
Unit-2

Explanation of the Components:


• function: The keyword that signifies the start of a function definition.
• functionName: The name you choose for your function, following PHP naming rules.
• parameters: The list of input parameters that the function can accept, separated by
commas.
• {}: The curly braces that enclose the function body.
• // ...: Placeholder for the actual statements you want the function to execute.
• return value;: An optional return statement that specifies the value the function will return.

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 34 | P a g e


Course Name: Web development using PHP
Course Content
Unit-2

• 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.

Topic 20: Expression

An expression in programming is a combination of values, variables, operators, and function


calls that, when evaluated, produces a single value or result. Expressions are the building blocks
of code that perform calculations, comparisons, and other operations, and they provide a way
to manipulate and transform data. Expressions can be as simple as a single value or as complex
as a combination of multiple sub-expressions.
Expression Type Example Description
Arithmetic Expression $sum = $x + $y; Performs arithmetic calculations.
Comparison Expression $isGreater = $a > $b; Compares values using comparison
operators.
String Concatenation $fullName = $firstName . " " . Combines strings using the
Expression $lastName; concatenation operator.
Function Call $area = pi() * pow($radius, 2); Calls built-in or user-defined functions.
Expression
Logical Expression $isGoodWeather = $isSunny && Combines boolean values using logical
$isWarm; operators.
Ternary Expression $isAdult = ($age >= 18) ? "Adult" Creates concise conditional
: "Minor"; expressions.

Facilitator: Dr. Ripal Ranpara, Atmiya University 35 | P a g e


Course Name: Web development using PHP
Course Content
Unit-2

Facilitator: Dr. Ripal Ranpara, Atmiya University 36 | P a g e


Course Name: Web development using PHP
Course Content
Unit-2

Topic 21: Variable Scope

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 37 | P a g e


Course Name: Web development using PHP
Course Content
Unit-2

 Super Global Scope:


PHP provides a set of predefined superglobal arrays (e.g., $_POST, $_GET, $_SESSION) that are
accessible from any part of the script.

 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:

• public: The property or method is accessible from outside the class.


• private: The property or method is only accessible within the class that defines it.
• protected: The property or method is accessible within the class and its subclasses.

Facilitator: Dr. Ripal Ranpara, Atmiya University 38 | P a g e


Course Name: Web development using PHP
Course Content
Unit-2

echo "Model: {$this->model}, Price: {$this->price}, Year: {$this->year}";

Facilitator: Dr. Ripal Ranpara, Atmiya University 39 | P a g e


Course Name: Web development using PHP
Course Content
Unit-2

Topic 22: Arrays

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.

Defining an Indexed Array:


You can define an indexed array using the array() function or using the shorthand square
bracket syntax [].

Accessing Values:
You can access array values using their corresponding numeric indices.

Modifying Array Values:


You can modify values in an indexed array using their indices.

Adding New Values:


You can add new values to an indexed array by specifying a new index.

Facilitator: Dr. Ripal Ranpara, Atmiya University 40 | P a g e


Course Name: Web development using PHP
Course Content
Unit-2

Looping Through Indexed Arrays:


You can use loops, such as for and foreach, to iterate through indexed arrays and perform
operations on their elements.

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.

Defining an Associative Array:


You can define an associative array using the array() function or the shorthand square bracket
syntax [].

Facilitator: Dr. Ripal Ranpara, Atmiya University 41 | P a g e


Course Name: Web development using PHP
Course Content
Unit-2

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.

Adding New Values:


You can add new key-value pairs to an associative array.

Looping Through Associative Arrays:


You can use loops, especially the foreach loop, to iterate through associative arrays.

Facilitator: Dr. Ripal Ranpara, Atmiya University 42 | P a g e


Course Name: Web development using PHP
Course Content
Unit-2

 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.

Defining a Multidimensional Array:


You can define a multidimensional array by nesting arrays within arrays.

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.

Looping Through Multidimensional Arrays:


Facilitator: Dr. Ripal Ranpara, Atmiya University 43 | P a g e
Course Name: Web development using PHP
Course Content
Unit-2

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.

Associative Array Functions


Function Description Example
count($array) Returns the number of elements count($student) returns 3
in an array.
array_keys($array) Returns an array containing all array_keys($student) returns
the keys of the input array. ["name", "age", "major"]
array_values($array) Returns an array containing all array_values($student) returns
the values of the input array. ["John", 25, "Computer Science"]
array_key_exists($key, Checks if a specific key exists in array_key_exists("age", $student)
$array) the array. returns true

Multidimensional Array Functions


Function Description Example
count($array) Returns the number of elements count($matrix) returns 3
in an array.
array_column($array, Returns the values from a single array_column($matrix, 1) returns
$column_key) column in the input array. [2, 5, 8]
Facilitator: Dr. Ripal Ranpara, Atmiya University 44 | P a g e
Course Name: Web development using PHP
Course Content
Unit-2

array_map($callback, Applies a callback function to each array_map('sqrt', $matrix) returns a


$array) element in the input array. new array with square roots

Other Array Functions


Function Description Example
implode($separator, Combines array elements into a implode(", ", $colors) returns "Red,
$array) string using a specified separator. Green, Blue"
explode($delimiter, Splits a string into an array based explode(" ", "Hello World") returns
$string) on a specified delimiter. ["Hello", "World"]
in_array($value, Checks if a value exists in an array in_array("Green", $colors) returns
$array) and returns true or false. true
array_flip($array) Exchanges keys with values in an array_flip($student) returns an
associative array. array with keys and values swapped
array_shift($array) Removes and returns the first array_shift($colors) returns the
element from an array. removed element
array_unshift($array, Adds one or more elements to the array_unshift($colors, "Yellow")
$value) beginning of an array. adds "Yellow" to the start
array_values($array) Returns an array containing all the array_values($student) returns
values of the input array. ["John", 25, "Computer Science"]

Facilitator: Dr. Ripal Ranpara, Atmiya University 45 | P a g e


Course Name: Web development using PHP
Course Content
Unit-3

Topic 23: Form Submission with GET | POST | REQUEST


Forms in HTML:
In web development, a form is an essential element that allows users to input data and submit
it to a server for processing. Forms are created using HTML <form> tags and include various
input elements such as text fields, checkboxes, radio buttons, and buttons.
GET Method: Sends data as part of the URL. It is suitable for non-sensitive data and is visible in
the URL.

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.

Aspect GET POST REQUEST


Visibility Data is visible in the Data is not visible in the Combines data from both GET and
URL URL POST requests
Security Less secure, as data More secure, as data is Combines the advantages of GET and
is in the URL in the request body POST
Data Limited by the Limited by the server Limited by the server and PHP settings
Length maximum URL length and PHP settings
Caching Can be cached Generally not cached Combines caching behaviour of both
GET and POST
Bookmarks Can be bookmarked Not suitable for Combines bookmarking behaviour of
bookmarking both GET and POST
Example in <form <form <form action="process.php"
HTML action="process.php" action="process.php" method="post">
method="get"> method="post">
Example in $name = $name = $name = $_REQUEST['name'];
PHP $_GET['name']; $_POST['name'];

Facilitator: Dr. Ripal Ranpara, Atmiya University 46 | P a g e


Course Name: Web development using PHP
Course Content
Unit-3

Topic 24: File Uploading

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 47 | P a g e


Course Name: Web development using PHP
Course Content
Unit-3

Topic 25: File Handling

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.).

 Reading from a File:


You can use functions like fgets() or fread() to read data from an opened file.

 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.

 Checking File Existence:


You can use the file_exists() function to check if a file exists.

Facilitator: Dr. Ripal Ranpara, Atmiya University 48 | P a g e


Course Name: Web development using PHP
Course Content
Unit-3

 Reading Entire File Content:


You can use the file_get_contents() function to read the entire content of a file into a string.

 Writing Entire File Content:


You can use the file_put_contents() function to write a string to a file.

 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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 49 | P a g e


Course Name: Web development using PHP
Course Content
Unit-3

Topic 26: Cookies

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:

• Cookie name • Domain (optional)


• Cookie value • Secure (optional)
• Expiry time • HttpOnly (optional)
• Path

Topic 27: Session

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

Facilitator: Dr. Ripal Ranpara, Atmiya University 50 | P a g e


Course Name: Web development using PHP
Course Content
Unit-3

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 51 | P a g e


Course Name: Web development using PHP
Course Content
Unit-3

Topic 28: Regular Expression

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:

• pattern: The regular expression pattern to search for.


• subject: The string in which to search for the pattern.
• matches (optional): An optional parameter to store the matches found. If specified, it
will be filled with the matches.

 Text Validation Example:


Function: preg_match(pattern, subject)

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 52 | P a g e


Course Name: Web development using PHP
Course Content
Unit-3

 Email Validation Example:


Function: preg_match(pattern, subject)

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.

 Phone Validation Example:


Function: preg_match(pattern, subject)

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.

Facilitator: Dr. Ripal Ranpara, Atmiya University 53 | P a g e


Course Name: Web development using PHP
Course Content
Unit-4

Topic 29: MySQL

MySQL is a popular open-source relational database management system (RDBMS) that is


widely used for storing and managing structured data. It's commonly used for web applications,
content management systems, e-commerce platforms, and various other software projects.
Here's an overview of MySQL basics:

• 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;

Facilitator: Dr. Ripal Ranpara, Atmiya University 54 | P a g e


Course Name: Web development using PHP
Course Content
Unit-4

Topic 30: MySQL Php Functions

Function Description Syntax Example


mysqli_connect Establishes a mysqli_connect(host, $connection =
MySQL username, password, mysqli_connect("localhost",
database dbname); "username", "password",
connection. "dbname");
mysqli_query Executes an mysqli_query(connection, $query = "SELECT * FROM
SQL query on query); users"; $result =
the database. mysqli_query($connection,
$query);
mysqli_prepare Prepares an mysqli_prepare(connectio $stmt =
SQL statement n, query); mysqli_prepare($connectio
for execution. n, "SELECT username FROM
users WHERE id = ?");
mysqli_stmt_bind_pa Binds variables mysqli_stmt_bind_param( mysqli_stmt_bind_param($
ram to a prepared stmt, types, ...); stmt, "i", $id);
statement as
parameters.
mysqli_fetch_assoc Fetches a mysqli_fetch_assoc(result) while ($row =
result row as ; mysqli_fetch_assoc($result)
an associative ) { echo $row["username"];
array. }
mysqli_fetch_row Fetches a mysqli_fetch_row(result); while ($row =
result row as a mysqli_fetch_row($result))
numeric array. { echo $row[0]; }
mysqli_fetch_object Fetches a mysqli_fetch_object(result while ($row =
result row as ); mysqli_fetch_object($result
an object. )) { echo $row->username; }
mysqli_fetch_array Fetches a mysqli_fetch_array(result, while ($row =
result row as resulttype); mysqli_fetch_array($result,
an array. MYSQLI_ASSOC)) { echo
$row["username"]; }
mysqli_error Returns the mysqli_error(connection); $error =
last error mysqli_error($connection);
message from
the database
connection.
mysqli_close Closes the mysqli_close(connection); mysqli_close($connection);
database
connection.

Facilitator: Dr. Ripal Ranpara, Atmiya University 55 | P a g e


Course Name: Web development using PHP
Course Content
Unit-4

Function Description Syntax Example

mysqli_affected_ro Returns the mysqli_affected_rows(conne php $affected_rows =


ws() number of rows ction) mysqli_affected_rows($c
affected by the onn);
last query.
mysqli_fetch_all() Fetches all rows mysqli_fetch_all(result, php $rows =
from a result set resulttype) mysqli_fetch_all($result,
as an MYSQLI_ASSOC);
associative
array, a numeric
array, or both.
mysqli_fetch_array( Fetches a result mysqli_fetch_array(result, php $row =
) row as an resulttype) mysqli_fetch_array($resu
associative lt, MYSQLI_ASSOC);
array, a numeric
array, or both.
mysqli_fetch_assoc( Fetches a result mysqli_fetch_assoc(result) php $assoc_row =
) row as an mysqli_fetch_assoc($resu
associative lt);
array.
mysqli_fetch_fields( Returns an mysqli_fetch_fields(result) php $fields =
) array of objects mysqli_fetch_fields($resu
representing lt);
the fields in a
result set.
mysqli_fetch_row() Fetches a result mysqli_fetch_row(result) php $numeric_row =
row as a mysqli_fetch_row($result
numeric array. );
mysqli_fetch_objec Fetches a result mysqli_fetch_object(result) php $object_row =
t() row as an mysqli_fetch_object($res
object. ult);
mysqli_field_count( Returns the mysqli_field_count(connectio php $num_columns =
) number of n) mysqli_field_count($conn
columns for the );
most recent
query.
mysqli_field_seek() Sets the current mysqli_field_seek(result, php
position of the offset) mysqli_field_seek($result
field cursor. , 1);
mysqli_free_result() Frees the mysqli_free_result(result) php
memory mysqli_free_result($resul
associated with t);
a result set.
mysqli_insert_id() Returns the mysqli_insert_id(connection) php $last_id =
auto-generated mysqli_insert_id($conn);
id used in the
last query with
an

Facilitator: Dr. Ripal Ranpara, Atmiya University 56 | P a g e


Course Name: Web development using PHP
Course Content
Unit-4

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).

Facilitator: Dr. Ripal Ranpara, Atmiya University 57 | P a g e


Course Name: Web development using PHP
Course Content
Unit-4

$connection = mysqli_connect("localhost", "username", "password", "dbname");


$query = "INSERT INTO users (username, email, password) VALUES ('$username',
'$email', '$password')";

Facilitator: Dr. Ripal Ranpara, Atmiya University 58 | P a g e


Course Name: Web development using PHP
Course Content
Unit-4

Topic 31: CRUD OPERATION in php

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

Facilitator: Dr. Ripal Ranpara, Atmiya University 59 | P a g e


Course Name: Web development using PHP
Course Content
Module 5

For more information you can contact Course Facilitator:


Dr.Ripal D Ranpara
ranpararipal@atmiyauni.ac.in
www.ripalranpara.com
https://www.linkedin.com/in/ranpararipal/

Facilitator: Dr. Ripal Ranpara, Atmiya University 60 | P a g e

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