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

Module 5

Uploaded by

chandan kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Module 5

Uploaded by

chandan kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Origins and uses of PHP

PHP, which stands for Hypertext Preprocessor, is a widely used server-side scripting
language designed for web development. It has a long history and has evolved
signi cantly since its inception. Here are the origins and uses of PHP:

Origins of PHP:
• Creation by Rasmus Lerdorf (1994): PHP was originally created by Danish-
Canadian programmer Rasmus Lerdorf in 1994. It began as a set of Common
Gateway Interface (CGI) binaries written in the C programming language to track
visits to his online resume.
• PHP/FI (1995): Rasmus released PHP/FI (Personal Home Page/Forms Interpreter)
in 1995, which included a wider range of functionality. It allowed the creation of
simple dynamic web pages and the ability to interact with databases.
• Introduction of PHP 3 (1998): The next major release was PHP 3, which
introduced a more robust language structure and support for interacting with
databases like MySQL.
• Zend Engine (1999): PHP 4 incorporated the Zend Engine, a scripting engine for
PHP written by Andi Gutmans and Zeev Suraski. This signi cantly improved the
performance and capabilities of PHP.
• PHP 5 and Object-Oriented Programming (2004): PHP 5 introduced extensive
support for object-oriented programming (OOP) and brought improvements in
performance, error handling, and support for XML.
• PHP 7 (2015): PHP 7 marked a signi cant leap in performance with the introduction
of the Zend Engine 3. It brought improvements in speed, memory usage, and
introduced features like scalar type declarations and the spaceship operator.
• PHP 8 (2020): PHP 8 continued the evolution of the language, introducing features
like the Just-In-Time (JIT) compiler, union types, named arguments, and more.

Uses of PHP:
• Web Development:
1. Server-Side Scripting: PHP is primarily used for server-side scripting to
generate dynamic web pages. It can be embedded directly into HTML code.
2. Web Applications: PHP is used to develop web applications, from simple
websites to complex content management systems (CMS) like WordPress,
Joomla, and Drupal.
• Database Interaction:
1. MySQL Integration: PHP has strong support for interacting with MySQL
databases. It is frequently used to perform database operations, such as inserting,
updating, and retrieving data.
• User Authentication and Authorization:
1. PHP is commonly used to implement user authentication systems, managing
user sessions, and controlling access to various parts of a website or web
application.
• Server-Side Utilities:
1. File Handling: PHP can be used for le handling and manipulation on the
server, allowing applications to read, write, and modify les.
• API Development:
fi
fi
fi
fi
fi
1. PHP can be used to develop server-side components of RESTful APIs,
allowing communication between different web services and applications.
• Command-Line Scripting:
1. PHP can be executed from the command line, making it suitable for creating
command-line scripts and automation tasks.
• Content Management Systems (CMS):
1. Many popular CMS platforms, such as WordPress, are built using PHP. It
allows developers to create customizable and dynamic websites without extensive
coding.
• E-commerce Applications:
1. PHP is widely used in the development of e-commerce applications, enabling
the creation of online stores, shopping carts, and payment processing systems.
Overview of PHP

PHP, which originally stood for "Personal Home Page," is a widely used server-side
scripting language designed for web development. Over the years, its meaning has
evolved to "Hypertext Preprocessor." Here's an overview of PHP:

