PHP Nep Unit - 1
PHP Nep Unit - 1
CHAUDHARY
Web-Technologies
Web technology refers to the tools and techniques used to build and
manage websites and web applications. It involves a combination of
programming languages, protocols, frameworks, and tools that enable
the creation, development, and maintenance of web-based content,
services, and functionalities.
Key Components of Web Technology
1. Web Protocols:
HTTP (HyperText Transfer Protocol): The foundation of data
communication on the web. HTTP de ines how requests and
responses are sent and received between clients (typically web
browsers) and servers.
HTTPS (HyperText Transfer Protocol Secure): A secure
version of HTTP that uses encryption (SSL/TLS) to protect data
exchanged between the client and the server.
2. Web Browsers:
Web browsers (such as Google Chrome, Mozilla Firefox, Safari,
and) interpret web content and display it to users. They retrieve
web pages via HTTP/HTTPS requests and render HTML, CSS,
and JavaScript.
3. Frontend Technologies (Client-Side):
HTML (HyperText Markup Language): The standard language
used to structure content on the web. HTML provides the basic
framework for creating web pages, including text, images, links,
and multimedia.
CSS (Cascading Style Sheets): Used to de ine the layout, design,
and appearance of web pages. CSS controls elements such as
colors, fonts, spacing, and positioning.
JavaScript: A programming language that adds interactivity and
dynamic behavior to websites. JavaScript allows for client-side
scripting, enabling features such as form validation, animations,
and content updates without reloading the page.
4. Backend Technologies (Server-Side):
Web Servers: A server (e.g., Apache, Nginx) is responsible for
processing requests from clients and delivering web pages or
other resources like images, videos, or data. It serves content
based on the server-side programming logic.
User Request: The user types a URL into the browser or clicks a link.
Request Handling: The browser sends an HTTP request to the web
server.
Backend Processing: The server processes the request, potentially
querying a database, running business logic, and generating dynamic
content.
Response: The server sends the generated content back to the
browser, typically as HTML, CSS, and JavaScript.
Rendering: The browser renders the content for the user to interact
with.
Client-side scripting
Client-side scripting refers to scripts executed directly in a user's
web browser, rather than on the server. These scripts enable
dynamic interactions and real-time updates on web pages,
enhancing the user experience without needing to reload or
request new pages from the server.
Client-side scripting is primarily driven by JavaScript, though
HTML and CSS also play important roles in structuring and
styling content. The key advantage of client-side scripting is its
ability to reduce server load, speed up interactions, and create
responsive, interactive web applications. Examples include
handling form validation, updating content dynamically, and
creating animations.
Key Features of Client-Side Scripting
1. Execution in the Browser:
Scripts run on the client (the user’s web browser), meaning that
the server is only responsible for delivering the initial web page
(HTML, CSS, and JavaScript). Once the page is loaded, all dynamic
content updates and interactions are handled directly in the
browser.
2. Interactive and Dynamic Content:
Client-side scripting is used to change elements of the page
dynamically in response to user interactions. This can include
tasks like validating form data, displaying real-time updates, or
responding to button clicks without refreshing the page.
3. Reduced Server Load:
Because the browser handles most of the logic and UI updates,
the server is only responsible for serving the initial content. This
reduces the load on the server and minimizes network traf ic, as
only essential requests (e.g., for data) are sent.
4. Asynchronous Operations:
JavaScript can asynchronously fetch data from the server (using
techniques like AJAX) without needing to refresh the page. This
allows for features such as in inite scrolling, live data updates,
and interactive forms.
5. Enhanced User Experience:
The ability to manipulate the DOM (Document Object Model)
allows developers to create seamless, smooth, and engaging
experiences, like animations, real-time form validation, dynamic
content updates, and rich interactive elements.
How Client-Side Scripting Works
Page Load:
When a user visits a webpage, the browser sends a
request to the web server. The server responds by sending
the necessary resources (HTML, CSS, JavaScript) to the
browser.
Parsing and Rendering:
The browser parses the HTML, rendering the structure of
the page. It then applies the CSS styles, creating the visual layout.
JavaScript is executed either inline within the HTML or via
external iles.
Event Handling:
JavaScript listens for user interactions (such as clicks,
scrolls, keypresses) using event listeners. When an event occurs,
the associated JavaScript function is triggered to perform some
action.
DOM Manipulation:
The DOM represents the HTML structure of the page as a
tree-like structure in memory. JavaScript can interact with this
structure, modifying elements, changing styles, or
adding/removing content dynamically.
AJAX for Asynchronous Data Fetching:
AJAX (Asynchronous JavaScript and XML) allows JavaScript to
fetch data from the server in the background without reloading the
page. This is useful for live updates, form submissions, and dynamic
content loading.
Server-Side Scripting
Server-side scripting refers to scripts that are executed on a web
server rather than in the user's web browser. When a user
requests a webpage, the server processes the server-side script,
performs any necessary operations (such as database queries,
calculations, or authentication), and then sends the results
(often in the form of HTML) to the user's browser for display.
Example Php,Node Js, Asp.net,Rubby,Java etc.
Key Characteristics of Server-Side Scripting
Execution on the Server: The script runs on the server, which
means that the user does not see the server-side code. Only the
inal output (usually HTML) is sent to the user's browser.
Dynamic Content Generation: Server-side scripts can generate
dynamic content based on user input, session data, or database
information. This makes it possible to personalize websites and
create interactive web applications.
Interactivity: Server-side scripting can handle user requests,
process data, and return responses, such as retrieving
information from a database or performing calculations based
on form input.
Security: Since the code runs on the server, it is not exposed to
the client, which makes server-side scripting more secure for
handling sensitive data, like authentication, payment
processing, and ile uploads.
How Server-Side Scripting Works
User Request: When a user enters a URL in their browser or clicks a
link, the browser sends an HTTP request to the web server.
Server Processing: The server processes the request and invokes the
appropriate server-side script. The script may interact with a
database, perform calculations, or generate dynamic content based on
the request.
Database Interaction: If necessary, the server-side script can query a
database to retrieve or store information (e.g., user data, product
information, etc.).
Response Generation: After processing, the server sends back the
resulting data (usually HTML) to the user's browser. This could include
dynamically generated web pages, such as a personalized user
dashboard or search results.
User View: The browser renders the HTML received from the server
and displays the page to the user.
How Server side scripting work
Client Sends a Request
A user interacts with a web page (e.g., submits a form, clicks a button,
or requests a URL).
The browser sends an HTTP request to the web server hosting the
website.
Server Processes the Request
The server identi ies the requested resource (e.g., a PHP, Python, or
Node.js script) and executes the associated server-side script.
The script may include operations such as:
o Querying or updating a database.
o Validating user input.
o Reading or writing iles on the server.
o Generating dynamic HTML, JSON, or other content.
Interaction with a Database
If needed, the script interacts with a database to retrieve or store data.
For example:
o User requests their pro ile → Script queries the database for user
information.
oUser submits a comment → Script saves the comment in the
database.
Generating a Response
The script composes a response based on the processed data.
o This could be an HTML page, JSON data for an API, or even a ile
download.
Example:
o A login script checks the database for user credentials and either
redirects to a dashboard or shows an error message.
Sending the Response to the Client
The server sends the generated response back to the client.
If the response is an HTML page, it is rendered by the browser.
If it's JSON or XML, it may be processed by client-side scripts for
further interaction.
Client Displays the Response
The browser interprets and displays the content received from the
server.
If additional resources (images, CSS, JavaScript) are required, the
browser sends subsequent requests to fetch them.
Client Side Scripting Vs Server Side Scripting
Client-side scripting Server-side scripting
Source code is visible to the user. Source code is not visible to the
user because its output
of server-sideside is an HTML
page.
Its main function is to provide Its primary function is to
the requested output to the end manipulate and provide access to
user the respective database as per
the request.
It usually depends on the In this any server-side
browser and its version. technology can be used and it
does not
depend on the client.
It runs on the user’s computer. It runs on the webserver.
There are many advantages The primary advantage is its
linked with this like faster. ability to highly customize,
response times, a more response
interactive application. requirements, access rights
based on user.
It does not provide security for It provides more security for
data data.
It is a technique used in web It is a technique that uses scripts
development in which scripts on the webserver to produce a
run on the client’s browser response that is customized for
each client’s request.
HTML, CSS, and javascript are PHP, Python, Java, Ruby are used
used.
No need of interaction with the It is all about interacting with the
server. servers.
It reduces load on processing It surge the processing load on
unit of the server. the server.
Web browser
A web browser is a software application that allows users to access,
retrieve, and display content on the World Wide Web, such as web
1. Client:
2. Server:
The server is responsible for processing client requests and serving
appropriate responses. This is where PHP scripts reside, along with a
web server like Apache or Nginx.
It handles tasks such as business logic, database interactions, and
dynamic content generation.
How it Works in PHP
SHRI ADARSH BCA COLLEGE , RADHANPUR 12
Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY
Client Request:
The client sends a request (e.g., an HTTP request) to the server,
typically triggered by an action like clicking a button, submitting a
form, or loading a webpage.
Example: GET http://example.com/get-data
Server Response:
The server processes the request using PHP scripts, fetches or
processes data, and sends the response back to the client.
Example: JSON, HTML, or XML data is sent back to the client.
How PHP Fits in the Client-Server Model
Server-Side Scripting:
PHP runs on the server to handle incoming requests, process data, and
generate responses.
Database Interaction:
PHP scripts often interact with databases (like MySQL) to fetch or
store data as needed.
Response Handling:
PHP prepares dynamic content (HTML, JSON, etc.) that is sent to the
client.
Middleware Role:
PHP can also act as a middleware in APIs, interacting with other
services and forwarding the results to clients.
History of PHP
PHP, originally created in 1994, has grown from a
simple tool for building web pages to one of the
most widely used server-side programming
languages in the world. Here’s a timeline of its
evolution:
1994: The Beginning
PHP Features
PHP (Hypertext Preprocessor) is a powerful and
versatile scripting language widely used for server-
side web development. Here are the key features of
PHP that make it popular among developers:
1. Simplicity and Ease of Use
PHP is easy to learn, especially for beginners, due to its simple
and intuitive syntax.
1. Single-Line Comments
Used for brief comments or explanations on a single line.
Syntax:
2. Multi-Line Comments
Case-Sensitive:
$validVariable = "Valid";
$_another_valid_variable = 123;
$invalid-variable = "Invalid"; // Syntax Error: Hyphens are not
allowed.
Output Variables
In PHP, you can output variables using functions or constructs
like echo, print, printf, and var_dump.
1. Using echo
A simple and widely used construct to output one or more
strings or variables.
Example
<?php
$name = "John";
$age = 25;
echo "Name: " . $name . ", Age: " . $age; // Outputs: Name: John,
Age: 25
?>
2. Using print
Similar to echo but returns a value (1), making it slightly slower.
Example
<?php
$message = "Hello, World!";
print $message; // Outputs: Hello, World!
?>
3. Using printf
Used for formatted output, allowing more control over the
output format.
Example
<?php
$name = "Alice";
$age = 30;
printf("Name: %s, Age: %d", $name, $age); // Outputs: Name:
Alice, Age: 30
?>
4. Using print_r
Outputs human-readable information about a variable
(commonly for arrays or objects).
Example
<?php
$fruits = ["Apple", "Banana", "Cherry"];
localScopeExample();
echo $localVar; // Error: Unde ined variable
?>
2. Global Scope
function globalScopeExample() {
global $globalVar; // Importing the global variable
echo $globalVar; // Outputs: I'm global!
}
globalScopeExample();
?>
<?php
$globalVar = "Accessible via \$GLOBALS";
function globalScopeExample() {
echo $GLOBALS['globalVar']; // Outputs: Accessible via $GLOBALS
}
globalScopeExample();
?>
3. Static Scope
A variable declared as static inside a function retains its value
between function calls.
Unlike local variables, static variables are not destroyed when the
function ends. However, they are only accessible within the function
they are declared in.
<?php
function staticScopeExample() {
static $counter = 0; // Static variable
$counter++;
echo $counter . "\n";
}
staticScopeExample(); // Outputs: 1
staticScopeExample(); // Outputs: 2
staticScopeExample(); // Outputs: 3
?>
4. Superglobal Scope
a) NULL
Represents a variable with no value or an explicitly assigned null
value.
b) Resource
Refers to an external resource like a ile handle or database
connection.
Typically created using special functions (e.g., fopen,
mysqli_connect).
Type Casting
PHP allows converting variables from one data type to another.
PHP is a loosely typed language, so variables are automatically
assigned data types based on their values.
<?php
$var = 10; // Integer
$var = "PHP"; // String
$var = true; // Boolean
?>
Typecasting in PHP is the process of converting a variable
from one data type to another. Since PHP is a loosely typed
language, it automatically converts variables to the
required data type when performing certain operations.
However, there are times when you might need to
explicitly change the type of a variable using typecasting.
Syntax for Typecasting
The syntax for typecasting in PHP involves placing the
desired data type in parentheses before the variable or
value:
$new_variable = (type) $variable;
Examples of Typecasting
1. Integer Casting
Converts a variable to an integer.
<?php
$ loat = 10.5;
$integer = (int)$ loat; // Explicitly casting to an integer
echo $integer; // Outputs: 10
?>
2. Float Casting
Converts a variable to a loating-point number.
<?php
$string = "3.14";
$ loat = ( loat)$string; // Casting to loat
$a = 15;
$b = 3;
$result = $a / $b;
echo $result; // Outputs: 5
?>
5. Modulus (%)
Returns the remainder after dividing one number by
another.
<?php
$a = 10;
$b = 3;
$result = $a % $b;
echo $result; // Outputs: 1
?>
6. Exponentiation (**)
Raises one number to the power of another.
<?php
$a = 2;
$b = 3;
$result = $a ** $b;
echo $result; // Outputs: 8 (2³)
?>
Assignment operators
Assignment operators in PHP are used to assign values to
variables. The simplest assignment operator is the equals
sign (=), but PHP also provides compound assignment
operators that combine arithmetic or bitwise operations
with assignment.
Examples of Compound Assignment Operators
1. Addition Assignment (+=)
<?php
$x = 10;
$x += 5; // Equivalent to $x = $x + 5
echo $x; // Outputs: 15
?>
2. Subtraction Assignment (-=)
<?php
$x = 10;
$x -= 3; // Equivalent to $x = $x - 3
echo $x; // Outputs: 7
?>
$b = "5";
var_dump($a === $b); // Outputs: bool(false) (values are equal,
but types are different)
?>
3. Not Equal (!= or <>)
<?php
$a = 5;
$b = 10;
var_dump($a != $b); // Outputs: bool(true) (values are not
equal)
?>
4. Not Identical (!==)
<?php
$a = 5;
$b = "5";
var_dump($a !== $b); // Outputs: bool(true) (values are equal,
but types are different) ?>
5. Less Than (<)
<?php
$a = 3;
$b = 7;
var_dump($a < $b); // Outputs: bool(true)
?>
6. Greater Than (>)
<?php
$a = 10;
$b = 7;
var_dump($a > $b); // Outputs: bool(true)
?>
7. Spaceship Operator (<=>)
The spaceship operator is used to compare two values. It
returns:
<?php
echo 5 <=> 10; // Outputs: -1 (5 is less than 10)
echo 10 <=> 10; // Outputs: 0 (10 is equal to 10)
echo 15 <=> 10; // Outputs: 1 (15 is greater than 10)
?>
Increment/Decrement operators
PHP provides increment and decrement operators to increase
or decrease a variable's value by 1. These operators are
commonly used in loops, counters, and arithmetic operations.
1. Pre-Increment (++$x)
Increments the value of $x before it is used.
<?php
$x = 5;
echo ++$x; // Outputs: 6
echo $x; // Outputs: 6
?>
2. Post-Increment ($x++)
Returns the current value of $x, then increments it.
<?php
$x = 5;
echo $x++; // Outputs: 5
echo $x; // Outputs: 6
?>
3. Pre-Decrement (--$x)
Decrements the value of $x before it is used.
<?php
$x = 5;
echo --$x; // Outputs: 4
echo $x; // Outputs: 4
?>
4. Post-Decrement ($x--)
Returns the current value of $x, then decrements it.
<?php
$x = 5;
echo $x--; // Outputs: 5
echo $x; // Outputs: 4
?>
Logical operators
1. Logical AND (&& or and)
The AND operator returns true only if both conditions are true.
<?php
$x = 10;
$y = 20;
var_dump($x > 5 && $y < 30); // Outputs: bool(true)
var_dump($x > 15 && $y < 30); // Outputs: bool(false)
?>
2. Logical OR (|| or or)
The OR operator returns true if at least one condition is true.
<?php
$x = 10;
$y = 20;
var_dump($x > 5 || $y < 15); // Outputs: bool(true)
var_dump($x > 15 || $y < 15); // Outputs: bool(false)
?>
3. Logical NOT (!)
The NOT operator negates the result of a condition. It returns
true if the condition is false, and false if the condition is true.
<?php
$x = 10;
var_dump(!($x > 5)); // Outputs: bool(false)
var_dump(!($x < 5)); // Outputs: bool(true) ?>
4. Logical XOR (xor)
The XOR operator returns true if exactly one of the conditions is
true, but not both.
<?php
$x = 10;
$y = 20;
var_dump($x > 5 xor $y < 10); // Outputs: bool(true)
var_dump($x > 5 xor $y < 30); // Outputs: bool(false)
?>
String operators
In PHP, string operators are used to manipulate and combine
strings. PHP provides two primary string operators:
1. Concatenation Operator (.)
The concatenation operator (.) is used to join two or more
strings into a single string.
<?php
$greeting = "Hello";
$name = "John";
$message = $greeting . " " . $name . "!";
echo $message; // Outputs: Hello John!
?>
In this example:
The strings "Hello", " ", "John", and "!" are concatenated into one
string: "Hello John!".
2. Concatenation Assignment Operator (.=)
Associativity in PHP
break;
}
Key Points
The expression is evaluated once.
Each case checks whether the expression matches the given
value.
The break statement exits the switch block; otherwise,
execution continues to the next case (this is called fall-through
behavior).
The default block is optional and is executed if none of the case
values match.
Example: Simple Calculator
$operation = '+';
$num1 = 10;
$num2 = 5;
switch ($operation) {
case '+':
echo $num1 + $num2;
break;
case '-':
echo $num1 - $num2;
break;
case '*':
echo $num1 * $num2;
break;
case '/':
if ($num2 != 0) {
echo $num1 / $num2;
} else {
echo "Cannot divide by zero.";
}
break;
default:
echo "Invalid operation.";
break;
}
PHP Loops and branching statements
1. while
Examples
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo "Color: $color<br>";
}
Output:
Color: Red
Color: Green
Color: Blue
5. Break statement
The break statement in PHP is used to terminate a loop or
switch statement immediately, regardless of the iteration
or condition. It is useful for prematurely stopping a loop
or exiting a switch case.
Usage Scenarios
1. In Loops
The break statement stops the current loop and moves
control to the code immediately following the loop.
Example: Stopping a Loop
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Exit the loop when $i equals 5
} echo "Number: $i<br>"; }
Output
Number: 1
Number: 2
Number: 3
Number: 4
6. Continue statement
The continue statement in PHP is used to skip the rest of
the current iteration of a loop and proceed to the next
iteration. It is commonly used when a certain condition is
met, and you want to skip executing the remaining code
within the loop body for that iteration.
1. In Loops
The continue statement skips the rest of the loop's code
for the current iteration and jumps to the next iteration.
Example: Skipping Speci ic Iterations
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skip the iteration when $i equals 3