Unit - 1 Introduction To PHP
Unit - 1 Introduction To PHP
IntroductiontoPHP
DefinePHP
PHPisstandsfor"PHP:HypertextPreprocessor".
PHP is a server side scripting language that is embedded in HTML. It is usedto
manage dynamic content, databases, session tracking, even build entire e-
commerce sites.
Itisintegratedwithanumberofpopulardatabases,includingMySQL, Oracle,
Sybase, and Microsoft SQL Server.
PHP is pleasingly zippy in its execution, especially when compiled as an
Apache module on the Unix side. The MySQL server, once started, executes
even very complex queries with huge result sets in record-setting time.
PHPSyntaxisC-Like.
CommonusesofPHP
PHPperformssystemfunctions,i.e.fromfilesonasystemitcancreate,open, read,
write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file,
throughemail you can send data, return data to the user.
Weadd,delete,modifyelementswithinourdatabasethroughPHP.
Accesscookiesvariablesandsetcookies.
UsingPHP,wecanrestrictuserstoaccesssomepagesofourwebsite.
Itcanencryptdata.
CharacteristicsofPHP
FiveimportantcharacteristicsmakePHP'spracticalnaturepossible−
Simplicity
Efficiency
Security
Flexibility
Familiarity
P.No:1
"HelloWorld"ScriptinPHP
Example:PHP–Hello,WorldProgram
<html>
<head>
<title>HelloWorld</title>
</head>
<body>
<?phpecho"Hello,World!";?>
</body>
</html>
Itwillproducefollowingresult−
Hello,World!
If we examine the HTML output of the above example, we will notice that the PHP code
isnotpresentinthefilesentfromtheservertoourWebbrowser.AllofthePHPpresentin
theWebpageisprocessedandstrippedfromthepage;theonlythingreturnedtothe client from the
Web server is pure HTML output.
All PHP code must be included inside one of the three special markup tags ATE are
recognised by the PHP Parser.
<?phpPHPcodegoeshere?>
<? PHPcodegoeshere?>
<scriptlanguage="php">PHPcodegoeshere</script>
Amostcommontagisthe<?php...?>andwewillalsousethesametaginourtutorial.
P.No:2
DefiningVariablesandConstant
PHP Variables
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some
important points to know about variables:
AsPHPisalooselytypedlanguage,sowedonotneedtodeclarethedata
typesofthevariables.Itautomaticallyanalysisthevaluesandmakes conversions to its
correct datatype.
Afterdeclaringavariable,itcanbereusedthroughoutthecode.
AssignmentOperator(=)isusedtoassignthevaluetoavariable.
SyntaxofdeclaringavariableinPHPisgivenbelow:
$variablename=value;
RulesfordeclaringPHPvariable:
Avariablemuststartwithadollar($)sign,followedbythevariablename.
Itcanonlycontainalpha-numericcharacterandunderscore(A-z,0-9,_).
Avariablenamemuststartwithaletterorunderscore(_)character.
APHPvariablenamecannotcontainspaces.
Onethingtobekeptinmindthatthevariablenamecannotstartwithanumberor special symbols.
PHPvariablesarecase-sensitive,so$nameand$NAMEbotharetreatedasdifferent variable.
PHPVariable:Declaringstring,integer,andfloat
Let'sseetheexampletostorestring,integer,andfloatvaluesinPHPvariables.
<?php
$str="hellostring";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
P.No:3
Output:
PHP Constant
DefiningandAccessingaConstant
<?php
define(“THE_YEAR”,“2012”);
echo“Itistheyear“.THE_YEAR;
?>
Constants can beusedanywhere in our scripts, That is constant are includingin functionsstored
in external files.
Differencebetweenconstantandvariables
Constant Variables
Once the constant is defined, it can never Avariable can be undefined as well
be redefined. as redefined easily.
There is no need to use the dollar ($) sign To declare a variable, always use the
before constant during the assignment. dollar ($) sign before the variable.
Constants are the variables whose values The value of the variable can be
can'tbechangedthroughouttheprogram. changed.
P.No:4
PHPDatatype
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:
ScalarTypes(predefined)
CompoundTypes(user-defined)
SpecialTypes
PHPDataTypes:ScalarTypes
Itholdsonlysinglevalue.Thereare4scalardatatypesinPHP.
1. boolean
2. integer
3. float
4. string
PHPDataTypes:CompoundTypes
Itcanholdmultiplevalues.Thereare2compounddatatypesinPHP.
1. array
2. object
PHPDataTypes:SpecialTypes
Thereare2specialdatatypesinPHP.
1. resource
2. NULL
P.No:5
PHP Boolean
ABooleanrepresentstwopossiblestates:TRUEorFALSE.
$x=true;
$y=false;
Booleans are often used in conditional testing. You will learn more about conditional
testing in a later chapter of this tutorial.
PHP Integer
ExampleProgram
<?php Output:
$x=5985;
var_dump($x); int(5985)
?>
PHP Float
Afloat (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type
and value:
ExampleProgram
<?php
$x=10.365; Output:
var_dump($x); float(10.365)
?>
PHP String
Astringisasequenceofcharacters,like"Helloworld!".
Astringcanbeanytextinsidequotes.Wecanusesingleordoublequotes:
P.No:6
ExampleProgram
<?php
$x="Helloworld!";
$y='Helloworld!'; Output:
echo$x; Helloworld!
echo"<br>";
echo$y; Helloworld!
var_dump($x); string(12)"Helloworld!"
?>
PHPArray
Anarraystoresmultiplevaluesinonesinglevariable.
In the following example $cars is an array. The PHP var_dump() function returns the data
type and value:
ExampleProgram
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
Output:
array(3){[0]=>string(5)"Volvo"[1]=>string(3)"BMW"[2]=>string(6)"Toyota"}
PHP Object
Classesandobjectsarethetwomainaspectsofobject-orientedprogramming.
Let's assume we have a class named Car.ACar can have properties like model, color, etc.
We can define variables like $model, $color, and so on, to hold the values of these
properties.
When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for the
properties.
If you create a construct() function, PHP will automatically call this function when you create
an object from a class.
P.No:7
ExampleProgram
<?php
classCar{
public $color;
public$model;
publicfunctionconstruct($color,$model){
$this->color=$color;
$this->model=$model;
}
publicfunctionmessage(){
return"Mycarisa".$this->color."".$this->model."!";
}
}
PHPNULLValue
Nullisaspecialdatatypewhichcanhaveonlyonevalue:NULL.
AvariableofdatatypeNULL isavariablethathasnovalueassignedtoit.
Tip:Ifavariableiscreatedwithoutavalue,itisautomaticallyassignedavalueofNULL.
Variables can also be emptied by setting the value to NULL. PHP var_dump() function
returns the data type and value.
Example–NULLValue
<?php
$x="Helloworld!";
$x = null;
var_dump($x);
?>
P.No:8
OperatorsandExpressions
An operator is a symbol or series of symbols that, when used in conjunction with values,
performs an action, and usually produces a new value.
An operand is a value used in conjunction with an operator. There are usually two or more
operands to one operator.
Inthissimpleexample,twooperandsarecombinedwithanoperatortoproduceanew value: (4
+ 5)
a) TheAssignmentOperator
We have seen the assignment operator in use each time a variable was declared in an
example; the assignment operator consists of the single character: =. The assignment
operatortakesthevalueof theright-side operandand assignsittotheleft-sideoperand:
$name=“Jimbo”;
b) ArithmeticOperators
The arithmetic operators do exactly what you would expect—they perform arithmetic
operations. In given Table lists these operators along with examples of their usage and
results.
P.No:9
The addition operator adds the right-side operand to the left-side operand. The subtraction
operator subtracts the right-side operand from the left-side operand. The division operator
dividestheleft-sideoperandbytheright-sideoperand.Themultiplicationoperator multipliestheleft-
sideoperandbytheright-sideoperand.Themodulusoperatorreturns the remainder of the left-
side operand divided by the right-side operand.
<html>
<head>
<title>ArithmeticalOperators</title>
</head>
<body>
<?php
$a=42;
$b=20;
$c=$a+$b;
echo"AdditionOperationResult:$c<br/>";
$c=$a-$b;
echo"SubtractionOperationResult:$c<br/>";
$c=$a*$b;
echo"MultiplicationOperationResult:$c<br/>";
$c=$a/$b;
echo"DivisionOperationResult:$c<br/>";
?>
</body>
</html>
Output:
Addition Operation Result: 62
Subtraction Operation Result: 22
Multiplication Operation Result: 840
Division Operation Result: 2.1
c) ConcatenationOperator
Theconcatenationoperatorisrepresentedbyasingleperiod(.).Treatingbothoperands
asstrings,this operatorappendstheright-sideoperand to the left-sideoperand.
echo“hello”.”world” outputis:“helloworld”
$cm=212;
echo“thewidthis“.($cm/100).”meters”;
Outputis: thewidthis106meters
P.No:10
d) Combinedassignmentoperator
e) IncrementingandDecrementingOperators
Weknowthatbyincrementingthevalueof$xusingtheadditionoperator.
$x=$x+1;//$xisincrementedby1
orbyusingacombinedassignmentoperator
$x+=1;//$xisincrementedby1
PHPprovidessomespecialoperatorsthatallowwetoaddorsubtracttheintegerconstant
1fromanintegervariable,assigningtheresulttothevariableitself.Theseareknownas thepost-
incrementandpost-decrementoperators.Thepostincrementoperator consists of two plus
symbols appended to a variable name:
$x++;//$xisincrementedby1 post-increment
$x--;//$xisdecrementedby1 post-decrement
PHPprovidesthepre-incrementandpre-decrementoperatorsforsomepurpose. These
operators behave in the same way as the post-increment and post-decrement operators, but
they are writtenwiththe plus or minus symbols precedingthe variable:
++$x;//$xisincrementedby1 pre-increment
--$x;//$xisdecrementedby1 pre-decrement
P.No:11
f) ComparisonOperators
Comparison operators perform comparative tests using their operands and return the
Booleanvaluetrueifthetestissuccessfulorfalseifthetestfails.Thistypeofexpression is usefulwhen
using control structuresin our scripts, such as if and while statements.
For example, to test whether the value contained in $x is smaller than 5, we can use theless-
than operator as part of your expression:
$x<5
IngivenTableliststhecomparisonoperators.
P.No:12
g) LogicalOperators
Logical operators test combinations of Boolean values. For example, the or operator,
which is indicated by two pipe characters (||) or simply the word or, returns the Boolean
value true if either the left or the right operand is true:
true||false
Thisexpressionreturnstrue.
returnstheBooleanvaluetrueif$xcontainsavaluethatisgreaterthan2andsmallerthan
15.Parenthesesareusedwhencomparingexpressionstomakethecodeeasiertoread and to
indicate the precedence of expression evaluation.
IngivenTableliststhelogicaloperators.
ThefollowingexamplewillshowlhowtousethelogicaloperatorsinPHPprogram
<?php
$year=2014;
//Leapyearsaredivisibleby400orby4butnot100
if(($year%400==0)||(($year%100!=0)&&($year%4==0)))
{
echo"$yearisaleapyear.";
}
else
{
echo"$yearisnotaleapyear.";
}
?>
P.No:13
Control and Loop statements, GET and POST method
ControlstructuresinPHParefundamentalprogrammingconceptsthatenabledeveloperstowritepo
werfulandefficientcode.Theyallowtheprogramtoexecutespecificinstructionsbasedoncertaincon
ditions.Therearethreeprimarytypesofcontrolstructures: selection, iteration, and sequence.
Theselectionstructureexecutesasetofinstructionsifaspecificconditionismet.
Theiterationstructureisusedwhenasetofinstructionsneedstoberepeatedmultiple times
based on a given condition.
Thesequencestructureisusedtoexecuteinstructionsinsequentialorder.Thesestructures
are essential to writing efficient and reliable code.
Control structures in PHP are used to make decisions based on conditions, loop through
asetof instructions multiple times, and break outof a loop or switch statement.
ThemostcommoncontrolstructuresusedinPHPare
if-elsestatements,
Loopssuchasforandwhileloops,and
switchstatements.
PHPIfStatement
ThebasicsyntaxfortheIfStatementisasfollows:
if(condition){
//codetoexecuteiftheconditionistrue
}
Here'sanexampleofhowtheIfStatementworksinPHP:
<?php
$number=10;
if($number>5){
echo"Thenumberisgreaterthan5";
}
?>
Explanation In this example, Since 10 is greater than 5, the condition is true and the
codeinside the curly braces { } is executed. In this case, the code simply echoes the
message"The number is greater than 5" to the screen.
P.No:18
PHPIf-elseStatement
InPHP,theelsestatement(controlstructuresinPHP)isusedincombiningwithanifstatement to
execute code if the condition is false.
Thesyntaxforanif-elsestatementisasfollows:
if(condition){
//codetobeexecutediftheconditionistrue
}else{
//codetobeexecutediftheconditionisfalse
}
Here'sanexampletoillustratetheuseofanif-elsestatementinPHP:
<?php
$age=18;
if($age>=18){
echo"Youareeligibletovote.";
}else{
echo"Youarenoteligibletovote.";
}
?>
Explanation
Intheaboveexample,Since$ageis18andabove,theconditionevaluatestotrue,andthecodeinsidet
heifblockisexecuted,whichoutputs"Youareeligibletovote." If the condition had been evaluated
as false, the code insidethe else block wouldhave been executed instead, outputting "You
are not eligible to vote."
<?php
PHPElseIfStatement
$score=75;
if($score>=90){ Output:
InPHP,theelseifstatement allows wetotestmultipleconditionsandexecutedifferent code
blocks YourgradeisCExplanation
based on the results. The else-if statement
echo"YourgradeisA"; is often used when we need tocheck for
} more
else ifthan two conditions.
($score >= 80)
{ echo "Yourgrade isB"; :
HereisanexampleofhowtousetheelseifstatementinPHP:
} else if ($score >= 70)
{ echo "Yourgrade isC"; Thevalueofthe$scoreisgreaterthan70,
} else if ($score >= 60) then the code block inside the third
{ echo "Yourgrade isD"; ifstatement will be executed, and the
}else{ message"Your grade is C" will be displayed.
echo"Yourgradeis F";
} ?>
P.No:18
PHPSwitchStatement
Thebasicsyntaxofaswitchstatementisasfollows:
switch (expression)
{ case value1:
// code to execute if expression equals value1
break;
casevalue2:
// code to execute if expression equals value2
break;
// add as many cases as needed
default:
// code to execute if none of the cases match
break;
}
LetusseeanexampleofaswitchstatementinPHP:
$color="green";
Output:
switch ($color)
The color is
{ case "red":
echo "The color is red.";
greenExplanatio
break;
case"green":
n:
echo "The color is green.";
break;
The value of the $color is green,
case"blue":
thenthe corresponding case block
echo "The color is blue.";
wouldhave been executed instead.and
break;
themessage "The color is green” will
default:
echo "The color is unknown.";
break;
}
P.No:18
Loops in PHP
ForLoops
For Loops In PHP, a for loop is used to execute a block of code repeatedly for a specified
number oftimes. The general syntaxfor a for loop in PHP is as follows:
for(initialization;condition;increment){
//codetobeexecuted
}
Let'sbreakdownthecomponentsofaforloopinPHP:
for($i=1;$i<=10;$i++)
{
Initialization: This sets the initial value of the loop variable. It is executed only once at
echo$i.“”;
the beginning of the loop.
}
Condition: In this part of the for loop, we write the condition that is checked before each
iterationoftheloop.If theconditionistrue,theloopcontinuestoexecute.If the condition is
Output:
false, the loop terminates.
12345678910
Increment: In this part of the for loop the operation is performed after each iteration of
the loop. It is usually used to increment or decrement the loop variable value.
WhileLoop
Here'sanexampleofaforloopthatprintsthenumbersfrom1to10:
A whileloopisacontrolstructureinPHPthatallows,wetorepeatedlyexecuteablockofcode as long as
a specifiedcondition is true. The syntaxforawhileloop is as follows:
while(condition){
//codetobeexecuted
}
Explanation The condition is checked before each iteration of the loop. If the condition is
true,thecodeinsidetheloopisexecuted.Thiscontinuesuntiltheconditionbecomes
false,atwhichpointtheloopterminatesandcontrolispassedtothecodefollowingthe loop. Run the
above code in our editor for a better and clear explanation.
P.No:18
Here'sanexampleofasimplewhileloopinPHPthatcountsfrom1to5:
$num=1;
while ($num <= 5)
{ echo $num . "";
$num++;
}
Output:1
2345
Do-whileloop
A Do-While loop in PHP is a type of loop that allows you to execute a block of code repeatedly while a certai
Here'sthesyntaxforaDo-WhileloopinPHP:
do{
//codetobeexecuted
}while(condition);
Parametersofthesyntax:
$num=1;
The "do" keyword starts the loop and indicates the beginning of the code block to
do { be executed.
The "while"”;keyword is followed by a condition that will be evaluated at the end of
echo$num.“
each iteration of the loop.
$num++;
If the condition is true, the loop will continue to execute, starting again at the
}while($num<=5);
beginning of the code block.
Output:
The key difference between a do-while loop and a while loop is that a do-while loop will
12345
always execute the code in the block at least once, even if the condition is false from the
beginning. In contrast, a while loop will not execute the block of code at all if the
conditionis false from the beginning.
Here'sanexampleofaDo-WhileloopinPHPthatwilloutputthenumbers1to5:
P.No:18
HandlingHtmlFormwithPHP
The example (simple_form.html) below displays a simple HTML form with two input fields
Name, E-mail and a submit button:
simple_form.html
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail:<inputtype="text"name="email"><br>
<inputtype="submit">
</form>
</body>
</html>
When we fills out the form above and clicks the submit button, the form data is sent for
processingtoaPHPfilenamed"welcome.php".TheformdataissentwiththeHTTP POST method.
welcome.php
<html>
<body>
Welcome<?phpecho$_POST["name"];?><br>
Youremailaddressis:<?phpecho$_POST["email"];?>
</body>
</html>
Theoutputcouldbesomethinglikethis:
P.No:18
GET and POST Methods in PHP
PHP provides two methods through which a client (browser) can send information to the
server. These methods are given below, and discussed in detail:
1. GETmethod
2. POSTmethod
Get and Post methods are the HTTP request methods used inside the <form>tag to send
form data to the server.
HTTP protocol enables the communication between the client and the server where a
browser can be the client, and an application running on a computer system that hosts our
website can be the server.
GETmethod
The GET method is used to submit the HTML form data. This data is collected by the
predefined $_GET variable for processing.
Example
Thebelow code will display an HTML formcontaining two inputfieldsanda submit button. In
this HTML form, we used the method = "get" to submit the form data.
file:test1.html
<html>
<body>
<form action = "get_method.php" method = "GET">Username:
<input type = "text" name = "username" /><br> Blood Group:
<input type = "text" name = "bloodgroup" /><br>
<inputtype="submit"/>
</form>
</body>
</html>
P.No:18
Createget_method.phpfile,whichwillacceptthedatasentbyHTMLform.
file:get_method.php
<html>
<body>
Welcome <?php echo $_GET["username"]; ?></br>
Your blood group is: <?php echo $_GET["bloodgroup"]; ?>
</body>
</html>
Output:
WelcomeHarry
Yourbloodgroupis:AB-
POSTmethod
Similar to the GET method, the POST method is also used to submit the HTML form data.
Butthedatasubmittedbythismethodiscollectedbythepredefinedsuperglobal variable $_POST
instead of $_GET.
Example
Thebelow code will display an HTML formcontaining two inputfieldsanda submit button. In
this HTML form, we used the method = "post" to submit the form data.
file:test2.html
<html>
<body>
<form action = "post_method.php" method = "POST">
Username: <input type = "text" name = "username" /><br>
Blood Group: <input type = "text" name = "bloodgroup" /><br>
<inputtype="submit"/>
</form>
</body>
</html>
P.No:18
Createpost_method.phpfile,whichwillacceptthedatasentbyHTMLform.
file:post_method.php
<html>
<body>
Welcome <?php echo $_POST["username"]; ?></br>
Your blood group is: <?php echo $_POST["bloodgroup"]; ?>
</body>
</html>
Output:
WelcomeHarry
Yourbloodgroupis:AB-
AdvantagesofPOSTmethod(method="post")
ThePOSTmethodisusefulforsendinganysensitiveinformationbecausethe information
sent using the POST method is not visible to anyone.
ThereisnolimitationonsizeofdatatobesentusingthePOSTMethod.Wecan send a large
amount of information using this method.
BinaryandASCIIdatacanalsobesentusingthePOSTmethod.
DifferencebetweenHTTPGETandHTTPPOST
GETMethod POSTMethod
In GET method we can not send large amount In POST method large amount of data
of data rather limited data is sent because the can be sent because the request
request parameter is appended into the URL. parameter is appended into the body.
Data passed through GET method can be Data passed through POST method can
easily stolen by attackers. not be easily stolen by attackers.
In GET method onlyASCII characters are In POST method all types of data is
allowed. allowed.
P.No:18
Redirecting a form after submission
When a server script communicates with a client, it must first send some headers thatprovide
information about the document to follow. PHP usually handles this for us automatically, but
we can choose to send our own header lines with PHP’s header( ) function.
Redirection is done by outputting a Location using PHP using the header() function.
Here's how to redirect to a page called thanks.html:
header("Location:thanks.html");
Don't output any content to the browser via echo( ) or print( ), or by including HTML
markup outside the <?php ... ?> tags before calling header( ).
Here'saquickexampleofaformhandlerscriptthatredirectstoathank-youpage:
<?php
if(isset($_POST["submitButton"]))
{
// (deal with the submitted fields here)
header( "Location: thanks.html");
exit;
}
else{displayForm();
}
functiondisplayForm()
{
?>
<!DOCTYPEhtml5>
<html>
<body>
<formaction="index.php"method="post">
<labelfor="firstName">Firstname</label>
<inputtype="text"name="firstName"id="firstName"value=""/>
<labelfor="lastName">Lastname</label>
<inputtype="text"name="lastName"id="lastName"value=""/>
<inputtype="submit"name="submitButton"id="submitButton"
value="SendDetails"/>
</form>
</body>
</html>
<?php
}
?>
P.No:10