PHP Introduction
PHP Introduction
Easy to Learn: It is easier to learn for anyone who has come across to any programming
language for the first time.
Free of Cost: Since it is an open-source language, therefore developers are allowed to
use its components and all methods for free.
Flexible: Since It is a dynamically typed language, therefore there are no hard rules on
how to build features using it.
Supports nearly all databases: It supports all the widely used databases, including
MySQL, ODBC, SQLite etc.
Secured: It has multiple security levels provides us a secure platform for developing
websites as it has multiple security levels.
Huge Community Support: It is loved and used by a huge number of developers. The
developers share their knowledge with other people of the community that want to know
about it.
Applications of PHP
• Server-side web development: It is a development where the program runs on server
dealing with the generation of content of web page.
• Content management systems (CMS): It is a framework already designed by other
programmers and coders on which you can either contribute your knowledge and skills, or
just use those coders’ skills to design your own website or blog
• E-commerce websites: E-commerce, or electronic commerce, refers to the buying and
selling of goods and services over the internet.
• Database-driven applications: It is a software application that relies on a database to
store, manage, and retrieve data. It utilizes a database management system (DBMS) to
organize and manipulate data, enabling efficient data storage, retrieval, and management.
• Web APIs: It is an API as the name suggests, it can be accessed over the web using the
HTTP protocol. It is a framework that helps you to create and develop HTTP based
RESTFUL services.
echo
• echo is a statement, which is used to display the output.
• echo can be used with or without parentheses: echo(), and echo.
• echo does not return any value.
• We can pass multiple strings separated by a comma (,) in echo.
• echo is faster than the print statement.
?php <?php
echo "Hello by PHP echo"; echo "Hello by PHP echo
?> this is multi line
text printed by
PHP echo statement
Hello by PHP echo
";
?>
Hello by PHP echo this is multi line text printed by PHP echo statement
print
• print is a statement, used as an alternative to echo
<?php
at many times to display the output. $msg="Hello print() in PHP
• print can be used with or without parentheses. ";
• print always returns an integer value, which is 1. print "Message is: $msg";
• Using print, we cannot pass multiple arguments. Message is: Hello print() in
• print is slower than the echo statement. ?>
PHP
<?php <?php
print "Hello by PHP print "; print "Hello by PHP print
print ("Hello by PHP print()"); this is multi line
?> text printed by
PHP print statement
Hello by PHP print Hello by PHP
";
print() ?>
Hello by PHP print this is multi line text printed by PHP print statement
<?php
print "Hello escape \"sequence\" characters
by PHP print"; Hello escape "sequence" characters by PHP
?> print
Print Echo
ERROR!
Parse error: syntax error,
unexpected token "," in
/tmp/7g8h5uTI86.php on line 5
Language Basics- Data Types
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:
• Scalar Types (predefined)
• Compound Types (user-defined)
• Special Types
Language Basics- Data Types
It holds only single value. There are 4 scalar data types in PHP.
• boolean
• integer
• float
• string
Language Basics- Data Types
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.
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Language Basics- Data Types
Integer means numeric data with a negative or positive sign. It holds only whole numbers,
i.e., numbers without fractional part or decimal points.
Rules for integer:
• An integer can be either positive or negative.
• An integer must not contain decimal point.
• 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.
<?php
$dec1 = 34;
$oct1 = 0243;
Decimal number: 34
$hexa1 = 0x45; Octal number: 163
echo "Decimal number: " .$dec1. "</br>"; HexaDecimal
echo "Octal number: " .$oct1. "</br>"; number: 69
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
Language Basics- Data Types
<?php
$company = "Javatpoint";
//
both single and double quote statements will treat
different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>
Hello Javatpoint
Hello $company
Language Basics- Data Types
It can hold multiple values. There are 2 compound data types in PHP.
• array
• object
Language Basics- Data Types
• An array is a compound data type. It can store multiple values of same data
type in a single variable.
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
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
Language Basics- Data Types
<html>
<body>
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
</body>
</html>
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
The var_dump() function returns the data type and the value.
Language Basics- Data Types
• Objects are the instances of user-defined classes that can store both values
and functions. They must be explicitly declared.
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
<?php
$conn = ftp_connect("127.0.0.1") or die("Could not connect");
echo get_resource_type($conn);
?>
Language Basics- Data Types
NULL:
• A variable of type Null is a variable without any data. In PHP, null is not a value, and
we can consider it as a null variable based on 3 condition.
• If the variable is not set with any value.
• If the variable is set with a null value.
• If the value of the variable is unset.
<?php
$empty=null;
var_dump($empty);
?>
Language Basics- Data Types
<?php
$a1 = " ";
var_dump($a1);
echo "<br />";
$a2 = null;
var_dump($a2);
?>
PHP Variables
Next Top
• 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.
• After declaring a variable, it can be reused throughout the code.
• Assignment Operator (=) is used to assign the value to a variable.
PHP is a loosely typed language, it means PHP automatically converts the variable to its correct data type.
PHP Variables
Rules for declaring PHP variable:
• 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, _).
• A variable name must start with a letter or underscore (_) character.
• A PHP variable name cannot contain spaces.
• 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.
PHP Variables
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
</body>
</html>
11
float(5.5)
PHP Constant
PHP constants are name or identifier that can't be changed during the
execution.
PHP constants can be defined by 2 ways:
• Using define() function define('PI', 3.14159);
• Using const keyword const AREA_UNIT = 'square units';
<?php
const RGB = ['red', 'green', 'blue'];
echo RGB[2];
?>
blue
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
<?php
$x = 10;
$y = 4;
echo($x + $y) . "\n";
echo($x - $y) . "\n";
echo($x * $y) . "\n";
echo($x / $y) . "\n";
echo($x % $y) . "\n";
echo($x ** $y) . "\n";
?> 14
6
40
2.5
2
10000
PHP Operators
• Assignment operators are used to assign values to variables.
<?php
$aFew = 4.4;
$some = "4";
The value on both sides
if($some == $aFew ){ are not same.
echo "The value on both sides are same.";
}
else
{
echo "The value on both sides are not same.";
}
PHP Operators
• Comparison operators.
<?php
$a = 34;
$b = 34; not Equal
if('34' === 34){
echo "Equal";
}
else{
echo "not Equal";
}
<?php
$a = 42;
$b = 20; A is not less than B
if( $a < $b ) {
echo "A is less than B \n";
}else {
echo "A is not less than B \n";
}
?>
PHP Operators
• Increment operators are used to increment a variable's value while
decrement operators are used to decrement.
<?php <?php
$x = 10;
$x = 10; echo $x++ . "\n";
echo ++$x . "\n"; echo $x . "\n";
echo $x . "\n"; ?>
?>
? ?
PHP Operators
• Logical operators are typically used to combine conditional statements.
Operator Name Example Output
and And $x and $y true if both $x and $y are true
` ` Or
! Not !$x true if $x is not true
PHP Operators
• Logical operators are typically used to combine conditional statements.
<?php
$year = 2021;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 == 0))){
echo "$year is a leap year.";
} else{
echo "$year is not a leap year.";
}
?>
a = 10
b = 10
c = -10
if a > 0 and b > 0:
print("The numbers are greater than 0")
if a > 0 and b > 0 and c > 0:
print("The numbers are greater than 0")
else:
print("Atleast one number is not greater than 0")
Hello World!
Hello World!
PHP Operators
String Operators are specifically designed for strings.
<?php
$x = "Hello";
$y = " World!";
echo $x . $y . "\n";
$x .= $y;
echo $x . "\n";
?>
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue"); array(6) {
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink"); ["a"]=>
$f= $x; string(3) "Red"
$z = $x + $y; ["b"]=>
var_dump($z); string(5) "Green"
echo "\n";
["c"]=>
var_dump($x == $y);
var_dump($x == $f); string(4) "Blue"
?> ["u"]=>
string(6) "Yellow"
["v"]=>
string(6) "Orange"
["w"]=>
string(4) "Pink"
}
bool(false)
bool(true)
PHP Operators
Conditional assignment operators are used to set a value depending on
conditions.
Operator Name Example Output
?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x. The value of $x is
expr2 if expr1 = true. The value of $x is expr3 if
expr1 = false
<?php
$a = 10;
$b = 20;
$result = ($a > $b ) ? $a :$b;
Greater Value is 20
echo "Greater Value is $result\n";
?>
PHP Array
• In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
Array Items
• Array items can be of any data type.
• The most common are strings and numbers (int, float), but array items
can also be objects, functions or even arrays.
• You can have different data types in the same array.
• Array Functions
• The real strength of PHP arrays are the built-in array functions, like the
count() function for counting array items:
• PHP Indexed Arrays
• In indexed arrays each item has an index number.
• By default, the first item has index 0, the second item has item 1, etc.
• Loop through Indexed array
• PHP Associative Arrays
• Associative arrays are arrays that use named keys that you assign to
them.
Access Associative Arrays
To access an array item you can refer to the key name.
• Add Array Item
• To add items to an existing array, you can use the bracket [] syntax.
• Add Multiple Array Items
• To add multiple items to an existing array, use the array_push() function.
• Remove Array Item
• To remove an existing item from an array, you can use the array_splice()
function.
• With the array_splice() function you specify the index (where to start) and
how many items you want to delete.
• Remove Item From an Associative Array
• To remove items from an associative array, you can use the unset()
function.
• Specify the key of the item you want to delete.
• PHP - Multidimensional Arrays
• A multidimensional array is an array containing one or more arrays.
• PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However,
arrays more than three levels deep are hard to manage for most people.
• PHP - Two-dimensional Arrays
• We can store the data from the table above in a two-dimensional array, like this:
Decision Making in PHP
• Any PHP script is built out of a series of statements. A
statement can be an assignment, a function call, a
loop, a conditional statement of even a statement that
does nothing (an empty statement).
• Statements usually end with a semicolon. In addition,
statements can be grouped into a statement-group by
encapsulating a group of statements with curly
braces.
• If the condition is true, the conditional statements
will be run. However, if the condition is false, other
statements will sometimes be run instead.
Decision Making in PHP
PHP programming enables the application of decision-making by the
following conditional statements:
• if Statement
• if … else Statement
• elseif Statement
• switch Statement
Syntax:
if (condition){
// execute this block if true }
Syntax:
if (condition) {
// execute this block if the result is true
}
else{
// execute this block if the result in the first block is
false
}
<?php
if (condition) {
// execute this block if the result is true $a=10;
}
$b=20;
elseif {
// execute this block if the result in the first block is false if ($a > $b) {
}
echo "a is bigger than b";
else {
// execute this block if the result in the first and second blocks are } elseif ($a == $b) {
false
echo "a is equal to b";
}
} else {
echo "a is smaller than b";
25 is less than 100.
}
?>
Decision Making in PHP
elseif statement
Decision Making in PHP
<?php
$a=10;
$b=20;
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
a is smaller than b
Decision Making in PHP
• The switch statement executes several cases that match the
condition and executes the case block as appropriate.
• It evaluates an expression before comparing it with each case’s
values. As a result, whenever a case is matched, an identical case is
run.
• However, to use the switch statement in PHP decision-making, you
have to be familiar with two distinct terms:
break – After the code for the first true case has been run, it tells the
program to leave the switch-case statement block.
default – It is applied when there is no case in which the constant-
expression value equals the expression’s value. If there is no default
statement and there is no case match, none of the statements in the
switch body are run.
Decision Making in PHP
switch ( expression ) { <?php
case result1: $i=10;
// execute this if expression results in result1 switch ($i) {
break; case 0:
case result2: echo "i equals 0";
// execute this if expression results in result2 break;
break; case 1:
default: echo "i equals 1";
// execute this if no break statement break;
// has been encountered hitherto case 2:
} echo "i equals 2";
break;
default:
echo "i is greater than 3";
i is greater than 3 }
?>
Decision Making in PHP
Decision Making in PHP
<?php case "Fri":
$d = date("D"); echo "Today is Friday";
break;
switch ($d){
case "Mon": case "Sat":
echo "Today is Monday"; echo "Today is Saturday";
break; break;
while(condition){
//code to be executed
}
Looping Statement in PHP
<?php
1
$n=1;
2
while($n<=10){
3
echo "$n<br/>";
4
$n++;
5
}
6
?>
7
<?php 8
$n=1; 9
while($n<=10):
echo "$n<br/>"; 10
$n++;
endwhile;
?>
Looping Statement in PHP
• The do-while loop is also called an Exit control loop. The do-while loop is a variant of
while loop, which evaluates the condition at the end of each loop iteration. With a do-
while loop the block of code executed once, and then the condition is evaluated, if the
condition is true, the statement is repeated as long as the specified condition evaluated
to is true.
do{
// Code to be executed
}
while(condition);
Looping Statement in PHP
<?php
$i = 1;
The number is 2
do{
The number is 3
$i++; The number is 4
echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>
Looping Statement in PHP
• The for loop repeats a block of code as long as a certain condition is met. It is typically
used to execute a block of code for certain number of times.
Entry control loop
<?php
{ //code to be executed }
?>
Looping Statement in PHP
The parameters of for loop have following meanings:
• initialization — it is used to initialize the counter variables, and evaluated once
unconditionally before the first execution of the body of the loop.
• condition — in the beginning of each iteration, condition is evaluated. If it evaluates
to true, the loop continues and the nested statements are executed. If it evaluates
to false, the execution of the loop ends.
• increment — it updates the loop counter with a new value. It is evaluate at the end of
each iteration.
<?php
The number is 1
for($i=1; $i<=3; $i++) The number is 2
The number is 3
{ echo "The number is " . $i . “\n"; }
?>
Looping Statement in PHP
The foreach loop is used to iterate over arrays.
foreach($array as $value){
// Code to be executed
}
<?php
$colors = array("Red", "Green", "Blue");
// Loop through colors array
foreach($colors as $value){
Red
echo $value . “\n"; Green
} Blue
?>
Looping Statement in PHP
<?php
$superhero = array(
"name" => "Peter Parker",
"email" => "[email protected]",
"age" => 18
);
// Loop through superhero array
foreach($superhero as $key => $value){ name : Peter Parker
email :
echo $key . " : " . $value . "\n>";
[email protected]
} age : 18
Include and Require
• It is possible to insert the content of one PHP file into another PHP file (before the server executes it), with
the include or require statement.
• The include and require statements are identical, except upon failure:
• require will produce a fatal error (E_COMPILE_ERROR) and stop the script
• include will only produce a warning (E_WARNING) and the script will continue
• So, if you want the execution to go on and show users the output, even if the include file is missing, use the
include statement. Otherwise, in case of FrameWork, CMS, or a complex PHP application coding, always use
the require statement to include a key file to the flow of execution. This will help avoid compromising your
application's security and integrity, just in-case one key file is accidentally missing.
• Including files saves a lot of work. This means that you can create a standard header, footer, or menu file for
all your web pages. Then, when the header needs to be updated, you can only update the header include
file.
Example 1
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright © 1999-" . date("Y") . " W3Schools.com</p>";
?>
To include the footer file in a page, use the include statement:
Output
Output
• PHP include vs. require
• The require statement is also used to include a file into the PHP code.
• However, there is one big difference between include and require; when a
file is included with the include statement and PHP cannot find it, the
script will continue to execute:
Output
• If we do the same example using the require statement, the echo
statement will not be executed because the script execution dies after
the require statement returned a fatal error:
Output
Capturing Form Data
Capturing Form Data
• There exist two methods in PHP to collect data submitted in a FORM.
• In the PHP POST method, data from HTML FORM is submitted/collected using a
super global variable $_POST.
• This method sends the encoded information embedded in the body of the HTTP
request and hence the data is not visible in the page URL unlike the GET Method.
• 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 your website can be the server.
Capturing Form Data
• The GET method is used to submit the HTML form data. This data is
collected by the predefined $_GET variable for processing.
• The information sent from an HTML form using the GET method is visible to
everyone in the browser's address bar, which means that all the variable
names and their values will be displayed in the URL. Therefore, the get
method is not secured to send sensitive information.
For Example
localhost/gettest.php?username=Harry&bloodgroup=AB+
Get method in PHP
<html> Index.html
<body>
-
Get method in PHP
Advantages of GET method (method = "get")
• You can bookmark the page with the specific query string because the data
sent by the GET method is displayed in URL.
• GET requests can be cached.
• GET requests are always remained in the browser history.
</html>
Post method in PHP
• POST method is also used to submit the HTML form data. But the data
submitted by this method is collected by the predefined superglobal
variable $_POST instead of $_GET.
• Unlike the GET method, it does not have a limit on the amount of
information to be sent. The information sent from an HTML form using the
POST method is not visible to anyone.
For Example
localhost/posttest.php
Post method in PHP
Advantages of POST method (method =
"post"):
File handling is an important part of any web application. You often need to
open and process a file for different tasks.
PHP readfile() Function
The readfile() function reads a file and writes it to the output buffer.
PHP Open File - fopen()
A better method to open files is with the fopen()
function. This function gives you more options than the
readfile() function.
• PHP Create File - fopen()
• The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a
file is created using the same function used to open files.
• If you use fopen() on a file that does not exist, it will create it, given that the file is
opened for writing (w) or appending (a).
• The example below creates a new file called "testfile.txt". The file will be created in the
same directory where the PHP code resides.
• PHP Write to File - fwrite()
• The fwrite() function is used to write to a file.
• The first parameter of fwrite() contains the name of the file to write to and the second
parameter is the string to be written.
• The example below writes a couple of names into a new file called "newfile.txt":
• PHP Append Text
• You can append data to a file by using the "a" mode. The "a" mode
appends text to the end of the file, while the "w" mode overrides (and
erases) the old content of the file.
<?php
$myfile = fopen("newfile.txt", "a") or die("Unable to open
file!");
$txt = “MIT WPU\n";
fwrite($myfile, $txt);
$txt = “FYMCA\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
fruits.csv
113
Synchronous web communication
114
Web applications and Ajax
• web application: a dynamic web site that mimics the feel of a desktop
app
• presents a continuous user experience rather than disjoint pages
• examples: Gmail, Google Maps, Google Docs and Spreadsheets, Flickr, A9
115
Web applications and Ajax
• Ajax: Asynchronous JavaScript and XML
• not a programming language; a particular way of using JavaScript
• downloads data from a server in the background
• allows dynamically updating a page without making the user wait
• avoids the "click-wait-refresh" pattern
• Example: Google Suggest
116
Asynchronous web communication
CS380 117
XMLHttpRequest
118
A typical Ajax request
1. user clicks, invoking an event handler
2. handler's code creates an XMLHttpRequest object
3. XMLHttpRequest object requests page from server
4. server retrieves appropriate data, sends it back
5. XMLHttpRequest fires an event when data arrives
• this is often called a callback
• you can attach a handler function to this event
6. your callback event handler processes the data and
displays it
119
A typical Ajax request
120
Output
122
Prototype Ajax methods and
properties
event description
onSuccess request completed successfully
onFailure request was unsuccessful
request has a syntax error,
onException security error, etc.
123
Basic Prototype Ajax template
property description
the request's HTTP error code
status (200 = OK, etc.)
statusText HTTP error code text
the entire text of the fetched
responseText page, as a String
the entire contents of the
responseXML fetched page, as an XML DOM
tree
function handleRequest(ajax) {
alert(ajax.responseText);
} JS
124
125