PHP Chap-1 Notes
PHP Chap-1 Notes
Chapter- 1
Introduction to PHP
PHP is an open source , serverscripting a programing language that allow web-
developers to create dynamic content that interacts with the database.
History:
Open source: PHP is an open source software; it is readily available to all users with
free of cost. It opens to everyone, anytime, anywhere so that it is cost effective also.
Platform independent (cross platform): It can run on various types of platform. It
is supported by all the operating systems like windows, Unix, solaris etc.
Simple and easy: The one who knows any programming language can easily work
on PHP. It is simple because it is a loosely types language, easy to learn and write
the code.
Database connectivity: PHP is easily connected with the database and make the
connection securely with the database.
Fast: It is the fastest programming language as compared to another. The PHP
applications can be easily loaded over the slow internet and data speed.
Maintenance: The PHP framework is mainly used to make the web-application
development easier and maintain the code automatically.
Testing: The PHP based web applications can be easily tested and it performs the
unit testing quickly and easily.
Security: The PHP frame work has built-in-tools to protect the web applications
from the outer attacks and security threats.
When user wants to write a PHP code, he must know about the HTML without HTML user
cannot create the webpage both HTML and PHP languages are important for web-development.
The PHP code is embedded in HTML files.
HTML PHP
HTML is a markup language used to create PHP is an open source scripting language
static WebPages. used for the development of dynamic
Websites and dynamic web applications.
HTML is used for front end development or PHP is used for back end development or
Client side. Server side.
HTML is very easy to learn with less time it PHP is also easy to learn but not as much as
Accepts some small mistakes and gives the HTML it takes more time to learn and it
output. won’t accept the mistake in code.
HTML is compatible with almost all PHP also compatible with all types of
Browsers. Browsers.
HTML is used to organize the content of the PHP is used to “interact” with the database
websites. It focuses on how the contents need to retrieve the information, storing the data,
to display with different fonts, size and e-mail sending and provides the content to
colors etc. The HTML pages to display on the screen.
<html> <?PHP
<body>
-----------
</body>
?>
</html>
Server: To send and retrieve the data without interfering the display and behavior of existing
data.
Interpreter Compiler
It takes a single line of code or instructions It takes an entire program as its input.
As input.
It does not generate any intermediate object It generates intermediate object code.
code
It requires less memory. [does not create It requires more memory in order to create
Object code]. Object code.
It displays the errors when each instruction It displays the errors once the entire
Is run. Program is checked.
Execution is slower. Execution is faster.
E.g.: Python, Ruby etc. E.g.: C, C++ etc.
PHP parser:
A parser is a compiler or interpreter component that creates into the data of a smaller
element easy translation into another language.
The parse means to analyze an object specifically.
1. The PHP files can contain text, HTML, CSS, Java script and PHP code.
2. The PHP files are stored by using the extension .php.
3. The PHP scripts can be placed anywhere in the document.
4. Each code line in PHP must end with a semicolon.
5. We use different styles to create PHP files.
a. Canonical PHP tags (Long form).
b. Short form.
c. Active server page style [ASP style].
a) Long form:
It is always starting with <?php and ends with?>.
Putting a PHP after the opening question mark makes PHP code friendly to the
XML parser.
When PHP interpreter reads a file it only processes the lines between </php
and?> tags.
For portability and compatibility always use these types of php format.
E.g.: a) <?php
echo “Welcome to php”;
?>
b) Short form:
E.g.: a) <?
echo “ “;
?>
c) ASP style tags: These are used by active server pages to describe code blocks for
these we need to set the configuration of php.ini files.
E.g.: a) <%
-----------
%>
Syntax:
<script language=”php”>
---------------
</script>
Install XAMPP or WAMP server and any code editors like Notepad, Notepad++ etc.
to computer system.
Write the PHP code in the code editor
Ex: <?php
echo “This is PHP and MySQL for BCA”;
?>
Save this file by using the extension .php (test.php).
All php files stored in htdocs folder by default.
Then go to the XAMPP installation folder and run XAMPP.control.exe.
Now open any web browser then enter the file path, in address bar.
If php installation and php files are working properly then the following output
is displayed.
Comments
The user can use both single line and multi-line comments in php file.
E.g.: <?php
/*This is multiline
Comment block
*/
?>
Variables in PHP
Variables are valid identifiers which are used to store the values like text, numbers and arrays.
When a variable is declared it can be used again and again in the script.
The scope of the variable is the portion of the program in which the value of the variable
is accessed depending on the scope.
PHP has 3 variable scopes:
1) Local variables.
2) Global variables.
3) Static variables.
1) Local variables: The variables declared within a function are called local variables to
that function. These variables cannot accessible outside the function.
E.g.: <?php
$num=10;
function local()
{
$num=20;
echo “the value of number is $num”;
}
local();
echo “the value of number is $num”;
?>
2) Global variables: The variables declared outside a function are called global
variables.
These variables can be accessed directly access outside a function.
but to access the global variable within a function we need to use the keyword
“global” before the variable.
E.g.: $num=20;
function global()
{
global $num;
$num++;
echo ” The value of number is $num”;
}
global();
E.g.: $sum=10;
function static()
{
$sum=20;
Static $count=0;
$count++;
echo “$count”;
echo “$sum”;
}
static ();
static ();
static ();
Quotations
a) Single quotes (‘ ‘): The contained inside the single quote is evaluated literally. It does
not represent the value assigned to the variable.
E.g.:
single quotes $string=”PHP”;
echo ‘$string is a scripting language’;
output: $string is a scripting language
b) Double quotes (“ “): The variables inside the double quotes are evaluated with
their values.
E.g.:
double quotes $string=”PHP”;
echo “$string is a scripting language”;
output: PHP is a scripting language
c) Backslash (escape character): escape characters are evaluated inside the
double quotes.
E.g.:
Backslashes $string=”PHP”;
1] echo ‘\$string is a scripting language’;
output: $string is a scripting language
2] echo “The $string is a \”dynamic\”webpage”;
output: The PHP is a “dynamic” webpage
K C Silpa, Asst. Professor, Dept. Of BCA Page 8
PHP VVFGC, Tumkur
Data type: It defines the type of the data a variable can hold or stores.
Categories of data types are:
a) Scalar- Integer, float, Boolean, string.
b) Compound- array, object.
c) Special- resources, NULL.
a) Scalar data types: This are used to represent a single value.
i. Integer: An integer can hold only whole numbers including positive and
negative numbers. It does not contain fractional part they can be decimal, octal or
hexadecimal. The range of integers must lie between -231 to +232.
E.g.: -42 negative decimal
0 x 742 octal
0 x CA8 hexa-decimal
ii. Float: It can also call double, floating points, real numbers. It can hold the
numbers containing fractional or decimal point, including positive and negative.
E.g.: 4.56, 4.0, 8.7e4, 1.23E+11
iii. Boolean: It hold only 2 values i.e. true or false. All successful events and non-
zero value will return true (1). Unsuccessful events are zero returns false.
iv. String: String is a sequence of characters. Each character in a string occupies 1
byte of storage. It can hold both characters and numbers. strings are written with
double quotes during its declaration.
E.g.: “PHP is a great language”
A particular character of the string can be accessed using array. E.g.: $color=”
maroon”;
$char=$color [2];
It assigns to the variable $char.
b) Compound / Complex data types: This data type allows multiple items of the
same type under a single entity.
i. Array: Array is a compound data type which can store multiple value of
same data type.
E.g.: $int array=array (10,20,30);
echo “First element: $array [0]”;
echo “Second element: $array [1]”;
Type casting
It is a process of converting value of a variable from one data type to another is called as
type casting.
As we know that in PHP, we do not need to specify the data type of a variable. The php
parser automatically set the data type but the data type of the variable can be converted to
another either manually or automatically using type casting.
2) Explicit type casting: Explicit type conversion is done by the programmer manually.
The data type you need to change the variable should be returned inside the
parenthesis before the variable (casting operator).
E.g.: <?php
$x=5.3;
$y=(int)$x; //casting $x into integer.
Var_dump($y);
?>
<?php
$val=88;
var_dump(strval($val));
?>
Output: String(88)
Super global variables are built-in variables that are always available in all scopes.
User can access this variable from any function, class without declaring it
1) $GLOBAL
2) $_SERVER
3) $_REQUEST
4) $_GET
5) $_POST
6) $_SESSION
7) $_COOKIE
8) $_FILES
9) $_ENV
1) $GLOBAL:
It is a super global variable is used to access global variables from any where in
PHP Script.
PHP store all the global variables in array $GLOBALS [index] where index
holds the name of the variable.
E.g.: <?php
$x=75;
$y=25;
function add()
{
$GLOBALS[‘Z’]=$GLOBALS[‘X’]+$GLOBALS[‘Y’];
}
add();
echo $z;
?>
2) $_SERVER:
It stores the information about headers, paths and script locations.
E.g.:<?php
echo $_SERVER[‘PHP_SELF’];
echo $_SERVER[‘SERVER_NAME’];
echo $_SERVER[‘HTTP_HOST’];
echo $_SERVER[‘HTTP_REFERER’];
echo $_SERVER[‘HTTP_USER_AGENT’];
echo $_SERVER[‘SCRIPT_NAME’];
?>
3) $_REQUEST:
It is used to collect the data after submitting a html form. It is not widely
$_GET and $_POST perform the same task.
4) $_GET:
It is a default form request.
The data passed through get request is visible on the URL browser, so it is not
secured.
We can get limited amount of data through get request.
5) $_POST:
Post request is widely used to submit form that have large amount of data such as file
upload, image upload etc.
The data passed through post request is not visible on URL so it is secured.
6) $_SESSION:
It is a way to store the information to be used at the multiple pages.
By default, session variables will be lost after closes the browser.
Session_start() must be the very first in the document before any HTML tags.
7) $_COOKIE:
Cookies are small text files loaded from a server to a client computer.
It stores the information regarding the client computer so that the same page is visited
by the user again and again. It decreases the latency period to open the page.
8) $_FILES:
It is used to upload the files.
It is associated with 2-D array and it keeps all the information related to the uploaded
file.
9) $_ENV: it is a super global variable that contains the environment variable where that
environment variable is provided by the shell under which php is running.
Constant
A constant is an identifier for a simple value. The value cannot be changed during the
execution.
The valid constant name starts with a letter or underscores (no dollar sign before the
constant)
To create a php constant use the define () and const keyword.
define():
it is a function to create a constant. It defines a constant at runtime.
Syntax:
Case sensitive: it specifies whether the constant name should be insensitive the default
is false.
define(“MESSAGE”, “hello”);
const:
it is a keyword used to create a constant. It defines a constant at compile time.
Syntax:
const name = value;
Operators
Operator is a symbol that performs an even action on a value.
Relational operators: these are used to compare 2 elements then the output is in the form of
Boolean.
Identical / Identity: The identity operator compares the variables first then it compares the
type of the variable. If the type of the variable is different then it returns false.
E.g.:
These operators provide and easy method to assign a value and It makes to perform basic
arithmetic and string operation easily.
operand.
+= Add then assign $x+=$y Is same as
$x=$x+$y.
-= Subtract then assign $x-=$y Is same as $x=$x-
$y.
*= Multiply then assign $x*=$y Is same as
$x=$x*$y.
/= Divide then assign $x/=$y Is same as $x=$x/$y.
%= Modulus then assign $x%=$y Is same as
$x=$x%$y.
>>= Perform right shift $x>>=$y Is same as
then assign $x=$x>>$y.
<<= Perform left shift $x<<=$y Is same as
then assign $x=$x<<$y.
Bitwise operator: it is used to perform on its bit level. An operators are first converted to bit
level them calculation is performed on the operands.
Eg: $x=1010
$y=1100
1100
1000
1100
0110
1100
0110
0101
Eg: $x <<2
$x 1010
101000
$x >>2
$x 1010
001010
String operator:
There are 2 string operators in php are:
Control Structure
Control sequence allows user to execute block of code depending on conditions. It control
the flow of code, order in which the various statement are execute how many times a
particular code should execute when the code block will ended.
If statement
If else statement
If else ladder statement
Switch statement
If statement: it executes the block of statement depending on the condition it executes the
statement only it specifies condition is true.
if (condition)
{
Code to be executed;
}
Ex:
<?php
$num=12;
if($num<100){
echo "$num is less than 100";
}
?>
If else statement: in this structure the true block statements are execute if the condition are
true otherwise else part get executed.
Syntax:
if (cond)
{
code is true;
}
else
{
code is false;
}
Ex:
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
It is a multiway decision maker which contains two or more else if condition in which any
one code block will be executed based on the condition if all the condition becomes false then
the last code block will be executed.
Syntax:
if (condition1){
//code to be executed if condition1 is true
} elseif (condition2){
//code to be executed if condition2 is true
} elseif (condition3){
//code to be executed if condition3 is true
....
} else{
//code to be executed if all given conditions are false
}
Ex:
<?php
$marks=69;
if ($marks<33){
echo "fail";
}
else if ($marks>=34 && $marks<50) {
echo "D grade";
}
else if ($marks>=50 && $marks<65) {
echo "C grade";
}
else if ($marks>=65 && $marks<80) {
echo "B grade";
}
else if ($marks>=80 && $marks<90) {
echo "A grade";
}
else if ($marks>=90 && $marks<100) {
echo "A+ grade";
}
else {
echo "Invalid input";
}
?>
Switch statement: switch statement is used to select one block of code among multiple
blocks.
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;
}
Ex:
<?php
$num=20;
switch($num){
case 10:
echo("number is equals to 10");
K C Silpa, Asst. Professor, Dept. Of BCA Page 23
PHP VVFGC, Tumkur
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");
}
?>
Looping statements
They are executes a block of code for specific times until the condition becomes false
It helps to execute the code again and again.
It avoids rewriting the code.
There are 4 loop statements:
o While
o Do-while
o For
o Foreach
While loop: it executes a block of code as long as the condition is true
It is also called as entry controlled loop.
Syntax:
while(condition){
//code to be executed
}
Ex:
<?php
$n=1;
while($n<=10){
echo "$n<br/>";
$n++;
}
?>
Do-while loop: it always execute the block of code at least once. It repeats the loop as long as the
condition is true. It checks the condition at the end of the code
It is also called as exit controlled loop.
Syntax:
do{
//code to be executed
}while(condition);
Ex:
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=10);
?>
For loop: it is used to execute the block of code for a certain number of time. It is also called
as fixed loop
Syntax:
Condition evaluates the for iteration, if it is true then executes the code until it becomes false
Ex:
<?php
for($n=1;$n<=10;$n++){
echo "$n<br/>";
}
?>
For each loop: it is used to iterate over arrays.
The value of the current array element is assigned to the variable($value) and shifted to the
next element.
Syntax:
foreach(array-elements as $value)
{
Code;
}
Foreach statement excepts an array-element
The keyword as and definition of the variable to receive the value.
Ex:
<?php
$x=array(“ one” ,” two” ,” three” ;
foreach($x as $value)
{
echo$value;
}
?>
Jumping statements: it is used to transfer the control from one point to another point in
the program.
Break
Continue
Goto
Break: it is used to terminate the execution of a loop at that point itself. It immediately
coming out of a loop.
Eg:
<?php
$i=0;
while($i<5)
{
$i++;
if($i==3)
break;
echo $i;
}
?>
o/p:
1
2
Continue: it is used to stop the current iteration and starts the next iteration until condition
becomes false.
Note: Always break and continue keywords are preceded by a conditional statement.
Ex:
<?php
$i=0;
while($i<=5)
{
$i++;
if($i==3)
continue;
echo $i;
}
?>
o/p:
Syntax:
Statement 1;
Goto labelname;
Statement2;
Labelname:
statements;
Ex:
<?php
$i=0;
while($i<=10)
{
$i++;
if($i==10)
goto stop;
else
echo $i;
}
stop: echo “ value is greater than 10 hence stopped” ;
?>
o/p;