UNIT1 PHP
UNIT1 PHP
What is PHP
PHP is an open-source, interpreted, and object-oriented scripting language that can be executed
at the server-side. PHP is well suited for web development. Therefore, it is used to develop web
applications (an application that executes on the server and generates the dynamic page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP 8.2 is the
latest version of PHP, which was released on 24 November 2022. Some important points need
to be noticed about PHP are as followed:
o It handles dynamic content, database as well as session tracking for the website.
o You can create sessions in PHP.
o It can access cookies variable and also set cookies.
o It helps to encrypt the data and apply validation.
o PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many more.
o Using PHP language, you can control the user to access some pages of your website.
o As PHP is easy to install and set up, this is the main reason why PHP is the best language
to learn.
o PHP can handle the forms, such as - collect the data from users using forms, save it into
the database, and return useful information to the user. For example - Registration form.
PHP Features
PHP is very popular language because of its simplicity and open source. There are some important
features of PHP given below:
Performance:
PHP script is executed much faster than those scripts which are written in other languages such
as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.
Open Source:
PHP source code and software are freely available on the web. You can develop all the versions
of PHP according to your requirement without paying any cost. All its components are free to
download and use.
PHP has easily understandable syntax. Programmers are comfortable coding with it.
Embedded:
PHP code can be easily embedded within HTML tags and script. PHP was designed to work with
HTML, and as such, it can be embedded into the HTML code.
You can create PHP files without any html tags and that is called Pure PHP file .
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP application
developed in one OS can be easily executed in other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at runtime.
E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
PHP allows us to use a variable without declaring its datatype. It will be taken automatically at the
time of execution based on the type of data it contains on its value.
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft IIS,
etc.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP can do the same work
in a few lines of code. It has maximum control over the websites like you can make changes easily
whenever you want.
Scripting Language
A script or scripting language is a computer language that does not need the compilation step
and is rather interpreted one by one at runtime. It is where the script is written and where
instructions for a run-time environment are written. In contrast to programming languages that
are compiled first before running, scripting languages do not compile the file and execute the file
without being compiled.
Server-side language
Code running in the browser is known as client-side code and is primarily concerned with improving the
appearance and behavior of a rendered web page. This includes selecting and styling UI components,
creating layouts, navigation, form validation, etc. By contrast, server-side website programming mostly
involves choosing which content is returned to the browser in response to requests. The server-side
code handles tasks like validating submitted data and requests, using databases to store and retrieve
data and sending the correct data to the client as required.
Interpreted language
run through a program line by line and execute each command.
Session Tracking
tracks a user's requests and maintains their state. It is a mechanism used to store information on
specific users and in order to recognize these user's requests when they connect to the web
server.
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in
PHP function "echo" to output the text "Hello World!" on a web page:
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
PHP Versions
PHP Version 1.0
• As mentioned before, PHP development started way back in 1994 and was developed
by Rasmus Lerdorf. He used C as a scripting language He originally used them to
maintain his personal homepage. He later extended these code specs to work with web
forms and databases.
• The initial version of PHP, though not very refined gained a lot of popularity by the
developer community when it was released for public usage in 1995.
• As its popularity continued to grow, a formal developer team was formed to work on
the inconsistencies of version 1.
• As PHP’s popularity grew, it attracted the attention of Zeev Suraski and Andi Gutmans.
• In 1997, Zeev Suraski and Andi Gutmans rewrote the internal PHP parser and formed
the basic structure for PHP 3. The official launch of PHP 3 was done in June 1998 once
the public testing was completed.
• Finally, in the year 2000, PHP version 4 powered by Zend Engine 1 was released for
public usage.
• By 2008, PHP version 4 had evolved and reached 4.4.9. However, it is no more
supported for security updates.
Version 7.0
• During the period of 2016 and 2017, PHP underwent major changes and the update was
released as PHP 7. The version number selected for rolling out this release has to face several
debates.
• In spite of the PHP Unicode project not officially released, several books had referencing
included in them addressing it as PHP version 6. If an actual release would have been also
rolled out as version 6, it would have caused confusion in the developer community. Hence, it
was decided to release this update as version 7.0.
• PHP 7 is based on phpng which stands for PHP next Generation. PHP Next Generation was an
initiative by developers to overcome the high-performance constraints of previous PHP
versions. The phpng branch served as the base branch for PHP version 7.0.
---------------------------------------------------------------------
Installation of PHP
In order to develop and run PHP Web pages three vital components need to be installed on
your computer system.
• Web Server − PHP will work with virtually all Web Server software, including
Microsoft's Internet Information Server (IIS) but then most often used is freely
available Apache Server. Download Apache for free here
− https://httpd.apache.org/download.cgi
• Database − PHP will work with virtually all database software, including Oracle
and Sybase but most commonly used is freely available MySQL database.
Download MySQL for free here − https://www.mysql.com/downloads/
• PHP Parser − In order to process PHP script instructions a parser must be installed
to generate HTML output that can be sent to the Web Browser.
Early years when the servers are costly we have to setup a local environment for php by
installing and configuring apache serve and sql data base in our system but now by the
introduction of XAMMP and WAMMP server we did not do it separately or manually. To run
PHP for the web, we need to install a web server like Apache and a database like MySQL – and
both are supported by XAMPP.
XAMPP is a local server that can run smoothly on our personal computer, and is accepted in
both Windows and Linux. It also helps you test websites and see if they work before actually
publishing them to a web server.
PHP Variables
Variables in a program are used to store some values or data that can be used later in a program.
The variables are also like containers that store character values, numeric values, memory
addresses, and strings
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important
points to know about variables:
o As PHP is a loosely typed language, so we do not need to declare the data types of the
variables. It automatically analyzes the values and makes conversions to its correct
datatype.
o After declaring a variable, it can be reused throughout the code.
o Assignment Operator (=) is used to assign the value to a variable.
$variablename=value;
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a number or special
symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as different
variable.
1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>
Output:
string is: hello string
integer is: 200
float is: 44.6
-----------------------------------------------
1. Boolean
2. Integer
3. Double
4. String
1. Array
2. Objects
2. Resource
The first five are called simple data types and the last three are compound data types:
1. Integer: Integers hold only whole numbers including positive and negative numbers, i.e.,
numbers without fractional part or decimal point. range of integers must lie between -
2^31 to 2^31.
2. Double: Can hold numbers containing fractional or decimal parts including positive and
negative numbers or a number in exponential form. By default, the variables add a
minimum number of decimal places. The Double data type is the same as a float as
floating-point numbers or real numbers.
$val1 = 50.85;
$val2 = 654.26;
3. String: Hold letters or any alphabets, even numbers are included. These are written within
double quotes during declaration. The strings can also be written within single quotes, but
they will be treated differently while printing variables.
$name = "Krishna";
echo "The name of the Geek is $name \n";
4. Boolean: Boolean data types are used in conditional testing. Hold only two values, either
TRUE(1) or FALSE(0). Successful events will return true and unsuccessful events return false.
NULL type values are also treated as false in Boolean. Apart from NULL, 0 is also considered
false in boolean. If a string is empty then it is also considered false in boolean data type.
<?php
if(TRUE)
5. Array: Array is a compound data type that can store multiple values of the same data type.
Below is an example of an array of integers. It combines a series of data that are related
together.
<?php
?>
6. Objects: Objects are defined as instances of user-defined classes that can hold both
values and functions and information for data processing specific to the class. When the
objects are created, they inherit all the properties and behaviours from the class, having
different values for all the properties.
7. NULL: These are special types of variables that can hold only one value i.e., NULL. We
follow the convention of writing it in capital form, but it’s case-sensitive. If a variable is
created without a value or no value, it is automatically assigned a value of NULL. It is
written in capital letters.
<?php
$nm = NULL;
var_dump($nm);
?>
PHP Expression
Almost everything in a PHP script is an expression. Anything that has a value is an expression. In
a typical assignment statement ($x=100), a literal value, a function or operands processed by
operators is an expression, anything that appears to the right of assignment operator (=)
Syntax
PHP Operators
Operators are used to performing operations on some values. In other words, we can describe
operators as something that takes some values, performs some operation on them, and gives a
result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes two values 1 and
2, performs an addition operation on them to give 3.
Just like any other programming language, PHP also supports various types of operations like
arithmetic operations(addition, subtraction, etc), logical operations(AND, OR etc),
Increment/Decrement Operations, etc. Thus, PHP provides us with many operators to perform
such operations on various operands or variables, or values. These operators are nothing but
symbols needed to perform operations of various types. Given below are the various groups of
operators:
Arithmetic Operators
Logical or Relational Operators
Comparison Operators
Conditional or Ternary Operators
Assignment Operators
Spaceship Operators (Introduced in PHP 7)
Array Operators
Increment/Decrement Operators
String Operators
Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical operations like addition,
subtraction, multiplication, etc. Below is the list of arithmetic operators along with their syntax
and operations in PHP.
Operator Name Syntax Operation
These are basically used to operate with conditional statements and expressions. Conditional
statements are based on conditions. Also, a condition can either be met or cannot be met so
the result of a conditional statement can either be true or false. Here are the logical operators
along with their syntax and operations in PHP.
Operator Name Syntax Operation
Logical $x and
and AND $y True if both the operands are true else false
Logical
&& AND $x && $y True if both the operands are true else false
Logical
! NOT !$x True if $x is false
Comparison Operators: These operators are used to compare two elements and outputs the
result in boolean form. Here are the comparison operators along with their syntax and
operations in PHP.
These operators are used to compare two values and take either of the results simultaneously,
depending on whether the outcome is TRUE or FALSE. These are also used as a shorthand
notation for if…else statement that we will read in the article on decision making.
Syntax:
If the condition is true? then $x : or else $y. This means that if the
condition is true then the left result of the colon is accepted
?: Ternary otherwise the result is on right.
Assignment Operators: These operators are used to assign values to different variables, with or
without mid-operations. Here are the assignment operators along with their syntax and
operations, that PHP provides for the operations.
Operator Name Syntax Operation
$x %=
Divide then Assign
%= $y Simple division same as $x = $x % $y
(remainder)
Array Operators: These operators are used in the case of arrays. Here are the array operators
along with their syntax and operations, that PHP provides for the array operation.
Operator Name Syntax Operation
Non- $x !==
!== Identity $y Returns True if both are not identical to each other
Increment/Decrement Operators: These are called the unary operators as they work on single
operands. These are used to increment or decrement values.
String Operators: This operator is used for the concatenation of 2 or more strings using the
concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to
append the argument on the right side to the argument on the left side.
Operator Name Syntax Operation
<?php
$x = "Geeks";
$y = "for"; Output
$z = "Geeks!!!"; GeeksforGeeks!!!
$x .= $y . $z;
echo $x;
?>
Spaceship Operators:
PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship operator
or combined comparison operator is denoted by “<=>“. These operators are used to compare
values but instead of returning the boolean results, it returns integer values. If both the
operands are equal, it returns 0. If the right operand is greater, it returns -1. If the left operand is
greater, it returns 1. The following table shows how it works in detail:
$x <=>
$x < $y $y Identical to -1 (right is greater)
$x <=>
$x > $y $y Identical to 1 (left is greater)
$x >= $x <=> Identical to 1 (if left is greater) or identical to 0 (if both are
$y $y equal)
$x == $x <=>
$y $y Identical to 0 (both are equal)
$x <=>
$x != $y $y Not Identical to 0
<?php
Output
$x = 50;
0
$y = 50;
1
$z = 25;
-1
echo $x <=> $y;
1
echo "\n";
echo "\n"; -1
echo $z <=> $y;
echo "\n";
$x = "Ram";
$y = "Krishna";
echo "\n";
echo "\n";
?>
PHP Constants
Constants are either identifiers or simple names that can be assigned any fixed values. They are
similar to a variable except that they can never be changed. They remain constant throughout the
program and cannot be altered during execution. Once a constant is defined, it cannot be
undefined or redefined. Constant identifiers should be written in upper case following the
convention. By default, a constant is always case-sensitive, unless mentioned. A constant name
must never start with a number. It always starts with a letter or underscores, followed by letter,
numbers or underscore. It should not contain any special characters except underscore, as
mentioned.
Use the define() function to create a constant. It defines constant at run time. Let's see the syntax
of define() function in PHP.
1. <?php Output:
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
Hello JavaTpoint PHP
3. echo MESSAGE, "</br>";
4. echo message; Hello JavaTpoint PHP
5. ?>
PHP introduced a keyword const to create a constant. The const keyword defines constants at
compile time. It is a language construct, not a function. The constant defined using const keyword
are case-sensitive.
1. <?php Output:
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE; Hello const by JavaTpoint PHP
4. ?>
Constant() function
There is another way to print the value of constants using constant() function instead of using the
echo statement.
constant (name)
1. <?php
2. define("MSG", "JavaTpoint"); Output:
3. echo MSG, "</br>"; JavaTpoint
4. echo constant("MSG"); JavaTpoint
5. //both are similar
6. ?>
To use the switch, we need to get familiar with two different keywords namely, break and default.
❖ break: The break statement is used to stop the automatic control flow into the next cases
and exit from the switch case.
❖ default: The default statement contains the code that would execute if none of the cases
match.
6. break;
7. case 20:
8. echo("number is equal to 20"); Output:
9. break;
10. default: number is equal to 20
11. echo("number is not equal to 10, 20 or 30");
12. }
13. ?>
The flow of the program always flow from top to bottom to change the flow of
program on certain condition we use various flow statement
Conditional Statements
• if statements
• if ... else ... statements
• switch Statements --- defined above
Looping Statements
• while loops
• do ... while loops
Conditional Statement
PHP allows us to perform actions based on some type of conditions that may be
logical or comparative. Based on the result of these conditions i.e., either TRUE or
FALSE, an action would be performed as asked by the user. It’s just like a two- way
path. If you want something then go this way or else turn that way. To use this
feature, PHP provides us with four conditional statements:
• if statement
• if…else statement
• if…elseif…else statement
• switch statement
PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is true. If
statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.
Syntax
1. if(condition){
2. //code to be executed
3. }
Flowchart
Example
1. <?php
2. $num=12; Output:
3. if($num<100){ 12 is less than 100
4. echo "$num is less than 100";
5. }
6. ?>
If-else statement is slightly different from if statement. It executes one block of code if the
specified condition is true and another block of code if the condition is false.
Syntax
1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }
Flowchart
Example
1. <?php
2. $num=12;
Output:
3. if($num%2==0){
4. echo "$num is even number"; 12 is even number
5. }else{
6. echo "$num is odd number";
7. }
8. ?>
Syntax
1. if (condition1){
2. //code to be executed if condition1 is true
3. } elseif (condition2){
4. //code to be executed if condition2 is true
5. } elseif (condition3){
6. //code to be executed if condition3 is true
7. ....
8. } else{
9. //code to be executed if all given conditions are false
10. }
Example
1. <?php
2. $marks=69;
3. if ($marks<33){
4. echo "fail"; }
5. else if ($marks>=34 && $marks<50) {
6. echo "D grade";
7. }
8. else if ($marks>=50 && $marks<65) {
9. echo "C grade";
10. }
Output:
11. else if ($marks>=65 && $marks<80) {
12. echo "B grade"; B Grade
13. }
14. else {
15. echo "Invalid input";
16. }
17. ?>
Syntax
1. if (condition) {
2. //code to be executed if condition is true
3. if (condition) {
4. //code to be executed if condition is true
5. }
6. }
Flowchart
Example
1. <?php
2. $age = 23;
3. $nationality = "Indian";
4. //applying conditions on nationality and age
5. if ($nationality == "Indian") Output:
6. { Eligible to give vote
7. if ($age >= 18) {
8. echo "Eligible to give vote";
9. }
10. else {
11. echo "Not eligible to give vote";
12. }
13. }
14. ?>
Like any other language, loop in PHP is used to execute a statement or a block of statements,
multiple times until and unless a specific condition is met. This helps the user to save both time
and effort of writing the same code multiple times.
for loop
while loop
do-while loop
foreach loop
For loop: This type of loops is used when the user knows in advance, how many times the block
needs to execute. That is, the number of iterations is known beforehand. These type of loops
are also known as entry-controlled loops. There are three main parameters to the code, namely
the initialization, the test condition and the counter.
Syntax:
// code to be executed
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some
value, then check whether this variable is less than or greater than counter value. If statement is
true, then loop body is executed and loop variable gets updated . Steps are repeated till exit
condition comes.
Initialization Expression: In this expression we have to initialize the loop counter to some value.
for example: $num = 1;
Test Expression: In this expression we have to test the condition. If the condition evaluates to
true then we will execute the body of loop and go to update expression otherwise we will exit
from the for loop. For example: $num <= 10;
Update Expression: After executing loop body this expression increments/decrements the loop
variable by some value. for example: $num += 2;
Example:
Output:
<?php 1
// code to illustrate for loop 3
for ($num = 1; $num <= 10; $num += 2) { 5
?>
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
32
Flow Diagram:
while loop: The while loop is also an entry control loop like for loops i.e., it first checks the
condition at the start of the loop and if its true then it enters the loop and executes the block of
statements, and goes on executing it as long as the condition holds true.
Syntax:
Example:
Output:
<?php 4
// PHP code to illustrate while loops 6
$num = 2; 8
while ($num < 12) { 10
$num += 2; 12
do-while loop: This is an exit control loop which means that it first enters the loop, executes
the statements, and then checks the condition. Therefore, a statement is executed at least once
on using the do…while loop. After executing once, the program is executed as long as the
condition holds true.
Syntax:
do {
//code is executed
Example:
<?php
?>
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
34
foreach loop: This loop is used to iterate over arrays. For every counter of loop, an array
element is assigned and the next counter is shifted to the next element.
Syntax:
//code to be executed
Example:
<?php Output:
10
$arr = array (10, 20, 30, 40, 50, 60);
20
foreach ($arr as $val) {
30
echo "$val \n"; 40
} 50
$arr = array ("Ram", "Laxman", "Sita"); 60
Ram
foreach ($arr as $val) {
Laxman
echo "$val \n";
Sita
}?>
Note : one more type of loop is nested loop in which we call loop inside the loop. This is most
commonly used in the case of two dimensional array .
--------------------------------------------------------------------------
PHP is designed to work with HTML, so you can easily write and embed PHP code with
HTML. A PHP code block begins with <?php tag and ends with ?> tag.
<?php
//your php code goes here
?>
A code block is a list of statements grouped as one unit. In PHP we use {} to wrap code
blocks and notify the compiler by saying, "hey this is a group of statements." Although
statements cannot be combined like expressions, you can always put a sequence of statements
anywhere a statement can go by enclosing them in a set of curly braces.
if (3 == 2 + 1)
print("lost my mind.");
PHP provides the following methods for printing data in the browser:
1. print()
2. echo()
PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the
argument list. Print statement can be used with or without parentheses: print and print(). Unlike
echo, it always returns 1.
PHP print statement can be used to print the string, multi-line strings, escaping characters,
variable, array, etc. Some important points that you must know about the echo statement are:
o print is a statement, used as an alternative to echo at many times to display the output.
o print can be used with or without parentheses.
o print always returns an integer value, which is 1.
o Using print, we cannot pass multiple arguments.
o print is slower than the echo statement.
o <?php
o print "Hello by PHP print ";
o print ("Hello by PHP print()");
o ?>
PHP Echo
PHP echo is a language construct, not a function. Therefore, you don't need to use parenthesis
with it. But if you want to use more than one parameter, it is required to use parenthesis.
PHP echo statement can be used to print the string, multi-line strings, escaping characters,
variable, array, etc. Some important points that you must know about the echo statement are:
o <?php
o echo "Hello by PHP echo";
o ?>
1. <?php
2. $msg="Hello JavaTpoint PHP";
3. echo "Message is: $msg";
4. ?>
Single-line comments − They are generally used for short explanations or notes relevant to the
local code. Here are the examples of single line comments.
<?
// This is a comment too. Each style comments only print "An example with single line
comments";
?>
Multi-lines comments − They are generally used to provide pseudocode algorithms and more
detailed explanations when necessary. The multiline style of commenting is the same as in C.
Here are the example of multi lines comments.
<?
Subject: PHP */
?>