Key Characteristics:
• Server-Side Scripting: PHP is a server-side scripting language, meaning it is
executed on the server before the result is sent to the client's web browser. It is
used to generate dynamic content, interact with databases, and perform various
server-side tasks.
• Open Source: PHP is an open-source language, and its source code is freely
available. This fosters collaboration and community-driven development, resulting in
continuous improvements and updates.
• Cross-Platform Compatibility: PHP is platform-independent and can run on
various operating systems, including Windows, macOS, Linux, and more. It is
compatible with different web servers, such as Apache, Nginx, and Microsoft IIS.
• Interoperability: PHP can easily integrate with various databases (MySQL,
PostgreSQL, SQLite), web servers, and other technologies. It supports numerous
protocols, making it versatile for web development.
• Ease of Learning: PHP has a syntax that is relatively easy to learn, especially for
those with a background in C-style languages. Its simplicity makes it accessible for
beginners while providing powerful features for advanced users.
• HTML Embedded: PHP code is embedded directly within HTML, allowing
developers to mix dynamic server-side logic with static HTML content. This makes it
convenient for creating dynamic web pages.
• Extensibility: PHP supports extensions and modules that enhance its functionality.
These extensions cover a wide range of tasks, from image processing to encryption
and beyond.
• Large Community: PHP has a vast and active community of developers, which
contributes to extensive documentation, libraries, frameworks, and support forums.
The community-driven nature ensures ongoing support and improvement.
Evolution:
• PHP 3 (1998): Initial version with increased functionality beyond its original purpose
of tracking online resume views.
• PHP 4 (2000): Introduction of the Zend Engine, providing better performance and
additional features.
• PHP 5 (2004): Signi cant improvements, including support for object-oriented
programming (OOP), better error handling, and enhanced XML support.
• PHP 7 (2015): Major performance improvements, reduced memory usage, and the
introduction of features like scalar type declarations, return type declarations, and
the spaceship operator.
• PHP 8 (2020): Continued improvements with the introduction of the Just-In-Time
(JIT) compiler, union types, named arguments, and other enhancements.
Use Cases:
• Web Development: PHP is a cornerstone of web development, commonly used for
building websites, web applications, and dynamic content.
• Content Management Systems (CMS): Many popular CMS platforms, including
WordPress, Joomla, and Drupal, are built with PHP.
• E-commerce: PHP is widely used in developing e-commerce solutions, facilitating
the creation of online stores, shopping carts, and payment processing systems.
• Server-Side Scripting: PHP is employed for various server-side scripting tasks,
such as form processing, user authentication, and data manipulation.
• API Development: PHP can be used to develop the server-side components of
RESTful APIs, enabling communication between different services and applications.
• Command-Line Scripting: PHP scripts can be executed from the command line,
making it suitable for automation and scripting tasks.

General syntactic characteristics

PHP has a syntax that is easy to learn, especially for those with a background in C-style
languages. Here are some general syntactic characteristics of PHP:

1. Script Tags:

• PHP code is enclosed in <?php and ?> tags.


• Shorter opening tags (<?) and short echo tags (<?=) are also available but
may be disabled in some environments.

<?php
// PHP code here
?>

Comments:

