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

PHP Unit II Part I

PHP is a server-side scripting language commonly used for web development. It allows developers to dynamically generate HTML pages using PHP code. Unlike HTML, PHP code is interpreted on the server-side and allows data manipulation and output generation. PHP is free, open-source, supports MySQL databases, and runs on most web servers by default. It is widely used for building dynamic websites and web applications.

Uploaded by

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

PHP Unit II Part I

PHP is a server-side scripting language commonly used for web development. It allows developers to dynamically generate HTML pages using PHP code. Unlike HTML, PHP code is interpreted on the server-side and allows data manipulation and output generation. PHP is free, open-source, supports MySQL databases, and runs on most web servers by default. It is widely used for building dynamic websites and web applications.

Uploaded by

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

PHP - Hypertext Preprocessor

A scripting language is a language that interprets scripts at runtime. The purpose of the scripts
is usually to enhance the performance or perform routine tasks for an application.
PHP stands for Hypertext Preprocessor and it is a server side scripting language that is used to
develop Static websites or Dynamic websites or Web applications. It is the preferred scripting
language for tech giants such as Facebook, Wikipedia, and Tumblr despite full-
stack JavaScript gaining popularity with upcoming developers

What is the difference between HTML & PHP?


Now many of you might ask that why do we need PHP when we already have HTML. Unlike
HTML, PHP allows the coder to create an HTML page or section of it dynamically. PHP is also
capable of taking data and use or manipulate it to create the output that the user desires.
In HTML, anything you put in creates an output but PHP would not give you an output if
something is wrong with your code. The learning curve of PHP is also much steeper compared to
HTML.A PHP script can be placed anywhere in the document.
It starts with <?php and ends with ?>:
Syntax <?php // PHP code goes here ?>

Prerequisites to learn PHP


Once you have gained some knowledge in PHP, you will need to learn other languages for
using PHP effectively. The languages include:
o HTML
o MySQL
o CSS
o JavaScript
Why do we need PHP?
You must be wondering that why do we need PHP for web programming when we
already have other scripting languages like HTML.
The compelling reasons for using PHP:
 It is open-source and free scripting language
 It has short learning curve compared to other languages such as JSP, ASP etc.
 Most web hosting servers support PHP by default
 It is a server-side scripting language so you need to install it on
the server and client computers requesting for resources from the server do not
need to have PHP installed
 PHP has in built support for working hand in hand with MySQL
 It is cross platform so you can deploy your application on a number of
different operating systems such as windows, Linux, Mac OS etc.
Where do we use PHP?:
There are three main areas where we use PHP:
Server-side Scripting– This is the most traditional and main target field for PHP. The
three things required to make this work include a PHP parser, a web server and a web
browser. The web server runs with a connected PHP installation. You can access the
PHP program output with a web browser, viewing the PHP page through the server.
Command line Scripting– PHP script can also run without any server or browser. You
only need the PHP parser to use the command line scripting. 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 is probably not the most preferable language to
create a desktop application with a graphical user interface. But if you are well versed
with PHP, you can use some advanced PHP features in your client-side applications and
also use PHP-GTK to write such programs. You also have the ability to write cross-
platform applications this way.
How to run PHP?
Manual installation of a Web server and PHP requires in-depth configuration knowledge
but the XAMPP suite of Web development tools, created by Apache Friends, makes
it easy to run PHP. Installing XAMPP on Windows only requires running an installer
package without the need to upload everything to an online Web server.
What is XAMPP?
It is a free and open source cross-platform web server solution stack package developed
by Apache Friends that consists of the Apache HTTP Server, MariaDB & MySQL
database, and interpreters for scripts written in the PHP and Perl programming languages.
XAMPP stands for Cross-Platform (X), Apache (A), MariaDB & MySQL (M), PHP (P)
and Perl (P). It is a simple, lightweight Apache distribution that makes it
extremely easy for developers to create a local web server for testing and deployment
purposes.
PHP using WAMP Server - If you’re working on a project for the production
environment and have a PC running the Windows OS then you should opt for WAMP
server because it was built with security in mind. You can use this method to run PHP
scripts you may have obtained from somewhere and need to run with little or no
knowledge of PHP. You can execute your scripts through a web server where the output
is a web browser.
Let’s have a look at the steps involved in using WAMP Server:
e. Install the Server Software
f. Set up the Server
g. Save PHP Scripts
h. Run PHP Scripts
i. Troubleshoot
PHP IDE : In order to remain competitive and productive, writing good code in
minimum time is an essential skill that every software developer must possess. As the
number and style of writing code increases and new programming languages emerge
frequently, it is important that the software developers must opt for the right IDE to
achieve the objectives.
An Integrated Development Environment or IDE is a self-contained package that
allow you to write, compile, execute and debug code in the same place. So let’s have a
look at some of the best IDE’s for PHP:
o PHPStorm
o Netbeans
o Aptana Studio
o Eclipse
o Visual Studio (with Xamarin)
o ZendStudio
PHP Data Types
PHP Data Types- A variable can store different types of Data. Let’s have a look at
some of the data types supported by PHP:
PHP String-A string is a sequence of characters. In PHP, you can write the string
inside single or double quotes.
<!DOCTYPE html>
<html> <body>
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
$a = "Hello LNMI!";
$b = 'Hello Students!';
echo $a; echo "<br>"; echo $b;
?>
</body> </html>

