PHP1
PHP1
PHP
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 1 / 35
Introduction
b PHP is a server-side scripting language designed specifically for the Web
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 2 / 35
Introduction
b PHP is a server-side scripting language designed specifically for the Web
- What is server-side scripting language?
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 2 / 35
Introduction
b PHP is a server-side scripting language designed specifically for the Web
- What is server-side scripting language?
/ Language designed to be executed on the server of a web application
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 2 / 35
Introduction
b PHP is a server-side scripting language designed specifically for the Web
- What is server-side scripting language?
/ Language designed to be executed on the server of a web application
- Two primary components are involved in web development:
/ Client side: Refers to the user’s web browser, where HTML, CSS, and JavaScript are
processed and executed.
/ Server side: Refers to the host of the web application that handles request, process data,
and generate dynamic content.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 2 / 35
Introduction
b PHP is a server-side scripting language designed specifically for the Web
- What is server-side scripting language?
/ Language designed to be executed on the server of a web application
- Two primary components are involved in web development:
/ Client side: Refers to the user’s web browser, where HTML, CSS, and JavaScript are
processed and executed.
/ Server side: Refers to the host of the web application that handles request, process data,
and generate dynamic content.
- What is a web server?
/ Software that handles client requests and serves web content to users over the internet
- When a user requests a web page, the web server
/ processes that request,
/ executes server-side code(s) if any,
/ retrieves data from database(s) if any,
/ sends the result to the client’s web browser. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 2 / 35
Web server
b PHP History
b Alternatives to PHP
b Open-source
<html>
<head>
<title>PHP Example</title>
</head>
<body>
<?php
echo "Hello World!";
?>
</html>
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 6 / 35
Introduction Variables
Variable
b Declared using a $ sign followed by the name of the variable. As loosely typed language, the
declaration of the data type of the variables are not required. Variable names are case-sensitive
$abc = 1.0; $bcd = "bcd"; $cde = true; $def = array("abc", "bcd", "cde");
b Superglobal Variables → Predefined variables that are accessible from any part of the script
regardless of scope.
- $_GET, $_POST, and $_REQUEST are used to access user input via URL parameters, HTTP POST
requests, and HTTP cookies in the form of associative array.
- $_SERVER is used to collect information about server environment
- $_COOKIE is used to collect HTTP cookie values in the form of an associative array
- $_ENV is used to collect information about the environment variables
- $_SESSION is used to store and retrieve user-specific data across multiple requests.
- $_FILES is used to access files that are uploaded via an HTTP POST request.
- $GLOBALS allows to access all global variables. Useful for debugging
b The scope of a variable is the portion of the program within which it is defined and can be accessed.
PHP has three types of variable scopes: Local, Global and Static
b The default sope is depends on, where the variables are declared/defined. PHP also has a concept
called class scope, which are based on access modifiers (public, private, or. protected)
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 7 / 35
Introduction Scope of variables
Local variable
b Local variables are variables that are declared within a function or method. They are only accessible
within the function where they are declared. Value of such variables are not accessible outside the
function’s curly braces {}
1 <?php
2 $abc = 3; /*global scope*/
3 function testFunction(){
4 var_dump($abc);
5 $abc = 1; /*local scope*/
6 var_dump($abc);
7 }
8 testFunction(); //output: NULL (with Warning: Undefined variable $abc)
9 //int(1)
10 var_dump($abc); //int(3)
b Local variables are limited to the scope in which they are declared, providing encapsulation and
helping to prevent naming conflicts
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 8 / 35
Introduction Scope of variables
Global variable
b Global variables in C are automatically available to functions unless specifically overridden by a local
definition. In PHP global variables must be declared global inside a function if they are going to be
used in that function
1 <?php
2 $abc = 3; $bcd = 0; /*Global scope*/
3 function testFunction(){
4 global $abc; /*1st approach I to use a global variable*/
5 $bcd = 2; /*Local scope*/
6 $GLOBALS['bcd'] = $GLOBALS['abc']; /*2nd approach to use a global variable*/
7 echo $abc. " ". $bcd;
8 }
9 testFunction(); //3 2
10 var_dump($bcd); //int(3)
b $GLOBALS is an associative array with the name of the global variable being the key and the contents
of that variable being the value of the array element
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 9 / 35
Introduction Scope of variables
Static variable
b Static variable are local variable that maintains its value across multiple calls. The static keyword is
used to define a static variable
1 <?php
2 function testFunction() {
3 static $abc = 0;
4 $abc++;
5 echo "value of abc: $abc\n";
6 }
7 testFunction(); //output: value of abc: 1
8 testFunction(); //output: value of abc: 2
9 testFunction(); //output: value of abc: 3
b Unlike local variables, static variables are not destroyed when a function finishes its execution.
Instead, they retain their values.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 10 / 35
Introduction Constant
Constant
b Identifiers that do not change during the execution of a script. Constant names are case-sensitive.
b Unlike variables, scope of constants are global across the entire script.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 11 / 35
Introduction Constant
Constant
b Identifiers that do not change during the execution of a script. Constant names are case-sensitive.
b Unlike variables, scope of constants are global across the entire script.
b Constant can be defined using two ways - Using define() function and const keyword
- define() function defines a named constant. Returns true on success and false otherwise.
/ Syntax: define("name", value);
/ Example: define("PI",3.1459); echo PI;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 11 / 35
Introduction Constant
Constant
b Identifiers that do not change during the execution of a script. Constant names are case-sensitive.
b Unlike variables, scope of constants are global across the entire script.
b Constant can be defined using two ways - Using define() function and const keyword
- define() function defines a named constant. Returns true on success and false otherwise.
/ Syntax: define("name", value);
/ Example: define("PI",3.1459); echo PI;
- Using const keyword
/ Syntax: const name=value;
/ Example: const PI = 3.1459; echo PI;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 11 / 35
Introduction Constant
Constant
b Identifiers that do not change during the execution of a script. Constant names are case-sensitive.
b Unlike variables, scope of constants are global across the entire script.
b Constant can be defined using two ways - Using define() function and const keyword
- define() function defines a named constant. Returns true on success and false otherwise.
/ Syntax: define("name", value);
/ Example: define("PI",3.1459); echo PI;
- Using const keyword
/ Syntax: const name=value;
/ Example: const PI = 3.1459; echo PI;
b Value of a constant may be another constant.
define("ABC", "nested??"); define("BCD", ABC); echo BCD; //output: nested??
b defined() function checks whether a constant with the given name is defined.
var_dump(defined("ABCD"));//output: bool(false)
b constant() function returns the value of the constant.
- The output echo PI; and echo constant("PI"); are equivalent. . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 11 / 35
Introduction Constant
Magic constant
<?php
namespace webClass;
trait testTrait{
public function testLab(){
echo "\nCurrent trait: ".__trait__; output:
echo "\nCurrent class: ".__class__; Current trait: webClass\testTrait
echo "\nCurrent method: ".__method__; Current class: webClass\testClass
} Current method: webClass\testTrait::testLab
}
class testClass {use testTrait;}
$obj = new testClass();
. . . . . . . . . . . . . . . . . . . .
$obj->testLab(); . . . . . . . . . . . . . . . . . . . .
[email protected] PHP 13 / 35
Introduction Constant
/*output
traitSpace\testTrait::testMethodConst
traitSpace\testClass
. . . . . . . . . . . . . . . . . . . .
traitSpace\testClass . . . . . . . . . . . . . . . . . . . .
*/ [email protected] PHP 14 / 35
IO Statements Output
Output streams
b echo: Statement, displays one or more strings or values of variables to the browser.
- $courseName = " Web Technology "; $courseCode = 2015;
- echo $courseCode, $courseName; //output: 2015 Web Technology
b print: Statement, similar to echo, but it can output only one value/variable.
- print $courseCode; print $courseCode . $courseName; //note the concatenation
b printf: Function, displays formatted output. Does not return a value, it outputs directly to screen
- printf("Course name: %s, \tCourse code: %d", $courseCode, $courseName);
b sprintf: Function, returns the formatted string, which can be stored in a variable or used in
subsequent operations.
- sprintf("Course name: %s Course code: %d", $courseCode, $courseName);//no output
- $str = sprintf("Course name: %s, \tCourse code: %d", $courseCode, $courseName);
- $str = sprintf("select * from users where cName = '%s' ", $courseName);
- echo str;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 15 / 35
IO Statements Debugging
Debugging functions
b print_r: Displays content of a variable, such as an array or object, in human readable format.
<?php
$courseName = array("Web Technology", "DBMS", "Computer Network", "Theory of Computation");
echo $courseName; //output: Array with a warning: Array to string conversion
print $courseName; //output: Array with a warning: Array to string conversion
printf($courseName);//TypeError: printf(): Argument #1 ($format) must be of type string
print_r($courseName);
/*Output
Array
(
[0] => Web Technology
[1] => DBMS
[2] => Computer Network
[3] => Theory of Computation
)
. . . . . . . . . . . . . . . . . . . .
*/ ?> . . . . . . . . . . . . . . . . . . . .
[email protected] PHP 16 / 35
IO Statements Debugging
Debugging functions
b var_dump: Used for debugging and inspecting variables. It provides detailed information about a
variable, including its type and value
<?php
$courseName = array("Web Technology", "DBMS", "Computer Network", "Theory of Computation");
var_dump($courseName);
/*Output
array(4) {
[0]=>
string(14) "Web Technology"
[1]=>
string(4) "DBMS"
[2]=>
string(16) "Computer Network"
[3]=>
string(21) "Theory of Computation"
}
. . . . . . . . . . . . . . . . . . . .
*/ . . . . . . . . . . . . . . . . . . . .
[email protected] PHP 17 / 35
IO Statements Input
Input streams
b CLI-based mechanism
- Read one line: $line = trim(fgets(STDIN));
- Read multiple lines: fscanf(STDIN, "%d\n", $number);
b Form-based mechanism
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 18 / 35
IO Statements Input
b PHP reDirect.php
<?php
$cName = $_POST['cName'];
$cCode = $_POST['cCode'];
echo "Course Name: ". $cName. "and code: ". $cCode;
?>
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 19 / 35
IO Statements Input
b GET method appends data into the URL as query parameters, thus, limited by the maximum length
of a URL.
http://localhost/classTest/reDirect.php?cName=WebTechnology&cCode=CS2015
b However, the POST method sends data as a part of the body of the HTTP(S) request. Thus, POST
method can transmit larger amounts of data.
http://localhost/classTest/reDirect.php
b GET method is suitable for searching, filtering, and navigation, where state of the server will not
change. The POST method is suitable for form submissions, file uploads, and other actions that
change data on the server and contains sensitive information.
https://www.google.com/search?q=how+to+install+apache+&sca_esv=47...
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 20 / 35
IO Statements Input
b action: Specifies the URL to which the form data should be submitted when the user clicks the
submit button. <form action="submitForm.php" >
b method: Defines the HTTP method to be used when submitting the form. <form method="get">
b enctype: Specifies the encoding type used for sending data to the server when the form is submitted.
<form enctype="multipart/form-data">
b autocomplete: Specifies whether the browser should automatically complete the form values based
on the user’s input history. <form autocomplete="on">
b novalidate: Boolean attribute. If present, disables browser validation of form elements. Useful for
custom validation with JavaScript. <form novalidate>
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 21 / 35
IO Statements Input
b name: Assigns a name to the form, which can be used for scripting or styling purposes.
<form name="firstForm">
b Global attribute such as id, and class are also used for scripting or styling purposes.
<form name="firstForm" id="firstForm" class="firstForm">
b target: Specifies where to open the response from the server after form submission.
<form target="_blank">
b accept-charset: Specifies the character encodings that are to be used for the submission of the form
data. <form accept-charset="UTF-8">
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 22 / 35
Data Type Introduction
Types of Data
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 23 / 35
Data Type Introduction
Types of Data
b Scalar Type
- boolean
- integer
- float
- string
b Compound Type
- array
- object
b Special Type
- resource
- null
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 23 / 35
Data Type Scalar Type
Boolean Type
b Predefined constant with two values - True and False. Not case sensitive
b $a=true; $b=false; $c = (1 == 1); $d = (bool) 0; $e = (bool) "test";
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 24 / 35
Data Type Scalar Type
Boolean Type
b Predefined constant with two values - True and False. Not case sensitive
b $a=true; $b=false; $c = (1 == 1); $d = (bool) 0; $e = (bool) "test";
b Discuss the output of the following code segments
Segment I: $x=true; $y=false; var_dump($z=$y OR $x);
Segment II : $x=true; $y=false; $z=$y OR $x; var_dump($z);
Segment III : $x=true; $y=false; $z=$y || $x; var_dump($z);
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 24 / 35
Data Type Scalar Type
Boolean Type
b Predefined constant with two values - True and False. Not case sensitive
b $a=true; $b=false; $c = (1 == 1); $d = (bool) 0; $e = (bool) "test";
b Discuss the output of the following code segments
Segment I: $x=true; $y=false; var_dump($z=$y OR $x);
Segment II : $x=true; $y=false; $z=$y OR $x; var_dump($z);
Segment III : $x=true; $y=false; $z=$y || $x; var_dump($z);
The output of Segment II $z=$y OR $x; var_dump($z); is false, while other two are true. The OR
operator has lower precedence than assignment operator, thus, it will be like ($z=$y) OR $x rather
than $z=($y OR $x), whereas, in Segment II, the || operator has higher precedence than assignment.
Thus, the expression is equivalent to $z=($y || $x).
b When converting to bool, the following values are considered false: the boolean false itself, the integer
0, the floats 0.0 and -0.0, the empty string “”, the string “0”, an array with zero elements, the unit
type NULL and internal objects that overload their casting behaviour to bool.
Every other value is considered true.
b The (bool) cast is used to explicitly convert a value to bool
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 24 / 35
Data Type Scalar Type
Integer Type
b Represent whole numbers without decimal points. It can be octal, hexadecimal, +ve and -ve decimal
with range: -231 to 231 or zero.
b echo PHP_INT_SIZE; is used to print the size of the integer in bytes. While echo PHP_INT_MAX; and
echo PHP_INT_MIN; are used to print maximum and minimum supporting integer.
b Check the output of $d = dechex($c); echo $d; and $e = 3.14; echo round($e);
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 25 / 35
Data Type Scalar Type
b Floating point numbers (also known as “floats”, “doubles”, or “real numbers”) can be specified using
any of the syntaxes: $a = 1.234; $b = 1.2e3; $c = 7E-10; $d = 1_234.567;
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 26 / 35
Data Type Scalar Type
b Decimal: 1_000
b Scientific: 3.14_491_234e-12
b Float: 0.314_213_423_543_124_123
b Binary: 0b1001_0010_0001_1011_1111_1010_1110_1010
b Octal: 0123_456
b Hexa-decimal: 0xBEEF_BABE
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 27 / 35
Data Type Scalar Type
b Decimal: 1_000
b Scientific: 3.14_491_234e-12
b Float: 0.314_213_423_543_124_123
b Binary: 0b1001_0010_0001_1011_1111_1010_1110_1010
b Octal: 0123_456
b Hexa-decimal: 0xBEEF_BABE
b Pattern which will generate errors
- Two or more underscores: 1__000
- Underscores before and after the number: _16 and 16_
- Underscore around the decimal point: 1_.6 or 1._6
- Underscore around number notation: 0_b01010 or 0_x_f00d or 3.1e_-12
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 27 / 35
Data Type Scalar Type
Strings
b A string is a sequence of chars
<?php $strTest = "this is a sequence of chars";
echo $strTest[0]; //output: t
echo $strTest; //output: this is a sequence of chars
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 28 / 35
Data Type Scalar Type
Strings
b A string is a sequence of chars
<?php $strTest = "this is a sequence of chars";
echo $strTest[0]; //output: t
echo $strTest; //output: this is a sequence of chars
b A single quoted strings is displayed as-it-is
<?php $age = 20;
$strTest = 'I am $age years old'; // output: I am $age years old
$strTest = "I am $age years old"; // output: I am 20 years old
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 28 / 35
Data Type Scalar Type
Strings
b A string is a sequence of chars
<?php $strTest = "this is a sequence of chars";
echo $strTest[0]; //output: t
echo $strTest; //output: this is a sequence of chars
b A single quoted strings is displayed as-it-is
<?php $age = 20;
$strTest = 'I am $age years old'; // output: I am $age years old
$strTest = "I am $age years old"; // output: I am 20 years old
b String concatenation
<?php $str = "This is "."a "."concatenated "."string";
echo $str; // output: is a composed string
$newStr = 'Also $str '.$str;
echo $newStr; // output: Also $str This is a concatenated string
b is_string($variableName) function finds whether a variable is of type String
. . . . .or
. .not.
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 28 / 35
Data Type Compound Type
Array-I
b Used to store a collection of values, which can be of different data types such as integers, strings, or
even other arrays
- $arr = array (1, "PHP", true, 3.14, array(10,20,30)); var_dump($arr);
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 31 / 35
Data Type Compound Type
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 31 / 35
Data Type Compound Type
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 31 / 35
Data Type Compound Type
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 31 / 35
Data Type Compound Type
Object Type
b Represents an instance of a class. An object is created using the new keyword followed by the class
name and a set of parentheses
b Ways to define object: $a = new className();, $b = new class{};, and $c = (object)[];
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 32 / 35
Data Type Special Type
Resource Type
b Represents an external resource such as a file handle, database connection, image, or network socket
b Resource variables cannot be manipulated directly by PHP code, rather PHP has a dedicated set of
functions that interacts with an the system
b Resource variable needs to close properly after use to get rid of memory leakage.
NULL Type
b Represents a value that is undefined, non-existent, or absence of a value. For example: $a = NULL;
b NULL represents a lack of a value, it does not provide any information about the data type that the
value should be. For example: $a = 1; $a = null; var_dump(is_int($a));
b PHP automatically converts a value to a different data type if needed. This can lead to unexpected
behavior. For example: $a = null; $b = ""; var_dump(is_null($a)); var_dump(is_null($b));.
Variable $a is NULL variable and $b is a string, which is an empty. But var_dump($a == $b); will
generate true.
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 34 / 35
Data Type Type Coercion
Type Coercion
b Process of automatic conversion of a value from one data type to another data type
b String to Boolean: $a = ""; $b = "0"; $c = "1"; if($a) echo "True"; else echo "False";
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
[email protected] PHP 35 / 35