PHP was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1994. The PHP reference implementation is now produced by The PHP Group. PHP originally stood for Personal Home Page but now it stands for the recursive acronym, PHP: Hypertext Preprocessor. Popular websites like Facebook, Yahoo, Wikipedia etc. are developed using PHP.
PHP is a widely-used open source general-purpose scripting language for web development. It allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications. It’s a versatile language used extensively in web development for creating dynamic and interactive web applications.
PHP is a server side scripting language that is embedded into HTML. PHP code is executed on the server, generating HTML content that is then sent to the client’s web browser for display. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. PHP is mainly focused on server-side scripting so we can collect form data, generate dynamic page content, or send and receive cookies. Code is executed in a server that is why we will have to install a sever-like environment enabled by programs like XAMPP which is an Apache distribution.
XAMPP Setup:
XAMPP is a free and open source cross-platform web server solution developed by Apache Friends, consisting mainly of the Apache HTTP Server, MariaDB database, and interpreters for scripts written in the PHP and Perl programming languages. In order to make your PHP code execute locally, first install XAMPP.
• Download XAMPP
• Install the program (check the technologies we want during installation)
• Open XAMPP and click on “Start” on Apache and MySQL (when working with databases)
Characteristics of PHP:
Five important characteristics make PHP’s practical nature possible:
· Simplicity
· Efficiency
· Security
· Flexibility
· Familiarity
Advantages of PHP:
Since PHP is designed for the web in the first place, it brings many advantages to web development:
- Simple: PHP is quite easy to learn and get started.
- Fast: PHP websites typically run very fast.
- Stable: PHP is stable since it has been in existence for a long time.
- Open-source and free: PHP is open source and free. It means that you don’t have to pay a license fee to use PHP to develop software products.
- Community support: PHP has an active online community that helps us whenever we face an issue.
Features of PHP
Here are some Key Features (characteristics) of PHP:
- Server-Side Scripting: PHP is primarily used for server-side scripting, meaning that the PHP code is executed on the server before the result is sent to the client’s web browser. This allows for dynamic content generation and interaction with databases.
- Open Source: PHP is an open-source language, which means it is free to use, distribute, and modify. This has contributed to its widespread adoption and the development of a large community of users and contributors.
- Cross-Platform Compatibility: PHP runs on various operating systems, including Windows, Linux, macOS, and others, making it highly versatile and accessible.
- Integration: PHP can be seamlessly integrated with various web servers (such as Apache and Nginx), as well as with different database management systems (such as MySQL, PostgreSQL, and MongoDB).
- Ease of Learning: PHP syntax is similar to C, Java, and Perl, making it relatively easy for programmers with experience in those languages to pick up. Additionally, there is a vast amount of documentation, tutorials, and resources available for learning PHP.
- Powerful and Flexible: PHP offers a wide range of features for web development, including but not limited to, form handling, file handling, session management, encryption, and authentication. It can also be extended with additional libraries and frameworks to suit various needs.
- Scalability: PHP is capable of handling both small-scale and large-scale web applications, making it suitable for projects of all sizes.
- Community Support: PHP has a large and active community of developers who contribute to its ongoing development, share knowledge, provide support, and create libraries and frameworks to enhance its functionality.
Uses of PHP:
Here are a few applications of PHP:
Server-side scripting: This is the most used and main target for PHP. We need three things to make this work the way you need it. The PHP parser (CGI or server module), a web server and a web browser. We need to run the web server where. We can access the PHP program output with a web browser, viewing the PHP page through the server.
Command line scripting: We can make a PHP script to run it without any server or browser. We only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks.
Writing desktop applications: PHP may not the very best language to create a desktop application with a graphical user interface, but if we know PHP very well, and would like to use some advanced PHP features in client-side applications we can also use PHP-GTK to write such programs. We also have the ability to write cross-platform applications this way.Â
Â
How PHP Works:
- First, the web browser sends an HTTP request to the web server, e.g., index.php.
- Second, the PHP preprocessor that locates on the web server processes PHP code to generate the HTML document.
- Third, the web server sends the HTML document back to the web browser.
Syntax of PHP:
PHP code is typically embedded within HTML markup using special delimiters <?php
and ?>
. For example:
<?php
echo “Hello, World!”;
?>
Variables in PHP:
In PHP, variables are used to store data values. These values can be of various types, such as strings, integers, floats, booleans, arrays, or objects. PHP variables follow a few rules:
- Variable Naming:
- Variable names in PHP must start with a dollar sign
$
, followed by the name of the variable. - Variable names can contain letters, numbers, or underscores.
- Variable names cannot start with a number or contain spaces.
- Variable names are case-sensitive.
- Variable names in PHP must start with a dollar sign
- Variable Assignment:
- Variables in PHP are assigned values using the assignment operator
=
, with the variable on the left-hand side and the expression to be evaluated on the right. - Variables can, but do not need, to be declared before assignment.
- Variables in PHP are assigned values using the assignment operator
Declaring and Assigning values to variables:
PHP is loosely typed, meaning we don’t have to declare the data type of a variable when we create one. Here’s a basic example of declaring and assigning values to variables in PHP:
$name = “Samuel”;
$age = 20;
A simple program to show the use of variable in a program
<?php
$name = “Rahul”; // string
$age = 25; // integer
$height = 5.11; // float
$isStudent = true; // boolean
// Outputting variables
echo “Name: ” . $name . “<br>”;
echo “Age: ” . $age . “<br>”;
echo “Height: ” . $height . “<br>”;
echo “Is Student: ” . ($isStudent ? ‘Yes’ : ‘No’) . “<br>”;
?>
Output:
Name: Rahul
Age: 25
Height: 5.11
Is Student: Yes
Variable Scope:
- PHP supports different scopes for variables: global and local.
- Variables declared outside of a function have global scope and can be accessed from anywhere in the script.
- Variables declared inside a function have local scope and can only be accessed within that function, unless explicitly stated otherwise.
Example of Variable Scope:
<?php
$globalVariable = “I am global”;
function myFunction() {
$localVariable = “I am local”;
echo $localVariable; // This will work
echo $globalVariable; // This will throw an error
}
echo $globalVariable; // This will work
echo $localVariable; // This will throw an error
?>
Output:
I am global
Warning: Undefined variable $localVariable in C:\xampp\htdocs\scope.php on line 17
Data Types:
PHP supports various data types including integers, floats, strings, booleans, arrays, and objects.
The main data types used to construct variables are:
• Integers: whole numbers like 23, 1254, 964 etc
• Doubles: floating-point numbers like 46.2, 733.21 etc
• Booleans: only two possible values, true or false
• Strings: set of characters, like ‘PHP supports string’
• Arrays: named and indexed collections of other values
• Objects: instances of predefined classes
- PHP is loosely typed, meaning we don’t have to declare the data type of a variable when we create one.
- PHP automatically converts the variable to the correct data type, depending on its value.
- We can use the gettype() function to determine the data type of a variable.
<?php
$var = “Hello”; // string
echo gettype($var); // Outputs: string
echo ” “;
$var = 42; // integer
echo gettype($var); // Outputs: integer
echo ” “;
$var = 3.14; // float
echo gettype($var); // Outputs: double
echo ” “;
$var = true; // boolean
echo gettype($var); // Outputs: boolean
?>
Output:
string integer double boolean
Operators :
In PHP, operators are used to perform operations on variables and values. PHP supports a wide range of operators, including :
· Arithmetic Operators
· Assignment Operators
· Comparison Operators
· Logical Operators
· String Operators
· Increment/Decrement Operators
· Conditional (or ternary) Operators
Here’s an overview of the different types of operators in PHP:
Arithmetic Operators:
Used to perform mathematical operations such as addition, subtraction, multiplication, division, modulus, and exponentiation.
Example:
<?php
$x = 10;
$y = 5;
echo $x + $y; // Outputs: 15
echo $x – $y; // Outputs: 5
echo $x * $y; // Outputs: 50
echo $x / $y; // Outputs: 2
echo $x % $y; // Outputs: 0 (remainder of division)
?>
Output:
15 5 50 2 0
Assignment Operators:
Used to assign values to variables, with the additional ability to perform an operation at the same time.
Example:
<?php
$x = 10;
$y = 5;
$x += $y; // Equivalent to: $x = $x + $y;
echo $x; // Outputs: 15
$x -= $y; // Equivalent to: $x = $x – $y;
echo $x; // Outputs: 10
?>
Output:
15 10
Comparison Operators:
Used to compare two values or expressions and return a boolean result (true or false).
Example:
<?php
$x = 10;
$y = 5;
echo $x == $y; // Outputs: false
echo $x != $y; // Outputs: true
echo $x > $y; // Outputs: true
echo $x < $y; // Outputs: false
echo $x >= $y; // Outputs: true
echo $x <= $y; // Outputs: false
?>
Output:
111
Logical Operators:
Used to combine conditional statements.
Example:
<?php
$x = true;
$y = false;
echo $x && $y; // Outputs: false (logical AND)
echo $x || $y; // Outputs: true (logical OR)
echo !$x; // Outputs: false (logical NOT)
?>
Output:
1
String Operators:
Used to concatenate strings. There are two string operators : concatenation operator (‘.’) and concatenating assignment operator (‘.=’).
Example : PHP string concatenation operator
<?php
$x=”Hello”;
$y=$x .” World”;
// now $y contains “Hello World”
echo $y;
?>
Output:
Hello World
Example: PHP string concatenating assignment operator
<?php
$x= “Hello”;
$x.=” World”;
echo $x;
Output:
Hello World
Increment/Decrement Operators:
Used to increment or decrement the value of a variable.
Example:
<?php
$x = 5;
echo ++$x; // Outputs: 6 (pre-increment)
echo $x++; // Outputs: 6 (post-increment)
echo – -$x; // Outputs: 6 (pre-decrement)
echo $x- -; // Outputs: 6 (post-decrement)
?>
Output:
6 6 6 6
Conditional (Ternary) Operator:
Used to assign a value to a variable based on a condition.
Example:
<?php
$x = 10;
$y = ($x > 5) ? “greater than 5” : “less than or equal to 5”;
echo $y; // Outputs: greater than 5
?>
Output:
greater than 5
Conditional Statement (Control Structures)
Conditional statements are used to execute different code based on different conditions. PHP supports common control structures like if…else, switch, while, for, foreach, etc., similar to many other programming languages.
If Statement:
The if statement executes a piece of code if a condition is true.
Syntax:
if (condition)
{
// code to be executed in case the condition is true
}
Example:
<?php
$year=2020;
if($year %4==0)
{
echo “$year is a leap year”;
}
?>
Output:
2020 is a leap year
If. . . Else statement :
The If. . . Else statement executed a piece of code if a condition is true and another piece of code if the condition is false.
Syntax:
if (condition)
{
// code to be executed in case the condition is true
}
else
{
// code to be executed in case the condition is false
}
Example:
<?php
$num=12;
if($num%2==0)
{
echo “$num is even number”;
}
else
{
echo “$num is odd number”;
}
?>
Output:
12 is even number
If. . . else if. . . else statement:
This kind of statement is used to define what should be executed in the case when two or more conditions are present.
Syntax:
if (condition1)
{
// code to be executed in case condition1 is true
}
else if (condition2)
{
// code to be executed in case condition2 is true
}
else
{
// code to be executed in case all conditions are false
}
Example:
<?php
$marks=80;
if ($marks<40)
{
echo “fail”;
}
else if ($marks>=40 && $marks<50)
{
echo “D grade”;
}
else if ($marks>=50 && $marks<60)
{
echo “C grade”;
}
else if ($marks>=60 && $marks<70)
{
echo “B grade”;
}
else if ($marks>=70 && $marks<80)
{
echo “A grade”;
}
else if ($marks>=80 && $marks<100)
{
echo “A+ grade”;
}
else
{
echo “Invalid input”;
}
?>
Output:
A+ grade
Looping : (Loops in PHP)
In PHP, just like any other programming language, loops are used to execute the same code block for a specified number of times. Except for the common loop types (for, while, do. . . while), PHP also support foreach loops.
For Loop:
The for loop is used when the programmer knows in advance how many times the block of code should be executed. This is the most common type of loop encountered in almost every programming language.
Syntax:
for(initialization; condition; update expressein)
{
//code to be executed
}
Example:
<? php
for($x=1;$x<=10;$x++)
{
echo “The number is: $x <br>”;
}
?>
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
Example:
<?php
for($x=10;$x<=100;$x=$x+10)
{
echo “The number is: $x <br>”;
}
?>
Output:
The number is: 10
The number is: 20
The number is: 30
The number is: 40
The number is: 50
The number is: 60
The number is: 70
The number is: 80
The number is: 90
The number is: 100
While Loop:
The while loop is used when we want to execute a block of code as long as a test expression continues to be true.
Syntax:
while(condition)
{
//code to be executed
}
Example:
<?php
$x=1;
while($x <=10)
{
echo ” The number is : $x <br>”;
$x++;
}
?>
Output:
The number is : 1
The number is : 2
The number is : 3
The number is : 4
The number is : 5
The number is : 6
The number is : 7
The number is : 8
The number is : 9
The number is : 10
Do. . . While loop:
The do…while loop is used when we want to execute a block of code at least once and then as long as a test expression is true.
Syntax:
do
{
//code to be executed
}
while(condition);
Example:
<?php
$x=1;
do
{
echo “The number is: $x <br>”;
$x++;
}
while($x<=10);
?>
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
Foreach Loop:
It works only on array and object. It will issue an error if you try to use it with the variables of different datatype. It provides an easiest way to iterate the elements of an array.
Syntax:
foreach ($array as $value)
{
code to be executed;
}
Example:
<?php
//declare array
$days= array(“Sunday”,”Monday”,”Tuesday”,”Wednesday”, “Thursday”,”Friday”,”Saturday”);
//access array elements using foreach loop
foreach($days as $value)
{
echo “$value <br>”;
}
?>
Output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Arrays:
In PHP, an array is a data structure that stores one or more values in a single variable. Arrays can hold multiple values of different data types, such as integers, strings, or even other arrays. PHP supports several types of arrays, including indexed arrays, associative arrays, and multidimensional arrays. Here’s an overview of each type:
Indexed Arrays:
- An indexed array stores a collection of values, each identified by an index or position.
- The index starts from 0 for the first element and increments by 1 for each subsequent element.
- Indexed arrays are created using square brackets
[]
or thearray()
function.
Example:
<?php
// Using square brackets
$colors = [“Red”, “Green”, “Blue”];
// Using the array() function
$fruits = array(“Apple”, “Banana”, “Orange”);
// Accessing elements
echo $colors[0]; // Outputs: Red
echo $fruits[1]; // Outputs: Banana
?>
Output:
Red Banana
Associative Arrays:
- An associative array stores key-value pairs, where each key is associated with a specific value.
- Keys can be strings or integers.
- Associative arrays are created using the
array()
function or using the[]
syntax with key-value pairs.
Example:
<?php
// Using the array() function
$person = array(“name” => “John”, “age” => 30, “city” => “New York”);
// Using square brackets with key-value pairs
$book = [“title” => ” PHP Programming”, “author” => ” Smith”, “pages” => 300];
// Accessing elements
echo $person[“name”]; // Outputs: John
echo $book[“author”]; // Outputs: John Smith
?>
Output:
John Smith
Multidimensional Arrays:
- A multidimensional array is an array of arrays, allowing you to store arrays within an array.
- This creates a matrix-like structure with rows and columns.
- Multidimensional arrays can be indexed or associative.
Example:
<?php
// Indexed multidimensional array
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9] ];
// Associative multidimensional array
$employees = [
[“name” => “John”, “age” => 30],
[“name” => “Alice”, “age” => 25],
[“name” => “Bob”, “age” => 35]
];
// Accessing elements
echo $matrix[0][1]; // Outputs: 2
echo $employees[1][“name”]; // Outputs: Alice
?>
Output:
2 Alice
Functions:
A function is a block of code that performs a specific task and can be reused throughout your code. Functions help to organize and modularize code, making it easier to read, understand, and maintain. PHP provides several built-in functions, and you can also create your own custom functions. Here’s an overview of how functions work in PHP:
Defining Functions:
We can define a function using the function keyword, followed by the function name and parentheses containing any parameters the function accepts. The function body is enclosed within curly braces {}
.
For example:
<?php
// Function without parameters
function greet() {
echo “Hello, World!”;
} // Function with parameters
function add($a, $b) {
return $a + $b; }
?>
Calling Functions:
Once a function is defined, we can call it anywhere in your code by using its name followed by parentheses ()
.
Example:
<?php
// Calling the greet function
greet(); // Outputs: Hello, World!
// Calling the add function
$result = add(5, 3);
echo $result; // Outputs: 8
?>
Programming example:
<?php
// Function without parameters
function greet() {
echo “Hello, World!”;
}
// Function with parameters
function add($a, $b) {
return $a + $b; }
// Calling the greet function
greet(); // Outputs: Hello, World!
// Calling the add function
$result = add(5, 3);
echo “Result ” .$result; // Outputs: 8
?>
Output:
Hello, World!
Result 8
Function Parameters:
Functions can accept parameters, which are variables that are passed into the function when it is called. Parameters can have default values, and you can specify their data types in PHP 7 and later versions.
Example:
<?php
// Function with default parameter
function greetWithName($name = “World”) {
echo “Hello, $name!”;
}
// Function with specified data types (PHP 7+)
function multiply(int $a, float $b): float {
return $a * $b; }
?>
Returning Values:
Functions can return values using the return keyword. You can return any data type, including strings, numbers, arrays, or objects.
Example:
<?php
// Function to calculate the sum of an array
function sumArray($array) {
$sum = 0;
foreach ($array as $value) {
$sum += $value;
}
return $sum;
}
?>
Recursion:
PHP allows functions to call themselves recursively. This is useful for solving problems that can be broken down into smaller, similar sub-problems.
Example:
<?php function factorial($n) {
if ($n === 0) {
return 1;
} else {
return $n * factorial($n – 1);
}
}
?>
Web Server Concept:
A web server is a software application or hardware device responsible for serving web content over the internet. It handles incoming requests from clients (typically web browsers) and responds with the requested web pages, files, or data. Here’s a breakdown of the key concepts related to web servers:
HTTP Protocol:
Hypertext Transfer Protocol (HTTP) is the foundation of data communication on the World Wide Web. It defines how messages are formatted and transmitted, as well as the actions web servers and browsers should take in response to various commands.
Client-Server Model:
- Web communication follows the client-server model, where clients (such as web browsers) request resources or services from servers, and servers respond to these requests.
- Web servers are responsible for processing and fulfilling client requests.
Request-Response Cycle:
- When a client (e.g., a web browser) requests a web page or resource by entering a URL into the address bar, it sends an HTTP request to the web server.
- The web server processes the request, retrieves the requested resource (e.g., an HTML file, image, or database query result), and sends an HTTP response back to the client.
- The client’s web browser then renders the received content for the user to view.
Types of Web Servers:
- Apache HTTP Server: One of the most widely used open-source web servers, known for its flexibility, reliability, and robust features.
- Nginx: A lightweight, high-performance web server and reverse proxy server, favored for its efficiency in handling concurrent connections.
- Microsoft Internet Information Services (IIS): A web server created by Microsoft for use with Windows Server operating systems.
Server-Side Scripting:
- Web servers often support server-side scripting languages like PHP, Python, Ruby, and Node.js. These languages allow dynamic generation of web content based on user input, database queries, or other parameters.
- When a request involves server-side scripting, the web server executes the appropriate script, processes the logic, and generates the HTML content dynamically before sending the response to the client.
Static vs. Dynamic Content:
- Static Content: Refers to web content that remains the same unless modified directly by the webmaster. Examples include HTML files, images, and CSS files.
- Dynamic Content: Generated on-the-fly by web servers or server-side scripts in response to user requests. Examples include dynamically generated web pages, personalized content, and data retrieved from databases.
Security and Configuration:
- Web servers require proper configuration and security measures to protect against vulnerabilities, attacks, and unauthorized access.
- Common security measures include using encryption (e.g., SSL/TLS), implementing firewalls, applying access controls, regularly updating server software, and monitoring server activity.
Scaling and Load Balancing:
- As web traffic increases, web servers may need to scale horizontally by adding more servers to handle the load.
- Load balancers distribute incoming requests across multiple servers to ensure optimal performance, availability, and reliability.