PHP Integer-An integer data type is a non-decimal number between -2,147,483,648


and 2,147,483,647. An integer must have at least one digit and can be either positive or
negative.
The following example takes $a as an integer. The PHP var_dump() function returns
the data type and value.
<?php $a = 711; var_dump($a); ?>

PHP Float-A float or floating point number is a number with a decimal point or a
number in exponential form.
The following example takes $a as a float and the PHP var_dump() function returns the
data type and value.
<?php $a = 14.763; var_dump($a); ?>

PHP Boolean-A Boolean represents two possible states: TRUE or FALSE. They are
often used in conditional testing.
$a = true; $b = false;
PHP Object-An object is a data type which stores data and information on how to
process that data. In PHP, an object must be explicitly declared. We need to declare a
class of object using the class keyword.
<?php
class Student {
function Student() { $this->name = "AMAN"; }
}
// create an object
$LNMI =new Student(); // show object properties
echo $LNMI->name; ?>

PHP Array-An array stores multiple values in one single variable. In the following
example, the PHP var_dump() function returns the data type and value.
<?php $students = array(“AMAN”,”Ram”,”Sohan”);
var_dump($students); ?>
PHP Variables -
PHP Variables - Variables are containers for storing information. All variables in
PHP are denoted with a leading dollar sign ($). Unlike other programming languages,
PHP has no command for declaring a variable. It is created the moment you first assign a
value to it.
Declaring PHP Variables:
<?php $txt = “Hello LNMI!”;
$a = 7; $b = 11.5; ?>
The PHP echo statement is often used to output data to the screen.
PHP Variables Scope
In PHP, variables can be declared anywhere in the script. The scope of a variable is the
part of the script where the variable can be used.
In PHP we have three different variable scopes:
Local – A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
<?php function myTest()
{ $a = 7; // local scope
echo “<p>Variable a inside function is: $a</p>”; }
myTest(); // using x outside the function will generate an error
echo “<p>Variable a outside function is: $a</p>”; ?>
Global– A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function. The global keyword is used to access a global variable from
within a function:
<?php $a = 9; // global scope function
myTest() {
// using a inside this function will generate an error echo
“<p>Variable a inside function is: $a</p>”; }
myTest(); echo “<p>Variable a outside function is: $a</p>”; ?>
Static– When a function is executed, all of its variables are deleted. But if you want any
variable not to be deleted, the static keyword is used when you first declare the variable:
<?php function
myTest() {
static $a = 0;
echo $a; $a++;
}
myTest(); myTest(); myTest(); ?>

Why PHP is Called a Loosely Typed Language?


Loosely typed language indicates a programming language that does not require defining
the variable. In simple words, while declaring a variable in a programming language, if it
does not require any classification of data types stored in its libraries then this means that
the programming language is loosely typed. And for this same reason, PHP is also called
loosely typed language.
The benefit of working with these languages is that you can define a variable as $string
and assign the integer number to it. You won’t have to backtrack the thousand lines of
code to change or declare the nature of the variable.
Contrary to many scripting languages, PHP is the loosely-typed programming language
as it does not require the variable type to be defined while declaring the variable.
Programmers often seem to enjoy its flexible features as it gives them an optimum and
efficient way of coding and debugging.
PHP Operators
Operators are used for performing different operations on variables. Let’s have a look at
the different operators in PHP:
o Arithmetic operators
o Assignment operators
o Comparison operators
o Logical operators
o Array operators
Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
Operator Name Example Result
+ Addition $a + $b Sum of $a and $b
– Subtraction $a – $b Difference of $a and $b
* Multiplication $a * $b Product of $a and $b
/ Division $a / $b Quotient of $a and $b
% Modulus $a % $b Remainder of $a divided by $b
** Exponentiation $a ** $b Result of raising $a to the $b’th power

