PHP Programming Unit 1 2 3
PHP Programming Unit 1 2 3
Introduction to PHP:
PHP (Hypertext Preprocessor) is a server-side scripting language that is widely used for web development.
It was first released in 1995 by Rasmus Lerdorf as a set of Common Gateway Interface (CGI) scripts written in C
language for personal use. Over time, it evolved into a more powerful language with a large community of developers
contributing to its development.
PHP is designed to be embedded in HTML and can be used to generate dynamic web pages, handle form data, manage
sessions, and interact with databases. It can also be used to build web applications, content management systems
(CMS), e-commerce platforms, and many other types of web-based software.
Versions of PHP
Here are the major versions of PHP that have been released so far:
PHP 2: This version was released in 1997 and introduced support for accessing databases and cookies.
PHP 3: This version was released in 1998 and added support for object-oriented programming (OOP) and
PHP 4: This version was released in 2000 and added support for sessions, output buffering, and a number
of new extensions.
PHP 5: This version was released in 2004 and introduced significant improvements to OOP, XML support,
and error handling. It also added support for the MySQLi extension for accessing MySQL databases.
PHP 6: This version was under development for many years but was eventually abandoned due to
PHP 7: This version was released in 2015 and introduced significant performance improvements, better error
handling, and a number of new features such as scalar type hints and anonymous classes
PHP 8: This version was released in 2020 and added many new features and improvements, including the JIT
(Just-In-Time) compiler for faster performance, union types, attributes, and improvements to error
PHP 8.2: This version was released in November 2022 and added many new features and improvements like
Read only classes, Random Extension, Allow null, false, and true as stand-alone types etc.
Uses of php
Using php you can restrict user to access specific web page
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.
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.
Advantages of PHP:
1. The most important advantage of PHP is that it’s open-source and free from cost. It can be downloaded
anywhere and is readily available to use for events or web applications.
2. It is platform-independent. PHP-based applications can run on any OS like UNIX, Linux, Windows, etc.
3. Applications can easily be loaded which are based on PHP and connected to the database. It’s mainly used due
to its faster rate of loading over slow internet speed than other programming language.
4. It has less learning curve because it is simple and straightforward to use. Someone familiar with C
programming can easily work on PHP.
5. It is more stable for a few years with the assistance of providing continuous support to various versions.
6. It helps in reusing an equivalent code and not got have to write lengthy code and sophisticated structure for
events of web applications.
7. It helps in managing code easily.
Disadvantages of PHP:
1. It is not that secure due to its open-source, because the ASCII text file is often easily available.
2. It is not suitable for giant content-based web applications.
3. It has a weak type, which can cause incorrect data and knowledge to users.
4. PHP frameworks got to learn to use PHP built-in functionalities to avoid writing additional code.
5. Using more features of PHP framework and tools cause poor performance of online applications.
6. PHP doesn’t allow change or modification in the core behaviour of online applications
7. The PHP frameworks aren’t equivalent in behaviour so does their performance and features.
8. While PHP may be a powerful tool supported by an outsized community and plentiful reference
documentation, there are easier programming languages for web apps.
A static website contains simple HTML pages and supporting files (e.g., Cascading Style Sheets (CSS), JavaScript
(JS)) hosted on a web server. When a site visitor requests a static page, say, by clicking a link, selecting a browser
bookmark, or entering a URL; the web server sends the page directly to the web browser without modifying the final
content of the page.
A dynamic page displays different content for different users while retaining the same layout and design. Such pages,
usually written in CGI, AJAX, ASP or ASP.NET, take more time to load than simple static pages. They’re frequently
implemented to show information that changes frequently, e.g., weather updates or stock prices.
Dynamic pages usually contain application programs for different services and require server-side resources like
databases. A database allows the page creator to separate the website’s design from the content to be displayed to
users. Once they upload content into the database, it is retrieved by the website in response to a user request.
Client-side Scripting: A web page that changes in response to an action within it (“client-side event”) uses
client-side scripting. These scripts generate “client-side content” on the user’s computer, rather than the web
server.
Server-side Scripting: A web page that changes when it’s loaded or visited, or based on what’s submitted to
it, uses server-side scripting. When the pages are loaded, server-side content is generated. Examples include
login pages, shopping carts and submission forms.
A website can be static or dynamic. A static website's information does not change automatically, which means it
remains static or the same for all visitors of the site. A dynamic website or webpage has information, which is
generated in real-time and altered on the basis of the viewer, the time zone, time of the day, and other aspects. For
example, the Java point website's home page changes daily to provide visitors latest content as it is a dynamic web
page. However, this page that you are visiting currently, its information will not be changed until it is not updated as it
is a static page.
The dynamic web pages have Web scripting code like ASP or PHP. The code within the dynamic web pages is
analyzed at the time they are accessed by the users; consequently, HTML is forwarded to the client's Web browser. A
dynamic website can be client-side scripting or server-side scripting or can be both kinds of scripting in order to
generate the changing content. In dynamic websites, HTML programming is also involved for the basic structure. The
page can use any scripting language like JavaScript with client-side HTML scripting to alter the content of the page.
Scripts are run on the server, which hosts the page; it is done with server-side scripting.
In server-side scripting, the parameters are defined that provide a way the process for how the page is built. While
comparing with static websites, dynamic websites are easier to maintain; therefore, most large websites are dynamic
type. This is because, with static websites, whenever a change is made, they must be opened, edited, and published
manually, and these site's each page has unique content. On the other hand, the information is accessed from a
database by dynamic pages. Therefore, with dynamic websites, webmasters may only need to update a database record
at the time of they want to change the content. Especially, the dynamic concept is much ideal for large sites as they
have hundreds or thousands of pages.
Step 1 : Download XAMPP: Visit the official XAMPP website (https://www.apachefriends.org/) and download the
version of XAMPP that is compatible with your operating system.
Step 2 : Install XAMPP: Double-click on the downloaded file to begin the installation process. Follow the
instructions in the installer to complete the installation.
Step 4 : Choose components to install: During the installation process, you will be prompted to select which
components you want to install. By default, all components are selected, but you can deselect any that you do not
need. and click "Next"
Step 5 : Choose installation directory: Choose the directory where you want to install XAMPP. The default
directory is usually fine, but you can change it if you prefer. "Next" to install.
Step 6 : XAMPP control panel for windows supports different languages. if you want change languages, select the
Step 7 : XAMPP control panel for windows supports many apps of your xampp installation click next to continue the
installation
Step 9 : Wait until the installation complete and allow Apache HTTP server to communicate on these networks
Step 10 : Start XAMPP: This will launch a control panel that allows you to start and stop the various components of
XAMPP, such as Apache and MySQL
Test the installation: Open a web browser and navigate to http://localhost/. If everything is set up correctly, you
should see the XAMPP welcome screen.
“I accept the agreement” radio button and then the “Next” button to continue with the installation shown below.
The main purpose of this step is to check for the suitable version of Microsoft VC++ re-distributable package. Click
on the ‘Next’ to continue.
Now, you need to select the folder where you wish to create the program’s shortcut. You can select any folder of
your choice or you can continue with the default option. You can easily access this folder from the Windows start
Finally, you would see a ready to install wizard with a ready setup to begin the installation. Just hit the ‘Install’
Now, just be patient as the WampServer is extracting files to your selected location. Let the process complete
Once the status bar is turned fully green, an information screen will appear like the one shown below. Click ‘Next’ to
continue
Note: During the installation process, you will be prompted to select a default web browser. You can either keep it as
default i.e. Internet Explorer. Else click on the folder icon to browser, find, and choose other options. Click on Open to
confirm your selection. Also, you may be prompted to add SMTP, and email settings. Add the value or keep it as
default and click on the Next option. The installation process will continue.
The installation is almost done now simply click ‘Finish’ to exit the setup
Assignment
1. What is PHP?
Syntax of PHP
You can run php code on any web browser. PHP script is executed on the server, and the plain HTML result is
sent back to the browser.
Basic Syntax of PHP
PHP code is start with <?php and ends with ?>
Every PHP statements end with a semicolon (;).
PHP code saves with .php extension.
PHP contain some HTML tag and PHP code.
You can place PHP code anywhere in your document.
Example:
Output statement
Name & Signature of the Faculty : M PRAKASH Page 1
Signature of the HoD :
Shanmuga Industries Arts and Science College, Tiruvannamalai.
PG & Research Department of Computer Science
Notes of Lesson
Date Day Order Hour Unit II
Course Code &
Year I Semester II PHP Programming
Name
Teaching Method
Echo statement
The echo statement can output one or more strings. In general terms , the echo statement can display anything that
can be displayed to the browser, such as string, numbers,variables values, the results expression etc.,
<? Php
//display strings of text
echo ”HELLO WORLD”;
?>
print statement:
You can also use the print statement (an alterative to echo) to display output to the browser.like echo the
print is also a language construct not a real function .so you can also use it without parenthesise like print
or print().
both echo and print statement works exactly the same way except that print statement can only output one
string and always return one.
<? Php
//display strings of text
print ”HELLO WORLD”;
?>
Difference between echo and print
echo
echo is a statement, which is used to display the output.
echo can be used with or without parentheses.
echo does not return any value.
We can pass multiple strings separated by comma (,) in echo.
echo is faster than print statement.
print
print is also a statement, used as an alternative to echo at many times to display the output.
print can be used with or without parentheses.
print always returns an integer value, which is 1.
Using print, we cannot pass multiple arguments.
print is slower than echo statement.
Multi-line comments begin with /* and end with */. Between these two symbols, everything is regarded as a
comment. For instance:
PHP comments can aid other programmers in understanding the code and its function. It is simpler to maintain
and update code that is self-explanatory, and adding comments can make the code more approachable to others.
Debugging: When debugging code, comments can be helpful. Programmers can more quickly find and fix
problematic code by commenting out the lines that are causing problems.
Comments can aid in team collaboration when writing code. Multiple programmers can collaborate on the same
codebase without causing conflicts or misunderstandings by leaving notes and explanations in the comments.
Code Clutter: Comments, especially when used excessively, can add clutter to code. Too many comments can
make the code difficult to read and comprehend.
Outdated Comments: If comments are not updated in tandem with the code, they will become obsolete. This is
especially true if the comments are inaccurate or misleading.
Writing comments is time-consuming and can slow down the coding process. To save time, programmers may be
tempted to skip adding comments, but this can lead to problems later on.
If we want to use PHP in the Html document, then we have to follow the steps which are given below. Using these
simple steps, we can easily add the PHP code.
Step 1: Firstly, we have to type the Html code in any text editor or open the existing Html file in the text editor in
which we want to use the PHP.
<!Doctype Html>
<Html>
<Head>
<Title>
</Title>
</Head>
<Body>
</Body>
</Html>
Step 2: Now, we have to place the cursor in any tag of the <body> tag where we want to add the code of PHP.
And, then we have to type the start and end tag of PHP.
<h1>
<?php ?>
</h1>
Step 3: After then, we have to type the code of PHP between the tags of PHP.
<h1>
Name & Signature of the Faculty : M PRAKASH Page 4
Signature of the HoD :
Shanmuga Industries Arts and Science College, Tiruvannamalai.
PG & Research Department of Computer Science
Notes of Lesson
Date Day Order Hour Unit II
Course Code &
Year I Semester II PHP Programming
Name
Teaching Method
<?php
?>
</h1>
Step 4: When we successfully add the PHP code, then we have to save the Html file and then run the file in the
browser.
<!Doctype Html>
<Html>
<Head>
<Title>
</Title>
</Head>
<Body>
</Body>
</Html>
PHP Variables
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important points to know
about variables:
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.
$variablename=value;
A variable must start with a dollar ($) sign, followed by the variable name.
It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
One thing to be kept in mind that the variable name cannot start with a number or special symbols.
PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.
Let's see the example to store string, integer, and float values in PHP variables.
File: variable1.php
<?php
$str="hello string";
$x=200;
$y=44.6;
?>
Output:
string is: hello string integer is: 200 float is: 44.6
File: variable2.php
<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z;
?>
Output:
11
In PHP, variable names are case sensitive. So variable name "color" is different from Color, COLOR, COLor etc.
File: variable3.php
<?php
$color="red";
?>
Output:
My car is red
My house is
My boat is
PHP data types are used to hold different types of data or values. PHP supports 8 primitive data types that can be
categorized further in 3 types:
Special Types
It holds only single value. There are 4 scalar data types in PHP.
Boolean
Name & Signature of the Faculty : M PRAKASH Page 7
Signature of the HoD :
Shanmuga Industries Arts and Science College, Tiruvannamalai.
PG & Research Department of Computer Science
Notes of Lesson
Date Day Order Hour Unit II
Course Code &
Year I Semester II PHP Programming
Name
Teaching Method
integer
float
string
It can hold multiple values. There are 2 compound data types in PHP.
array
object
resource
NULL
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is
often used with conditional statements. If the condition is correct, it returns TRUE otherwise FALSE.
Example:
<?php
if (TRUE)
if (FALSE)
?>
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e., numbers without
fractional part or decimal points.
Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31.
Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
?>
Output:
Decimal number: 34
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a fractional or
decimal point, including a negative or positive sign.
Example:
<?php
$n1 = 19.34;
$n2 = 54.472;
?>
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special characters.
String values must be enclosed either within single quotes or in double quotes. But both are treated differently.
To clarify this, see the example below:
<?php
$company = "Jpoint";
echo "</br>";
?>
Output:
PHP Array
An array is a compound data type. It can store multiple values of same data type in a single variable.
Example:
<?php
echo "</br>";
?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield Array Element2: Yamaha Array Element3: KTM
PHP object
Objects are the instances of user-defined classes that can store both values and functions. They must be explicitly
declared.
Example:
<?php
class bike {
function model() {
?>
Output:
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function calls or references
to external PHP resources.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters as it
is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
Output:
PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to
perform operations on variables or values. For example:
$num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.
PHP Operators can be categorized in following forms:
Arithmetic Operators
Assignment Operators
Bitwise Operators
Comparison Operators
Incrementing/Decrementing Operators
Logical Operators
String Operators
Array Operators
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a variable.
if($num<100){
echo "$num is less than 100";
}
?>
Output:
12 is less than 100
PHP If-else Statement
PHP if-else statement is executed whether condition is true or false.
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
if(condition)
{
//code to be executed if true
}
else{
//code to be executed if false
}
Example:
1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>
Output:
12 is even number
Assessment
1. Illustrate the PHP variable?
2. List down the arithmetic operators in PHP.
3. Write a detailed note on control statements in PHP.
4. Write basic data types used in PHP
5. List few data types supported in PHP.
6. Briefly explain about comment statement in PHP.
7. Mention the scalar data-types provided by PHP? Explain with Examples.
8. Difference between echo and output statement
9. Explain any five operators in php.
Switch Statements:
PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-
else-if statement.
Syntax
switch(expression)
{
case value1:
//code to be executed
break;
case value2:
//code to be executed
break;
......
default:
code to be executed if all cases are not matched;
}
Example:
<?php
$num=20;
switch($num)
{
case 10:
echo("number is equals to 10");
break;
case 20:
echo("number is equal to 20");
break;
case 30:
echo("number is equal to 30");
break;
default:
echo("number is not equal to 10, 20 or 30");
}
?>
Example:
<?php
$ch = 'U';
switch ($ch)
{
case 'a':
echo "Given character is vowel";
break;
case 'e':
echo "Given character is vowel";
break;
case 'i':
echo "Given character is vowel";
break;
case 'o':
echo "Given character is vowel";
break;
case 'u':
Loops are used to repeatedly execute the same block of code as long as a condition is met. The basic
concept behind a loop is to save time and effort by automating repetitive activities within a program.
There are four different types of loops supported by PHP.
Types of Loop in PHP
while — loops through a block of code until the given condition evaluates to true.
do...while — the code block is run once, and then the condition is evaluated. If the condition is valid,
the sentence will be repeated until the condition is no longer true.
for — iterates over a block of code until the counter exceeds a certain value.
foreach — for each element in an array, loops through a block of code.
PHP for loop can be used to traverse set of code for the specified number of times.
It should be used if the number of iterations is known otherwise use while loop. This means for loop is
used when you already know how many times you want to execute a block of code.
It allows users to put all the loop related statements in one place. See in the syntax given below:
Syntax
for(initialization; condition; increment/decrement)
{
//code to be executed
}
Parameters
The php for loop is similar to the java/C/C++ for loop. The parameters of for loop have the following
meanings:
initialization - Initialize the loop counter value. The initial value of the for loop is done only once. This
parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until the condition is false. If
TRUE, the loop execution continues, otherwise the execution of the loop ends.
Increment/decrement - It increments or decrements the value of the variable.
Example
<?php
for($n=1;$n<=10;$n++)
{
echo "$n<br/>";
}
?>
Output:
1 2 3 4 5 6 7 8 9 10
All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don't pass
parameters, it will execute infinite.
<?php
$i = 1;
//infinite loop
for (;;) {
echo $i++;
echo "</br>";
}
?>
Nested Loop
When a statement block of a for-loop lies completely inside the block of a new for-loop then, it is called Nested
for loop.
<?php
for($i=1;$i<=3;$i++)
{
for($j=1;$j<=3;$j++)
{
Name & Signature of the Faculty : M.PRAKASH Page 5
Signature of the HoD :
Shanmuga Industries Arts and Science College, Tiruvannamalai.
PG & Research Department of Computer Science
Notes of Lesson
Date Day Order Hour Unit III
Course Code &
Year Semester PHP PROGRAMMING
Name
Teaching Method
Foreach loop
The foreach loop is used to traverse the array elements. It works only on array and object. It will issue
an error if you try to use it with the variables of different datatype.
The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the
elements of an array.
Syntax
Example:
<?php
$season=array("summer","winter","spring","autumn");
foreach( $season as $arr )
{
echo "Season is: $arr<br />";
}
?>
Output:
Season is: summer
Season is: winter
Season is: spring
Season is: autumn
Example:
<?php
//declare array
$employee = array (
"Name" => "Alex",
"Email" => "[email protected]",
"Age" => 21,
"Gender" => "Male"
);
$n++;
}
?>
do-while loop.
PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while loop
is guaranteed to run at least once.
The PHP do-while loop is used to execute a set of code of the program several times. If you have to
execute the loop at least once and the number of iterations is not even fixed, it is recommended to use
the do-while loop.
It executes the code at least one time always because the condition is checked after executing the
code.
The do-while loop is very much similar to the while loop except the condition check. The main
difference between both loops is that while loop checks the condition at the beginning, whereas do-
while loop checks the condition at the end of the loop.
Syntax
do
{
//code to be executed
}
while(condition);
Example
<?php
$n=1;
Do
{
echo "$n<br/>";
$n++;
}
while($n<=10);
?> Output:
<?php
$x = 5;
do {
echo "Welcome to I CS E! </br>";
$x++;
} while ($x < 10);
?>
PHP function
PHP function is a piece of code that can be reused many times. It can take input as argument list and
return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive function also.
Advantage of PHP Functions
Code Reusability: PHP functions are defined only once and can be invoked many times, like in other
programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By the use of
function, you can write the logic only once and reuse it.
Easy to understand: PHP functions separate the programming logic. So it is easier to understand the
flow of the application because every logic is divided in the form of functions.
PHP User-defined Functions
We can declare and call user-defined functions easily. Let's see the syntax to declare user-defined
functions.
Syntax
function functionname()
{
//code to be executed
}
PHP Functions Example
File: function1.php
<?php
function sayHello()
{
echo "Hello PHP Function";
}
sayHello();//calling function
?>
Output:
Hello PHP Function
PHP Function Arguments
We can pass the information in PHP function through arguments which is separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-length
argument list.
Let's see the example to pass single argument in PHP function.
File: functionarg.php
<?php
function sayHello($name)
{
echo "Hello $name<br/>";
}
sayHello("Sonoo");
sayHello("Vimal");
sayHello("John");
?>
Output:
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Output:
We can specify a default argument value in function. While calling PHP function if you don't specify
any argument, it will take the default argument. Let's see a simple example of using default argument
value in PHP function.
File: functiondefaultarg.php
<?php
function sayHello($name="Sonoo")
sayHello("Rajesh");
sayHello();//passing no value
sayHello("John");
?>
Output:
Name & Signature of the Faculty : M.PRAKASH Page 11
Signature of the HoD :
Shanmuga Industries Arts and Science College, Tiruvannamalai.
PG & Research Department of Computer Science
Notes of Lesson
Date Day Order Hour Unit III
Course Code &
Year Semester PHP PROGRAMMING
Name
Teaching Method