• PHP supports both single-line (//) and multi-line (/* */) comments.

<?php
// This is a single-line comment

/*
This is a multi-line comment
fi
spanning multiple lines
*/
?>

Variables:

• Variable names start with a $ sign followed by the name.


• Variable names are case-sensitive.

<?php
$name = "John";
$age = 25;
?>

Data Types:

• PHP has dynamic typing, meaning you do not need to declare the data type
of a variable.
• Common data types include strings, integers, oats, booleans, arrays, and
objects.

<?php
$name = "John"; // String
$age = 25; // Integer
$height = 5.9; // Float
$isStudent = true; // Boolean
$colors = array("Red", "Green", "Blue"); // Array
?>

Strings:

• Strings can be declared using single (') or double (") quotes.


• Variable interpolation is possible in double-quoted strings.

<?php
$name = "John";
echo 'Hello, ' . $name . '!'; // Single-quoted
echo "Hello, $name!"; // Double-quoted with variable interpolation
?>

Operators:

• PHP supports various operators, including arithmetic, comparison, logical,


and string concatenation.
fl
<?php
$result = 10 + 5; // Addition
$isGreater = 10 > 5; // Comparison
$logicalAnd = true && false; // Logical AND
$concatenated = "Hello " . "World"; // String concatenation
?>

Control Structures:

• PHP supports common control structures like if statements, loops (for, while,
do-while), and switch statements.

<?php
$x = 10;

if ($x > 0) {
echo "Positive";
} else {
echo "Non-positive";
}

// Loop
for ($i = 0; $i < 5; $i++) {
echo $i;
}
?>

Functions:

• Functions are declared using the function keyword.


• Function names are case-insensitive.

<?php
function greet($name) {
echo "Hello, $name!";
}

greet("John");
?>

Arrays:

• Arrays can be indexed or associative.


• PHP provides many array functions for manipulation.
<?php
$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Accessing array elements

$person = array("name" => "John", "age" => 25);


echo $person["name"]; // Associative array
?>

Include and Require:

• PHP includes other PHP les using include or require.


• include produces a warning if the le is not found, while require produces a
fatal error.

<?php
include "header.php";
require "functions.php";
?>

Output in php

With eco variables


<?php
$name = "John";
echo "Hello, $name!";
// or
echo 'Hello, ' . $name . '!';
?>

With Html Variable


<?php
echo "<h1>This is a heading</h1>";
echo "<p>This is a paragraph.</p>";
?>

Control statements in php

In PHP, control statements are used to control the ow of execution


in a script. They allow you to make decisions, repeat actions, and
perform different actions based on conditions. Here are some of the
key control statements in PHP:

if Statement:

• The if statement is used to execute a block of code only


if a speci ed condition is true.
fi
fi
fi
fl
<?php
$x = 10;

if ($x > 5) {
echo "x is greater than 5";
}
?>

if-else Statement:
The if-else statement allows you to execute one block of code if the
condition is true and another block if the condition is false.

<?php
$x = 10;

if ($x > 5) {
echo "x is greater than 5";
} else {
echo "x is not greater than 5";
}
?>

if-elseif-else Statement:
This statement allows you to test multiple conditions and execute
different blocks of code based on the rst condition that is true.

<?php
$x = 10;

if ($x > 10) {


echo "x is greater than 10";
} elseif ($x == 10) {
echo "x is equal to 10";
} else {
echo "x is less than 10";
}
?>
fi
switch Statement:
The switch statement is used to perform different actions based on
different conditions.

<?php
$day = "Monday";

switch ($day) {
case "Monday":
echo "It's the start of the week";
break;
case "Friday":
echo "It's almost the weekend";
break;
default:
echo "It's just another day";
}
?>

while Loop:
The while loop executes a block of code as long as the speci ed
condition is true.
<?php
$i = 1;

while ($i <= 5) {


echo $i . " ";
$i++;
}
?>

for Loop:
The for loop is used to iterate a block of code a speci ed number of
times.

<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
fi
fi
}
?>

foreach Loop:
The foreach loop is used to iterate over elements in an array.
<?php
$colors = array("red", "green", "blue");

foreach ($colors as $color) {


echo $color . " ";
}
?>

Arrays in php

In PHP, an array is a versatile data structure that allows you to store


multiple values in a single variable. Each value in an array is
assigned a unique key, which can be either an index (numeric or
associative) or a string. Here are some fundamental aspects of
working with arrays in PHP:

1. Numeric Arrays:
Numeric arrays use sequential numbers as keys.

<?php

$numericArray = array(1, 2, 3, 4, 5);

// or, using the shorthand syntax in PHP 5.4 and later

$numericArray = [1, 2, 3, 4, 5];

// Accessing elements

echo $numericArray[0]; // Outputs 1


?>

Associative Arrays:
Associative arrays use named keys.

<?php

$assocArray = array(

"name" => "John",

"age" => 30,

"city" => "New York"

);

// or, using the shorthand syntax

$assocArray = [

"name" => "John",

"age" => 30,

"city" => "New York"

];

// Accessing elements

echo $assocArray["name"]; // Outputs John

Multidimensional Arrays:
Arrays can contain other arrays, creating multidimensional arrays.

<?php

$multiArray = array(

array(1, 2, 3),

array("apple", "orange", "banana"),

array("a", "b", "c")

);

// Accessing elements

echo $multiArray[0][1]; // Outputs 2

echo $multiArray[1][2]; // Outputs banana

Array Functions:
PHP provides a variety of built-in functions to manipulate arrays.

• count(): Returns the number of elements in an array.


• array_push(): Adds one or more elements to the end of an array.
• array_pop(): Removes and returns the last element of an array.
• array_merge(): Merges one or more arrays into a single array.

<?php
$numbers = [1, 2, 3];

// Adding an element
array_push($numbers, 4);

// Removing the last element


$lastElement = array_pop($numbers);

// Merging arrays
$newArray = array_merge($numericArray, $assocArray);
?>
Functions in PHP

In PHP, a function is a block of reusable code that performs a


speci c task. Functions help in organizing code, making it more
modular and easier to maintain. Here's a guide to creating and
using functions in PHP:

De ning a Function:
You can de ne a function using the function keyword. The basic
syntax is as follows:

<?php
function greet($name) {
echo "Hello, $name!";
}

greet("John"); // Outputs: Hello, John!


?>

Function Parameters:
Functions can accept parameters (input values). These parameters
are listed within the parentheses after the function name

<?php

function add($a, $b) {

$sum = $a + $b;

return $sum;

$result = add(5, 3); // $result now holds the value 8

?>
fi
fi
fi
Variable Scope:
Variables de ned inside a function have local scope, meaning they
are only accessible within that function. You can use the global
keyword to access global variables.

<?php

$globalVar = "I'm global";

function example() {

global $globalVar;

echo $globalVar;

/example(); // Outputs: I'm global

Pattern Matching in php

In PHP, you can use various functions and techniques for pattern matching. Here are
some commonly used methods:

1. Regular Expressions:
PHP supports regular expressions through the preg_match() function. Regular
expressions allow you to de ne complex search patterns. Here's a simple example:

$text = "Hello, World!";

if (preg_match("/Hello/", $text)) {

echo "Pattern found!";} else {

echo "Pattern not found!";

}
fi
fi
Regular Expressions in PHP:
Regular expressions, often abbreviated as regex or regexp, are sequences of characters
that de ne a search pattern. They are particularly useful for complex pattern matching and
manipulation of strings. PHP supports regular expressions through the preg_* functions.

Here's a more detailed explanation using the preg_match() function:

preg_match() Function:
The preg_match() function is used to perform a pattern match on a string using a
regular expression. It returns true if the pattern is found in the string, and false otherwise.

The preg_match() function returns true because the pattern "Hello" is


found in the given text.

Regular Expression Modi ers:


Regular expressions can include modi ers that affect the matching behavior. For example,
the "i" modi er makes the pattern case-insensitive:

$text = "Hello, World!";

if (preg_match("/hello/i", $text)) {

echo "Pattern found!";

} else {

echo "Pattern not found!";

Capturing Groups:
Regular expressions can include capturing groups to extract speci c parts of a matched
string. For example:

$phone_number = "Phone: 123-456-7890";

if (preg_match("/Phone: (\d{3}-\d{3}-\d{4})/", $phone_number, $matches)) {

echo "Phone number found: " . $matches[1];

} else {
fi
fi
fi
fi
fi
echo "Phone number not found!";

2. Pattern Matching with Wildcards:

The fnmatch() function is used for simple pattern matching with


wildcards:

<?php
$input = "[email protected]";
if (fnmatch("abc*", $input)) {
echo "Matched user email prefix!";
} else {
echo "No match found.";
}

?>
3. String Functions:
PHP provides various string functions that can be used for basic pattern matching. For
instance, you can use strpos() to check if a substring is present in another string:

$haystack = "Hello, World!";

$needle = "World";

$position = strpos($haystack, $needle);

if ($position !== false) {

echo "Substring found at position: $position";

} else {

echo "Substring not found!";

}
4. Pattern Matching with strstr() and stristr():
The strstr() function is used to nd the rst occurrence of a substring, and stristr()
is case-insensitive. Both can be used for simple pattern matching:
$var1= "Hello, World!";

$var2= "World";

$restOfString = strstr($var1, $var2);

if ($restOfString !== false) {

echo "Substring found: $restOfString";

} else {

echo "Substring not found!";

Form Handling in PHP

HTML Forms:
HTML forms are used to collect and submit user input on web pages. They are created
using the <form> element and can contain various types of input elements such as text
elds, radio buttons, checkboxes, and buttons. The action attribute in the form speci es
the URL to which the form data will be sent, and the method attribute determines how the
data will be submitted (GET or POST).

<form action="process_form.php" method=“post">

HTTP Methods:
• GET Method:
• Submits form data as part of the URL.
• Limited data capacity (URL length restrictions).
• Data is visible in the URL.
• Suitable for non-sensitive data retrieval.
• POST Method:
• Submits form data in the request body.
• No URL length limitations.
• Data is not visible in the URL.
• Suitable for sensitive data and larger amounts of data.
fi
fi
fi
fi
3. PHP Form Handling:
Superglobals:
• $_GET: Retrieves form data submitted with the GET method.
• $_POST: Retrieves form data submitted with the POST method.
• $_REQUEST: Retrieves data from both GET and POST methods.

$name = $_POST[“name"];

$email = $_POST[“email"];

Form Processing in PHP:


1. Checking Form Submission:
• Use if ($_SERVER["REQUEST_METHOD"] == "POST") to check if the
form is submitted.
2. Retrieving Form Data:
• Use $_POST to retrieve form data.
3. Validation:
• Validate form data to ensure it meets required criteria (e.g., required elds,
valid email addresses).
• Use functions like empty(), isset(), and regular expressions for
validation.

Handling Form Submission:


Processing Logic:
• Implement the logic for processing form data (e.g., saving to a database,
sending emails).
• Perform necessary operations based on the application requirements.

if ($_SERVER["REQUEST_METHOD"] == "POST")

Redirection After Form Submission:


• After processing form data, consider redirecting users to another page.
• This helps prevent form resubmission when users refresh the page.

Files in PHP

PHP provides various functions to handle les. Some common le-related operations
include reading from and writing to les, checking le existence, deleting les, etc. Here
are some examples:
• Reading from a le:

$ leContent = le_get_contents(‘example.txt');
Writing to a le:

$data = "Hello, World!";


fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
le_put_contents('example.txt', $data);

Checking le existence:

if ( le_exists('example.txt')) {
echo 'File exists!';
} else {
echo 'File does not exist.';
}

Deleting a le:

unlink(‘example.txt');

Appending to a le:

$data = "Appended content.";


le_put_contents('example.txt', $data, FILE_APPEND);

Cookies in PHP

Cookies are small pieces of data that can be stored on the user's computer. They are
commonly used to store user preferences, session information, and other data.

Setting a cookie:

setcookie('user', 'John Doe', time() + 3600, '/');

In this example, a cookie named 'user' is set with the value 'John Doe', and it will expire in
one hour (time() + 3600). The last parameter '/' indicates that the cookie is available
across the entire domain.

Accessing a cookie:

$username = $_COOKIE[‘user'];
This retrieves the value of the 'user' cookie and assigns it to the $username variable.

Deleting a cookie:

setcookie('user', '', time() - 3600, ‘/');


This deletes the 'user' cookie by setting its expiration time to the past.

Checking if a cookie exists:

if (isset($_COOKIE['user'])) {
echo 'Cookie exists!';
} else {
echo 'Cookie does not exist.';
}
fi
fi
fi
fi
fi
fi
Difference between JavaScript and PHP

PHP
JavaScript
Currently, it is a full-stack programming It is a server-side
language. It means it can serve both the scripting language. It
client as well as server sites. serves only the
backend of the
website.
It is supportable by every web browser, It is supportable on
such as Mozilla, Google Chrome, and Windows, Linux, Mac,
many more. etc. platforms.
Supported by IIS,
Apache, and Lighttpd
web servers.
It carries less securable code. PHP code is highly
securable.
It requires an environment for accessing It allows easy and
the database. direct access to the
database.
T h e c o d e i s w r i t t e n w i t h i n The code is written
<script>...<script> tags. within <?php....?> tag.
Earlier, javascript was able to create A PHP program is able to
interactive pages for the clients. But, at generate dynamic pages,
send cookies, receive
present, it is able to build real-time games
cookies, collect form
and applications, mobile applications, too.
data, etc.
The extension used to save an external Files are saved using
javascript le is '.js'. '.php' extension.
We can embed the js code in HTML, XML, We can embed the
and AJAX. PHP code only with
HTML.
It supports fewer features. It supports more
advanced features as
compared to
JavaScript.
fi
Popular frameworks of JavaScript are Popular frameworks of
Angular, React, Vue.js, Meteor, etc. PHP are Laravel,
Symfony, FuelPHP,
CakePHP, and many
more.
Websites built in JavaScript are Twitter, Websites built in PHP
LinkedIn, Amazon, etc. are Wordpress,
Tumblr, MailChimp,
iStockPhoto, etc.

You might also like