Example:
<!DOCTYPE html>
<html> <body>
<?php
$x = 10;
$y = 6;
echo "Addition of x and y is:";
echo $x + $y;
echo " <br/> Substration of x and y is:";
echo $x - $y;
echo " <br/> Multiplication of x and y is:";
echo $x * $y;
echo " <br/> Devision of x and y is:";
echo $x / $y;
echo " <br/> Exponentiation of x and y is:";
echo $x ** $y;
?>
</body> </html>
Assignment Operators
The PHP assignment operators are used with numeric values to write a value to a
variable.
Assignment Similar to Result
The left operand gets set to the value of the expression
a=b a=b
on the right.
a += b a=a+b Addition
a -= b a=a–b Subtraction
Comparison Operators- The PHP comparison operators are used to compare two
numbers or strings
Operator Name Example
== Equal $a == $b > Greater than $a > $b
=== Identical $a === $b < Less than $a < $b
Greater than or equal
!= Not equal $a != $b >= $a >= $b
to
<> Not equal $a <> $b <= Less than or equal to $a <= $b
!== Not identical $a !== $b
Logical Operators
The PHP logical operators are used to combine conditional statements.
Operator Name Example
and And True if both $a & $b are true
or Or True if either $a or $b are true
xor Xor True if either $a or $b are true, but not both
&& And True if both $a & $b are true
|| Or True if either $a or $b are true
! Not True if $a is not true
Array Operators
The PHP array operators are used to compare arrays.
Operator Name Example
+ Union $a + $b
== Equality $a == $b
=== Identity $a === $b
!= Inequality $a != $b
<> Inequality $a <> $b
!== Non-identity $a !== $b
PHP Conditional Statements
Conditional statements are used to perform different actions for different conditions. In
PHP we have the following conditional statements:
o if statement – executes some code if one condition is true
o if…else statement – executes some code if a condition is true and another code if
that condition is false
o if…elseif…else statement – executes different codes for more than two
conditions
o switch statement – selects one of many blocks of code to be executed
The if Statement
The if statement executes some code if one condition is true.
<?php $t = date("H"); if ($t < "15") { echo "Have a good day!"; }
?>

The if…else Statement


The if…else statement executes some code if a condition is true and another code if that
condition is false.
<?php $t = date("H");
if ($t < "15") {
echo "Have a good day!";
}
else {
echo "Have a good night!";
}
?>
The if…elseif…else Statement
The if…elseif…else statement executes different codes for more than two conditions.
<?php $t = date("H"); if ($t < "15") { echo "Have a good
morning!"; } elseif ($t < "25") { echo "Have a good day!"; } else
{ echo "Have a good night!"; } ?>
The Switch Statement
The switch statement is used to perform different actions based on different conditions. It
is used to select one of many blocks of code to be executed.
<?php $favcolor = "blue"; switch ($favcolor) { case "blue": echo
"Your favorite color is blue!"; break; case "green": echo "Your
favorite color is green!"; break; case "black": echo "Your
favorite color is black!"; break; default: echo "Your favorite
color is neither blue, green nor black!"; } ?>
PHP Loops
When we write a code, we want the same block of code to run over and over again in a
row. Instead of adding several almost equal code-lines in a script, we can use loops to
perform the same task. In this PHP Tutorial we will learn about the three looping
statements.
In PHP, we have the following looping statements:
o while – loops through a block of code as long as the specified condition is true
o do…while – loops through a block of code once, and then repeats the loop as long
as the specified condition is true
o for – loops through a block of code a specified number of times
The While Loop
The while loop executes a block of code as long as the specified condition is true.
<?php
$a = 3;
while($a <= 5)
{ echo "The number is: $a <br>";
$a++;
}
?>
The do..while Loop
The do…while loop will always execute the block of code once, it will then check the
condition, and repeat the loop while the specified condition is true.
<?php
$a = 3;
do {
echo "The number is: $a <br>";
$a++;
} while ($a <= 5);
?>
The For Loop
PHP for loops execute a block of code a specified number of times. It is used when you
know in advance how many times the script should run.
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
PHP Functions
Functions and types.
The real power of PHP comes from its built-in functions. Besides the built-in PHP
functions, we can also create our own functions.
A function is a block of statements that can be used repeatedly in a program and will not
execute immediately when a page loads.
A user-defined function declaration starts with the word function. A function name can
start with a letter or underscore but not a number.
PHP functions are similar to other programming languages. As a function is a piece of code
which takes one more input in the form of parameter and does some processing and returns
a value.
They are built-in functions but PHP gives you option to create your own functions as well.
A function will be executed by a call to the function. You may call a function from
anywhere within a page.
Syntax:
function function_name()
{
//body of function.
}
Function Types
1. Simple function
2. Function with parameter
3. Anonymous function.
Example of Simple function:
<html> <body>
<?php
// Defining a PHP functions
function writeMessage()
{
echo “Welcome to PHP world”;
}
// Calling a PHP function.
writeMessage();
?>
</body>
</html>
Example of PHP function with Parameters:
<?php
function addfunc($num1,$num2)
{
$num=$num1+$num2;
echo “Sum of the two numbers is ”.$sum;
}
addfunc(50,20);
?>
Anonymous function- Anonymous functions allow to creation of functions which have no
specified name.
Example:
<?php
//Defining Anonymous function
$a=function() {
echo "Anonymous function";
};
//Calling Anonymous function
$a();
?>

You might also like