PHP Basic
PHP Basic
Prof.#Dr.#Carlos#Alves
1
PHP#Basic
PHP#HTML#Forms
PHP#Sessions/Cookies PHP
PHP#and#MySQL
PHP#Advanced
2
• Introduction
• Syntax
• Variables
• Constants
• Print
• Data#Types
PHP#Basic • Operators
• If
• Switch
• Strings
• Arrays
• Loops
• Functions
Foto%de%Clay Leconey na%Unsplash% 3
• PHP stands for Hypertext Preprocessor. PHPTBasic
• PHP is an open source server4side scripting language
• Dynamically generated web pages
• Free
• PHP is a hybrid of Perl, Java and C
• Created by Rasmus Lerdorf in 1994.
PopularTsitesTusing PHP
Facebook.com
Wikipedia.org
Wordpress.org
PHP is used by 77.5% of all the websites whose server4side programming Pinterest.com
language Vimeo.com
(2023/04/17 https://w3techs.com/technologies/details/pl4php) Wordpress.com
Mozilla.org
Europa.eu
Tumblr.com
Digicert.com
4
PHP#Basic
PHP#Can#Do#:
• Generate pages and files#
dynamically
• Create,#open,#read,#write and Advantages of PHP#[https://www.tutorialrepublic.com/phpHtutorial/]:
close files#on the server • Easy to'learn: PHP'is easy to'learn and use.'For'beginner
• Collect data#from a#web#form programmers who just started out'in'web'development,'PHP'
such as#user information,#email,# is often considered as'the preferable choice of language to'
phone no,#etc learn
• Send emails#to#the users of your • Open'source: PHP'is an open@source project.'It is developed
website and maintained by a'worldwide community of developers
• Send and receive cookies#to#track who make its source code freely available to'download'and
the visitor of your website use
• Store,#delete,#and modify • Portability: PHP'runs'on various platforms such as'Microsoft'
information in#your database Windows,'Linux,'Mac'OS, etc.'and it is compatible with almost
• Restrict unauthorized access to#a# all servers'used today such Apache,'IIS, etc
website • Fast Performance: Scripts'written in'PHP'usually execute'or
• Encrypt data runs'faster than those written in'other scripting languages like
• Send and receive cookies ASP,'Ruby,'Python,'Java,'etc
• Vast Community: Since PHP'is supported by the worldwide
community,'finding help or documentation related to'PHP'
online'is extremely easy.
5
PHPABasic
Why PHP?
• Error Handling
• Supports stricter Type Declarations for function arguments
• Supports new operators (like the spaceship operator: <=>)
6
• PHP code editable by any texto editor PHPIBasic
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code is executed on the server, and the result is returned to the browser as plain HTML
• PHP can be embedded within a normal HTML web page
• Inside your HTML document you can write the PHP statements
• PHP files have extension ".php"
<!DOCTYPEIhtml>
<html>
<body>
<?php
echo "Hello World,Ithis my first PHPIscript!";
?>
</body>
</html>I
7
• Install Wampserver or XAMPP, or other
• Create web applications with Apache PHP>Basic
• MySQL database
• Place them in>your web>directory,>and the server>will automatically parse>them for>you
• You do>not need to>compile>anything or install any extra>tools
hello.php
<!DOCTYPE>html>
<html>
<body> C:\xamp\htdocs\lpi
<?php
echo "Hello World,>this my first PHP>script!";
?>
</body>
</html>>
http://localhost/lpi/hello.php
8
PHP3Basic
<?3
echo (“Olá Mundo3<br>");3
?>3
<script3language="php">
echo(“Olá Mundo<br>”);
</script>3
<%3
<?php echo (“Olá Mundo<br>");3
echo (“Olá Mundo<br>");3 %>3
?>3
9
PHP1Basic
<?php
PHP Comments: /*1this is a1mul67line
comment */1
echo(“Olá Mundo\n");1
?>1
/*1*/1(type c)
<?php
#1this is a1one line comment
echo(“Olá Mundo\n");1
?>1
10
PHP3Basic
<?php
Case Sensitivity in PHP: //3Assign value to3variable
$name =3”John";3
//3Try to3print3variable value
echo "The name is "3.3$name .3"<br>";3
echo "The Name is "3.3$Name .3"<br>";3
• Variable names in3PHP3are3caseKsensiLve.3As3a3 echo "The NAME3is "3.3$NAME3.3"<br>";3
result the variables $name,3$Name and $NAME3 ?>
are3treated as3three different variables
11
PHP,Basic
PHP Variables:
• A,variable does,not need to,be declared before adding a,value to,it
• PHP,automatically associates a,data,type to,the variable
• The assignment operator (=),used to,assign value to,a,variable
• A,variable starts with the $,sign,,followed by the name of the variable
• A,variable name must,start with a,letter or the underscore character
• A,variable name cannot start with a,number
• A,variable name can,only contain alphaCnumeric characters and underscores (ACz,,0C9,,and _,)
• Variable names are,caseCsensitive ($age,and $AGE,are,two different variables)
<?php
$var =,"Bob";,
$Var,=,"Joe";,
echo,"$var,,$Var";,//,Display,"Bob,,Joe",
$4site,=,'not,yet';,//,NOT,valid;,starts,with,digit,
$_4site,=,'not,yet';,//,valid;,starts,with,underline,
$täyte =,'mansikka';,//,valid;,'ä',is,ASCII,228
?>, 12
PHP/Basic
PHP Constants:
<?php
///Define/the constant
define(”LPI",/”PHP/Language");/
///Use/the constant
echo 'Thank you for/learning G '/./LPI;/
?>
13
PHP2Basic
<?php
$php =2"2PHP2Language";
$txt =2“www.ipcb.pt/estcb/escola@superior@de@tecnologia2";
$num2=25;
14
PHP2Basic
<?php
$php =2"2PHP2Language";
$txt =2“www.ipcb.pt/estcb/escola@superior@de@tecnologia2";
$num2=25;
<?php
$php =2"2PHP2Language";
$txt =2“www.ipcb.pt/estcb/escolaAsuperiorAdeAtecnologia2";
$num2=25;
print2"<h2>"2.2$php .2"</h2>";
print2"Study “.2$php.2“2at "2.2$txt .2"<br>";
print2($num)2;
?>
16
PHP+Basic
17
PHP1Basic
<?php
$n11=1123;1//1decimal1number
$n21=19123;1//1a1negative1number
$n31=10x1A;1//1hexadecimal
$n41=10123;1//1octal1number
$n51=10b100111;1//1binary number
?>
18
PHP1Basic
19
PHP-Basic
<?php
$n1-=-112.234;-
$n2-=-12.3e4;-
$n3-=-3EM10;
?>
20
PHP-Basic
21
PHP1Basic
<?php
$x1=1true;
$y1=1false;
?>
22
PHP2Basic
PHP2Nan
• NaN stands2for2Not a2Number.
• NaN is used for2impossible mathemaGcal operaGons
• funcGons to2check if a2value is not a2number:
• is_nan()
• var_dump()3func6on returns the data3type and value
23
PHP7Basic
$n7=7"123";
var_dump(is_numeric($n));7//7Displays7bool(true)7
$n7=7"123.45"7+7100;
var_dump(is_numeric($n));7//7Displays7bool(true)7
$n7=7"Hello";
var_dump(is_numeric($n));7//7Displays7bool(false)7
?>
24
PHP8Basic
<?php
$x8=812345.678;
$foat_int_cast =8(int)$x;8//8Cast8float to8int
echo $float_int_cast;
$x8=8"12345";
$str_int_cast =8(int)$x;8//8Cast8string to8int
echo $str_int_cast;
?>8
25
PHP/Basic
26
PHP5Basic
$a[1]5=5$f;
• Arrays currently act as5hash tables (associa;ve arrays)5
$a["foo"]5=5$f;5
and indexed arrays (vectors)
$a[1][0]5=5$f;5
<?php
$a[3]['bar']5=5'Bob’; $a["foo"][2]5=5$f;5
echo5" This won't work :5$a[3][bar]";5 $a[3]["bar"]5=5$f;5
$a["foo"][4]["bar"][0]5=5$f;
echo5" This will work :5{$a[3][bar]}5"; ?>5
echo5" This will work :"5.5$a[3][bar];
?>5
27
PHP6Basic
<?php
$a6=6array("apple"6=>6array(6
PHP data types (mul./dimensional arrays):
"color"6=>6"red",6
"taste"6=>6"sweet",6
• Arrays currently act as6hash tables "shape"6=>6"round"6),
(associative arrays)6and indexed
arrays (vectors) "orange"6=>6array(6
"color"6=>6"orange",6
<?php
"taste"6=>6"acidic",6
$a6=6array6(
<?php "shape"6=>6"round"6),6
$a["cor"]6=6”red";6 "cor"6=>6"vermelho",6
"banana"6=>6array(6
$a["sabor"]6=6”sweet";6 "sabor"6=>6"doce",6
"color"6=>6"yellow",6
$a["forma"]6=6”round";6 "forma"6=>6"redondo",6
"taste"6=>6"doughy",6
$a["nome"]6=6”apple";6 "nome"6=>6"maçã",6
"shape"6=>6"cylindrical"6)6
$a[3]6=64;6 36=>646
);6
?>6 );
echo6$a["apple"]["taste"];6#6show6"sweet"6
?>6
?>6 28
PHP1Basic
<?php
$str =0"Hello World!";0
echo "$str <br>";
$str =0NULL;
echo "$str <br>";
?>
30
PHP2Basic
• A2resource is a2special variable that holds a2reference to2an external resource (file2
or database)
<?php
$file_handle =2fopen("my_file.txt",2"r");
$conn =2mysqli_connect("localhost",2"root",2"");
?>
31
PHP2Basic
<?php
$str12=2'Hello!';2
echo $str12.2"<br>";2
$str22=2"Hello class!";2
echo $str22.2"<br>";2
$str32=2'Hello,2I\’m2here.';2
echo $str3;
?>
32
PHP2Basic
33
PHP2Basic
<?php
define(name,0value,0case*insensitive) define("PHP",0"Welcome to0PHP0language!");
echo PHP;
define("GREETING",0"0Welcome to0PHP0language!",0true);
• name:0Specifies the name of the constant echo php;
• value:0Specifies the value of the constant ?>0
• case*insensi-ve:0Specifies whether the
constant name should be caseTinsensi5ve.0
Default is false
35
PHP0Basic
<?php
$n10=011;0$n20=05;0$n30=0"11";0
if ($n10==0$n3)0echo "TRUE<br>";0
else echo "FALSE<br>";0//0Displays:0boolean TRUE0
if ($n10===0$n3)0echo "TRUE<br>";0
else echo "FALSE<br>";0//0Displays0:0boolean FALSE0
if($n10>0$n2)0echo "TRUE<br>";0
else echo "FALSE<br>";0//0Displays:0boolean TRUE
?>
39
PHP0Basic
String Operators
• The two operators are0designed for0strings <?php
$str10=0"Hello ";0
$str20=0"my Friends!";0
$str30=0"Class!";0
echo $str10.0$str20.0"<br>";0
$str10.=0$str3;
echo "str3<br>";?>
43
PHP0Basic
Array Operators
• The comparison operators are0used to0compare0arrays
• Test condi8ons in4the form of expressions that evaluates to4either true or false4and based on
these results you can4perform certain ac8ons
• if statement
• if...else statement
• if...elseif....else statement
<?php
if(condition1){
//"Code to"be executed if condition1"is true
}4elseif(condition2){
//"Code to"be executed if the condition1"is false"and condition2"is true
}4elseif(condition3){
//"Code to"be executed if the condition1"and condition2"are"false"and condition3"is true
}4elseif(condition_n){
//"Code to"be executed if ...
}4else{
//"Code to"be executed if both ALL"conditions before are"false
}?>
45
PHP7Basic
<?php
if($age7<767){7
echo 'Middle age';7//7output7if age7is less than 67
}7else{7
echo 'Ancient';7//7output7if age7is greater than or equal to767
}
?>
<?php
echo ($age7<718)7?7'Middle age'7:7'Ancient ';
?>
46
PHP5Basic
PHP Conditional Statements (switch):
• The switch statement select one of many blocks of code to5be executed
• The switch>case5statement is an alternative to5the if>elseif>else statement
• Do5"almost"5the same
• The switch>case5statement tests a5variable against a5series5of values until it finds a5match
• Then executes5the block of code corresponding to5that match5...
• ...5And also executes5all the subsequent case5statements till the end of the switch block ...
• ...5The break statement tells PHP5to5break5out5of the switch>case5statement block once it executes5the
code associated with the first true case5automatically
<?php
switch($var){
case5value1:
//5To5be executed if $var=value1
break;
case5value2:
//5To5be executed if $var=value2
break;
...
default:
//5To5be executed if $var5is different from all values
}
?> 47
PHP6Basic
PHP Condi(onal Statements (switch):
<?php
$login6="client";
switch($login){
case6"client":
echo "Hello client.";
//break;
case6"employee":
echo "Hello employee.";
break;
case6"admin":
echo "Hello admin.";
break;
default:
echo "Not known.";
break;
}?>
48
PHP(Basic
PHP Loops:
49
PHP/Basic
• The while statement will loops through a/block of code as/long as/the condition specified in/the
while statement evaluate to/true
<?php
while(condition){ $i/=/0;
///Code to/be executed echo "Even number less then 20:<br>";/
} while($i/</20){/
$i+=2;/
echo $i/./"<br>";/
}
?>/
50
PHP1Basic
<?php
$i1=10;
echo "Even number less then 20:<br>";1
do{1 <?php
do1{ $i+=2;1 $i1=1100;
//"Code to"be executed;
echo $i1.1"<br>";1 echo "Even number less then 20:<br>";1
}1while (condi/on is true); ]1while($i1<120); do{1
?>1 $i+=2;1
echo $i1.1"<br>";1
]1while($i1<120);
?>1
51
PHP,Basic
<?php
echo "Even number less then 20:<br>";,
for,($i=0;,$i,<,20;,$i+=2)
echo $i,.,"<br>";
for(iniJalizaJon;,condiJon;,increment){ ?>,
//,Code to,be executed
}
• array — the array over which all its elements are0to0be traversed
• key — the index of the current array element
• value — the content of the current array element
53
PHP0Basic
<?php
$person =0array("Albert"=>"Portugal",0
"Jonh"=>"EUA",0"Mary"=>"Tunisia");
while0(list(,0$value)0=0each0($person))0{0 <?php
54
PHP/Basic
<?php
for/($n=0;/$n/</20;/$n++)
if ($n/==/10) <?php
break; $person =/array("Albert"=>"Portugal",/
else "Jonh"=>"EUA",/"Mary"=>"Tunisia");
echo $n."<br>";//
?>/ for/($n=0;/$n/<=/2;/$n++)
if ($n/!=/1)
echo $person[$n]."<br>";
else
break;
?>
55
PHP0Basic
<?php
for0($n=0;0$n0<020;0$n++) <?php
if ($n0%020==00) $person =0array("Albert"=>"Portugal",0
continue; "Jonh"=>"EUA",0"Mary"=>"Tunisia");
else
echo $n."<br>";00 for0($n=0;0$n0<=02;0$n++)
?>0 if ($n0!=01)
echo $person[$n]."<br>";
else
conUnue;
?>
56
PHP/Basic
<?php
PHP Loops (con*nue): for/($x=1;/$x<=10;/$x++)
{
echo "x=$x:<br>";
for/($y=$x;/$y<=10;/$y++)
{
echo "   y=$y:<br>";
for/($z=$y;/$z<=10;/$z++)
{
<?php if ($z/==/5)
for/($x=1;/$x<=10;/$x++) continue/3;
{ else
echo "x=$x:<br>"; echo " /x=$x,/y=$y,/z=$z<br>";
for/($y=$x;/$y<=10;/$y++) }
{ }
echo "   y=$y:<br>"; }?>
for/($z=$y;/$z<=10;/$z++)
{
echo " /x=$x,/y=$y,/z=$z<br>";
}
}
}?>
57
PHP+Basic
PHP Func'ons:
• A+function is a+self4contained block of code that performs a+specific task
• PHP+has more+than 1000+built4in+functions
• PHP+allows to+define+own functions
• A+function name must+start with a+letter or underscore character not with a+number,+optionally
followed by the more+letters,+numbers,+or underscore characters.+Function names are+case4
insensitive
• A+function will not execute+automatically when a+page loads
• A+function will be executed by a+call to+the function
<?php
//+Defining the func'on
function functionName($oneParameter,+$twoParameter,+...){ func'on helloworld(){+
//+Code to+be executed echo "Hello World";+
} }+
//+Calling the func'on
helloworld();
?>+
58
PHP2Basic
<?php
//9Defining the function
function multiplication($p1,9$p2=7){9
echo $p1."*".$p2."=".$p1*$p2."<br>";9
}9
//9Calling the function
multiplication(4);
$x9=911;
$y9=93;
multiplication($x,$y);
?>9
60
PHP6Basic
• A6function can6return a6value back to6the script6that called it,6using the return statement
• The return value can6be of any type (including arrays and objects)
• A6function can6not return multiple values,6but can6an array ...
<?php
function multiplication($p1,6$p2){6 <?php
return $p1*$p;6 function multiplication($p1,6$p2){
}6 $sum6=6$p1+$p;
$dif =6$p1T$p;
$x6=611; $mul =6$p1*$p;
$y6=63; return array($sum,$dif,$mul);6
echo multiplication($x,$y); }6
?>6
list($s,$d,$m)6=6multiplication(12,4);
?>6
61
PHP7Basic
<?php
function f7($p1){7
$p17+=77;7 <?php
}7 function f7(&$p1){7
$p17+=77;7
$x7=711; }7
f7($x);
echo $x; $x7=711;
?>7 f7($x);
echo $x;
?>7
62
PHP6Basic
63
PHP8Basic
<?php
function f8(){8
$p8=87;
echo "Inside f():8"8.8$p;8//outputs8Inside f():87
}8
f8();
echo $p;8//outputs8Undefined variable:8p
?>
64
PHP8Basic
<?php
$name =8"Abdel";8
func'on f8(){8
$p8=8123;
echo "Inside f():8p="8.8$p;8//8outputs8p=123
echo "name=".8$name .8"<br>";8//outputs8Undefined variable:8name
}8
f8();
echo "Outside f():8p="8.8$p;8//outputs8Undefined variable:8p
echo "name=".8$name .8"<br>";8//outputs8name=Abdel
?>
65
PHP8Basic
<?php
$name =8"Abdel";8 <?php
$msg =8'Portugal';8//8global8var
funcKon f8(){8
$p8=8123; function f()
echo "Inside f():8p="8.8$p;8//8outputs8p=123 {
echo "name=".8$name .8"<br>";8//outputs8Undefined variable:8name $msg =8'Tunisia';8//8local8var
}8 echo "In:8".8$msg ."<br>";8//8outputs8In:Tunisia
}
f8();
echo "Outside f():8p="8.8$p;8//outputs8Undefined variable:8p f();
echo "name=".8$name .8"<br>";8//outputs8name=Abdel echo $msg;8//8outputs8Portugal
?> ?>
66
PHP8Basic
<?php
$msg =8'Portugal';8//8global8var
function f()
{
global8$msg;8//8global8var
echo "In:8".8$msg ."<br>";8//8outputs8In:Portugal
$msg =8'Tunisia';
}
67
PHP8Basic
<?php
func'on f()
{
sta'c $p=1;8
echo $p8."<br>";8//8outputs818283
$p++;
}
f();
f();
f();
?>
68
PHP(Basic
Quiz:
69
PHP(Basic
Quiz:
Considering the PHP(language,(if the code contains the variables "$color",("$COLOR",(and "$coLOR",(will result:(
o which are(interpreted as(the same variable
o which are(interpreted as(3(different variables
o in(a(syntax error(message
o in(a(semantic error(message
70
PHP(Basic
Quiz:
In(PHP,(what is the operator used to(check if two variables are(equal and of the same data(type?
o !=
o =
o ==
o ===
71
PHP(Basic
Quiz:
From the following options,(indicate the valid options for(referencing an element of an array:
! $a[1,"cor"]
! $a[1][3](
! f $a[1]["color"]
! $a(1)("color")
72
PHP(Basic
Quiz:
Write the func4on with the name “f_quiz”,(in(PHP,(that simultaneously returns half,(double and the square of the
value passed in(the parameter,(named “param1”,(as(a(reference.
73