0% found this document useful (0 votes)
14 views

Php Introduction File1

PHP is a server-side scripting language created in 1994, primarily for web development, and it is open-source and free to use. PHP files can contain various types of code and are executed on the server to generate HTML for the browser. The document also covers installation instructions for XAMPP, basic PHP syntax, variables, data types, and arrays.

Uploaded by

sagarchouhan5252
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Php Introduction File1

PHP is a server-side scripting language created in 1994, primarily for web development, and it is open-source and free to use. PHP files can contain various types of code and are executed on the server to generate HTML for the browser. The document also covers installation instructions for XAMPP, basic PHP syntax, variables, data types, and arrays.

Uploaded by

sagarchouhan5252
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 201

PHP

INTRODUCTION
INTRODUCTION
• PHP is a server-side and general-purpose scripting language that is
especially suited for web development.
• it stands for Hypertext Preprocessor.
• PHP was created by Rasmus Lerdorf in 1994.
•PHP is a widely-used, open source scripting language
•PHP scripts are executed on the server
•PHP is free to download and use
What is a PHP File?

• 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 files have extension ".php"
What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
What Can PHP Do?

• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)


• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP supports a wide range of databases
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side
How PHP Works ?
How PHP Works ?
• First, the web browser sends an HTTP request to the web server, e.g.,
index.php.
• Second, the PHP preprocessor that locates on the web server processes
PHP code to generate the HTML document.
• Third, the web server sends the HTML document back to the web
browser.
Install PHP
• Installing PHP on your computer allows you to safely develop and test
a web application without affecting the live system.
• To work with PHP locally, you need to have the following software:
• PHP
• A web server that supports PHP.
• A database server.
It’s easier to find an all-in-one software package that includes PHP, a web server,
and a database server. One of the most popular PHP development environments
is XAMPP.
XAMPP is an easy install Apache distribution that contains PHP, MariaDB, and
Apache webserver.
To install XAMPP on windows, you can go to the XAMPP official website and
download the suitable version for your platform.
Install XAMPP on Windows
• Step 1. Start the installation
• Double-click the downloaded file to start setting up XAMPP:
Install XAMPP on Windows
• Step 2. Select components to install
• Select the components that you want to install. In this step, you can select Apache, MySQL, PHP,
and phpMyAdmin, deselect other components like the following, and click the Next button to go to
the next step.
Install XAMPP on Windows
• Step 3. Specifying the installation folder
• Select a folder to install XAMPP. It’s recommended to install XAMPP in the c:\xampp
folder. Click the Next button to go to the next step.
Install XAMPP on Windows
• Step 4. Selecting a language
• Select a language for XAMPP Control Panel. By default, it’s English. And you can
select your preferred language and click the Next button to go to the next step.
Install XAMPP on Windows
• Completing the XAMPP setup
• Once completed, the XAMPP setup wizard shows the following screen. You can click
the Finish button to launch the XAMPP Control Panel:
XAMPP Control Panel
Basic PHP Syntax

PHP script starts with “<?php” and ends with “?>”

Below, we have an example of a simple PHP file, with a PHP script that
uses a built-in PHP function "echo" to output the text "Hello World!" on a
web page:
<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>
Case sensitivity

PHP is partially case-sensitive. Knowing what are case sensitive and what is not
is very important to avoid syntax errors.
If you have a function such as count, you can use it as COUNT. It would work
properly.
The following are case-insensitive in PHP:
•PHP constructs such as if, if-else, if-elseif, switch, while, do-while, etc.
•Keywords such as true and false.
•User-defined function & class names.
On the other hand, variables are case-sensitive. e.g., $message and $MESSAGE
are different variables.
Case sensitivity

<!DOCTYPE html>
<html>
<body>

<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?> Output:
Hello World!
Hello World!
</body> Hello World!
</html>
Case sensitivity
<!DOCTYPE html>
<html>
<body>

<?php
$color = "red";
echo "My car is " . $color
. "<br>";
echo "My house is " .
$COLOR . "<br>"; Output:
echo "My boat is " . My car is red
My house is
$coLOR . "<br>"; My boat is
?>

</body>
</html>
Comments in PHP

A comment in PHP code is a line that is not executed as a part of the program.
Its only purpose is to be read by someone who is looking at the code.
Comments can be used to:
•Let others understand your code
•Remind yourself of what you did - Most programmers have experienced
coming back to their own work a year or two later and having to re-figure
out what they did. Comments can remind you of what you were thinking
when you wrote the code
•Leave out some parts of your code
Comments in PHP
<!DOCTYPE html>
<html>
<body>

<?php
// This is a single-line comment

# This is also a single-line comment

/* This is a
multi-line comment */
?>

</body>
</html>
PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the
variable.
<?php
$x = 5;
$y = "John";

echo $x;
echo "<br>";
echo $y;
?>
OUTPUT:
5
John
PHP Variables

Note: When you assign a text value to a variable, put quotes around the value.

When defining a variable, you need to follow these rules:


•The variable name must start with the dollar sign ($).
•The first character after the dollar sign ( $) must be a letter (a-z) or the
underscore ( _ ).
•The remaining characters can be underscores, letters, or numbers.
•PHP variables are case-sensitive. It means that $message and
$Message variables are entirely different.
PHP Variables

<!DOCTYPE html> <!DOCTYPE html>


<html> <html>
<body> <body>

<?php <?php
$txt = “Aryan College"; $x = 5;
echo "I love " . $txt . "!"; $y = 4;
?> echo $x + $y; //9
?>
</body>
</html> </body>
</html>
PHP is a Loosely Typed Language

• In the example above, notice that we did not have to tell PHP which data type
the variable is.
• PHP automatically associates a data type to the variable, depending on its
value.
• Since the data types are not set in a strict sense, you can do things like adding
a string to an integer without causing an error.
• In PHP 7, type declarations were added. This gives an option to specify the
data type expected when declaring a function, and by enabling the strict
requirement, it will throw a "Fatal Error" on a type mismatch.
PHP Variables

<body>

<?php
$x = 5; // $x is an integer
$y = "John"; // $y is a string

echo $x;
echo $y; //Output: 5John
?>

</body>
PHP Data Types

PHP supports the following data types:


•String
•Integer
•Float
•Boolean
•Array
•Object
•NULL
•Resource
Getting the Data Type

You can get the data type of ant object by using the var_dump() function.
<!DOCTYPE html>
<html>
<body>

<?php
$x = 5;
var_dump($x); // Output: int(5)
?>

</body>
</html>
PHP String

A string is a sequence of characters, like "Hello world!".


A string can be any text inside quotes. You can use single or double quotes:
<body>
<?php
$x = "Hello world!";
$y = 'Hello world!';

var_dump($x);
echo "<br>";
var_dump($y);
?>
</body>
Output:
string(12) "Hello world!"
string(12) "Hello world!"
PHP Integer

• An integer data type is a non-decimal number between -2147483648 and


2147483647 in 32 bit systems, and between -9223372036854775808 and
9223372036854775807 in 64 bit systems.
• A value greater (or lower) than this, will be stored as float, because it exceeds
the limit of an integer.
• Note: Another important thing to know is that even if 4 * 2.5 is 10, the result
is stored as float, because one of the operands is a float (2.5).
Here are some rules for integers:
•An integer must have at least one digit
•An integer must NOT have a decimal point
•An integer can be either positive or negative
•Integers can be specified in three formats: decimal (10-based), hexadecimal
(16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
PHP Integer

<?php
$x = 0x111;
$y = 0111;
$z=45;
var_dump($x);
echo "<br>";
var_dump($y);
echo "<br>";
var_dump($z);
?>
Output:
int(273)
int(73)
int(45)
PHP Integer
PHP has the following predefined constants for integers:
•PHP_INT_MAX - The largest integer supported
•PHP_INT_MIN - The smallest integer supported
•PHP_INT_SIZE - The size of an integer in bytes
<?php
echo PHP_INT_MAX ;
echo "</br>";
echo PHP_INT_MIN ;
echo "</br>";
echo PHP_INT_SIZE ;
?>
Output:
9223372036854775807
-9223372036854775808
8
PHP Integer
PHP has the following functions to check if the type of a variable is integer:
•is_int()
•is_integer() - alias of is_int()
•is_long() - alias of is_int()
<?php
$x = 5985;
var_dump(is_integer($x));
echo "<br>";
$x = 59.85;
var_dump(is_int($x));
?>
Output:
bool(true)
bool(false)
PHP Float

• A float is a number with a decimal point or a number in exponential form.

• 2.0, 256.4, 10.358, 7.64E+5, 5.56E-5 are all floats.

• The float data type can commonly store a value up to 1.7976931348623E+308

(platform dependent), and have a maximum precision of 14 digits.

•PHP_FLOAT_MAX - The largest representable floating point number

•PHP_FLOAT_MIN - The smallest representable positive floating point number


PHP Float
<!DOCTYPE html>
<html>
<body>
<?php
echo PHP_VERSION;
echo "</br>";
echo PHP_FLOAT_MAX;
echo "</br>";
echo PHP_FLOAT_MIN;
?>
</body>
</html>
Output:
8.1.1
1.7976931348623E+308
2.2250738585072E-308
PHP Float
PHP has the following functions to check if the type of a variable is float:
•is_float()
•is_double() - alias of is_float()
<!DOCTYPE html>
<html>
<body>

<?php
// Check if the type of a variable is float
$x = 10.365;
var_dump(is_float($x));
?>

</body>
</html>
Output:
bool(true)
PHP Float
PHP Infinity
A numeric value that is larger than PHP_FLOAT_MAX is considered infinite.
PHP has the following functions to check if a numeric value is finite or infinite:
•is_finite()
•is_infinite()

<?php
// Check if a numeric value is finite or infinite
$x = 1.7976931348624E+308 ;
var_dump($x);
?>
Output:
float(INF)
PHP NaN
• NaN stands for Not a Number.
• NaN is used for impossible mathematical operations.
• PHP has the following functions to check if a value is not a number:
•is_nan()

<?php
echo(acos(0.64) . "<br>");
echo(acos(-0.4) . "<br>");
echo(acos(0) . "<br>");
echo(acos(-1) . "<br>");
echo(acos(1) . "<br>");
echo(acos(-1.1) . "<br>");
echo(acos(1.1));
?>
Output:
0.87629806116834
1.9823131728624
1.5707963267949
3.1415926535898
0
NAN
NAN
PHP Numerical Strings
• The PHP is_numeric() function can be used to find whether a value is numeric.
• The function returns true if the variable is a number or a numeric string, false otherwise.
<?php
// Check if the variable is numeric
$x = 5985;
var_dump(is_numeric($x)); //bool(true)

echo "<br>";

$x = "5985";
var_dump(is_numeric($x)); //bool(true)

echo "<br>";

$x = "59.85" + 100;
var_dump(is_numeric($x)); //bool(true)

echo "<br>";

$x = "Hello";
var_dump(is_numeric($x)); //bool(false)
?>
PHP Boolean
• A Boolean represents two possible states: TRUE or FALSE.
• Booleans are often used in conditional testing.
<!DOCTYPE html>
<html>
<body>

<?php
$x = true;
var_dump($x); // bool(true)
?>

</body>
</html>
PHP Array

• An array is a special variable, which can hold more than one value at a time.
• In PHP, the array() function is used to create an array:
• 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
PHP Array

<?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 Indexed Arrays

• There are two ways to create indexed arrays:


• The index can be assigned automatically (index always starts at 0), like this:
• $cars = array("Volvo", "BMW", "Toyota");
• Or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
PHP Indexed Arrays
<!DOCTYPE html>
<html>
<body>

<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

</body>
</html>
Output:
I like Volvo, BMW and Toyota.
PHP Associative Arrays

• Associative arrays are arrays that use named keys that you assign to them.
• There are two ways to create an associative array:
• $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
• Or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
PHP Associative Arrays
<!DOCTYPE html>
<html>
<body>

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

</body>
</html>
Output:
Peter is 35 years old.
PHP Multidimensional Arrays
• Multidimensional array is an array containing one or more arrays.
• PHP supports multidimensional arrays that are two, three, four, five, or more levels
deep.
PHP - Two-dimensional Arrays:
A two-dimensional array is an array of arrays:
Example:
Name Stock Sold
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
PHP Multidimensional Arrays
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>

Output:
Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.
PHP NULL Value
• Null is a special data type which can have only one value: NULL.
• A variable of data type NULL is a variable that has no value assigned to it.
• Tip: If a variable is created without a value, it is automatically assigned a value of
NULL.
• Variables can also be emptied by setting the value to NULL:

<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
• Output:
• NULL
PHP Resource Type
• Resource is a special data type that refers to any external resource.
• A resource variable acts as a reference to external source of data such as stream, file,
database etc.
• PHP uses relevent functions to create these resources.
• For example, fopen() function opens a disk file and its reference is stored in a resource
variable.

<?php
$fp=fopen("test.txt","r");
var_dump($fp);
?>
Output:
resource(5) of type (stream)
PHP Resource Type

• PHP has get_resource_type() function that returns resource type of a variable.


<?php
$fp = fopen("test.txt", "w");
echo get_resource_type($fp) ;
?>
Output:
Stream

Other Examples:
ftp ftp_connect(), ftp_close()

mssql link mssql_connect()


mssql_close()
PHP Object

• Classes and objects are the two main aspects of object-oriented programming.
• A class is a template for objects, and an object is an instance of a class.
• When the individual objects are created, they inherit all the properties and behaviors
from the class, but each object will have different values for the properties.
• Let's assume we have a class named Car that 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.
PHP Object
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "<br> My car is a " . $this->color . " " . $this->model . "!";
}
}

$myCar = new Car("red", "Volvo");


var_dump($myCar);
$text = $myCar->message();
echo $text;
?>
Output:
object(Car)#1 (2) { ["color"]=> string(3) "red" ["model"]=> string(5) "Volvo" }
My car is a red Volvo!
PHP Casting

Sometimes you need to change a variable from one data type into another, and sometimes you want a
variable to have a specific data type. This can be done with casting.
Change Data Type
Casting in PHP is done with these statements:
•(string) - Converts to data type String
•(int) - Converts to data type Integer
•(float) - Converts to data type Float
•(bool) - Converts to data type Boolean
•(array) - Converts to data type Array
•(object) - Converts to data type Object
•(unset) - Converts to data type NULL
Cast to String
<?php
$a = 5; // Integer Output:
$b = 5.34; // Float string(1) "5"
$c = "hello"; // String string(4) "5.34"
$d = true; // Boolean string(5) "hello"
$e = NULL; // NULL string(1) "1"
string(0) ""
$a = (string) $a;
$b = (string) $b; Note that when casting a Boolean into string it
$c = (string) $c; gets the value "1", and when casting NULL into
$d = (string) $d; string it is converted into an empty string "".
$e = (string) $e;

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);
?>
Cast to INT
<?php
$a = 5; // Integer
$b = 5.34; // Float Output:
$c = "25 kilometers"; // String
$d = "kilometers 25"; // String
$e = "hello"; // String
$f = true; // Boolean int(5)
$g = NULL; // NULL int(5)
int(25)
$a = (int) $a;
$b = (int) $b;
int(0)
$c = (int) $c; int(0)
$d = (int) $d; int(1)
$e = (int) $e; int(0)
$f = (int) $f;
$g = (int) $g;
Note that when casting a string that starts with a
var_dump($a); number, the (int) function uses that number. If it
var_dump($b); does not start with a number, the (int) function
var_dump($c);
var_dump($d);
convert strings into the number 0.
var_dump($e);
var_dump($f);
var_dump($g);
?>
Cast to Float
<?php
$a = 5; // Integer
$b = 5.34; // Float Output:
$c = "25 kilometers"; // String
$d = "kilometers 25"; // String
$e = "hello"; // String
float(5)
$f = true; // Boolean float(5.34)
$g = NULL; // NULL float(25)
float(0)
$a = (float) $a;
$b = (float) $b;
float(0)
$c = (float) $c; float(1)
$d = (float) $d; float(0)
$e = (float) $e;
$f = (float) $f;
$g = (float) $g;
Note that when casting a string that starts with a
number, the (float) function uses that number. If it
var_dump($a); does not start with a number, the (float) function
var_dump($b); convert strings into the number 0.
var_dump($c);
var_dump($d);
var_dump($e);
var_dump($f);
var_dump($g);
?>
Cast to Boolean
<?php
$a = 5; // Integer
$b = 5.34; // Float
$c = 0; // Integer
Output:
$d = -1; // Integer
$e = 0.1; // Float bool(true)
$f = "hello"; // String
$g = ""; // String bool(true)
$h = true; // Boolean bool(false)
$i = NULL; // NULL
$a = (bool) $a;
bool(true)
$b = (bool) $b; bool(true)
$c = (bool) $c;
$d = (bool) $d;
bool(true)
$e = (bool) $e; bool(false)
$f = (bool) $f; bool(true)
$g = (bool) $g;
$h = (bool) $h; bool(false)
$i = (bool) $i;
var_dump($a);
var_dump($b); If a value is 0, NULL, false, or empty, the
var_dump($c); (bool) converts it into false, otherwise true.
var_dump($d);
var_dump($e);
Even -1 converts to true.
var_dump($f);
var_dump($g);
var_dump($h);
var_dump($i);
?>
Cast to Array
<?php
$a = 5; // Integer
Output:
$b = 5.34; // Float
$c = "hello"; // String
array(1) { [0]=> int(5) }
$d = true; // Boolean
array(1) { [0]=> float(5.34) }
$e = NULL; // NULL
array(1) { [0]=> string(5) "hello" }
array(1) { [0]=> bool(true) }
$a = (array) $a;
array(0) { }
$b = (array) $b;
$c = (array) $c;
When converting into arrays, most data types
$d = (array) $d;
converts into an indexed array with one element.
$e = (array) $e;
NULL values converts to an empty array object.
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);
?>
Cast Objects into Array
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}

$myCar = new Car("red", "Volvo");

$myCar = (array) $myCar;


var_dump($myCar);

?>
Cast Objects into Array
Output:

array(2) { ["color"]=> string(3) "red" ["model"]=> string(5) "Volvo" }

Note:
Objects converts into associative arrays where the property names becomes the keys and the
property values becomes the values.
Cast in Object
<?php
$a = 5; // Integer Output:
$b = 5.34; // Float
$c = "hello"; // String object(stdClass)#1 (1) { ["scalar"]=> int(5) }
$d = true; // Boolean object(stdClass)#2 (1) { ["scalar"]=> float(5.34) }
$e = NULL; // NULL object(stdClass)#3 (1) { ["scalar"]=> string(5) "hello" }
object(stdClass)#4 (1) { ["scalar"]=> bool(true) }
$a = (object) $a; object(stdClass)#5 (0) { }
$b = (object) $b;
$c = (object) $c; Note:
$d = (object) $d; In each case, the resulting object has a property named
$e = (object) $e; scalar that holds the original value of the variable. The
stdClass is a generic PHP class used for creating
var_dump($a); anonymous objects.
var_dump($b); NULL values converts to an empty object.
var_dump($c);
var_dump($d);
var_dump($e);
?>
PHP Constant

• Constants are like variables, except that once they are defined they cannot be
changed or undefined.
• Constants are automatically global across the entire script.
• To create a constant, use the define() function.
• define(name, value, case-insensitive);

•name: Specifies the name of the constant


•value: Specifies the value of the constant
•case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false.
•Note: Defining case-insensitive constants was deprecated in PHP 7.3. PHP 8.0
accepts only false, the value true will produce a warning.
PHP Constant

•<!DOCTYPE html>
•<html>
•<body>

•<?php
•// case-sensitive constant name
•define("GREETING", "Welcome to Aryan!");
•echo GREETING;
•?>

•</body>
•</html>

•Output:
•Welcome to Aryan!
PHP Constant

•<!DOCTYPE html>
•<html>
•<body>

•<?php
•// case-insensitive constant name
•define("GREETING", "Welcome to Aryan!", true);
•echo greeting;
•?>

•</body>
•</html>
•Output:
•Welcome to Aryan!
PHP Constant

You can also create a constant by using the const keyword.


<!DOCTYPE html>
<html>
<body>

<?php
const MYCAR = "Volvo";

echo MYCAR;
?>

</body>
</html>
• Output:
• Volvo
PHP Constant

const vs. define()


•const are always case-sensitive
•define() has has a case-insensitive option.
•const cannot be created inside another block scope, like inside a function or inside
an if statement.
•define can be created inside another block scope.
PHP Constant Arrays

<!DOCTYPE html>
<html>
<body>

<?php
define("cars", [
"Alfa",
"BMW",
"Toyota"
]);
echo cars[0];
?>

</body>
</html>

Outptut:

Alfa
PHP Constant Arrays

Constants are automatically global and can be used across the entire script.
<!DOCTYPE html>
<html>
<body>

<?php
define("GREETING", "Welcome to Aryan!");

function myTest() {
echo GREETING;
}

myTest();
?>

</body>
</html>
Output:
Welcome to Aryan!
PHP Magic Constants

PHP Predefined Constants


• PHP has nine predefined constants that change value depending on where
they are used, and therefore they are called "magic constants".
• These magic constants are written with a double underscore at the start and
the end.
PHP Magic Constants
<!DOCTYPE html>
<html>
<body>
<?php
class Fruits {
public function myValue(){
return __CLASS__;
}
}
$kiwi = new Fruits();
echo $kiwi->myValue();
?>
</body>
</html>
Output:
Fruits
PHP Magic Constants

__DIR__ The directory of the file.


The file name including the
__FILE__
full path.
If inside a function, the
__FUNCTION__
function name is returned.
__LINE__ The current line number.
If used inside a function
that belongs to a class, both
__METHOD__
class and function name is
returned.
PHP Magic Constants
<!DOCTYPE html>
<html>
<body>

<?php
function myValue(){
return __FUNCTION__;
}
echo myValue();
?>

</body>
</html>

Output:
myValue
PHP Magic Constants
<!DOCTYPE html>
<html>
<body>

<?php
echo __LINE__;
?>

</body>
</html>
Output:
6
PHP Magic Constants
<!DOCTYPE html>
<html>
<body>

<?php
class Fruits {
public function myValue(){
return __METHOD__;
}
}

$kiwi = new Fruits();


echo $kiwi->myValue();
?>

</body>
</html>
Output:
Fruits::myValue
PHP Global Variables

Some predefined variables in PHP are "superglobals", which means that they are
always accessible, regardless of scope - and you can access them from any
function, class or file without having to do anything special.
The PHP superglobal variables are:
•$GLOBALS
•$_SERVER
•$_REQUEST
•$_POST
•$_GET
•$_FILES
•$_ENV
•$_COOKIE
•$_SESSION
PHP Global Variables

<!DOCTYPE html>
<html>
<body>

<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

addition();
echo $z;
?>
</body>
</html>
Output:
100
PHP Global Variables
PHP $_SERVER
• $_SERVER is a PHP super global variable which holds information about headers, paths, and
script locations.
• The example below shows how to use some of the elements in $_SERVER:
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
PHP Global Variables
<!DOCTYPE html>
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php Output:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
//var_dump($_POST);
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
PHP Global Variables
index.php:
<html>
<body>

<a href="test_get.php?subject=PHP&web=aryan.com">Test $GET</a>

</body>
</html>

test_get.php:
<html>
<body>

<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>

</body>
</html>
PHP Operators

Operators are used to perform operations on variables and values.


PHP divides the operators in the following groups:

•Arithmetic operators
•Assignment operators
•Comparison operators
•Increment/Decrement operators
•Logical operators
•String operators
•Array operators
•Conditional assignment operators
PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as
addition, subtraction, multiplication etc.
PHP Assignment Operators

• The PHP arithmetic operators are used with numeric values to perform common arithmetical
operations, such as addition, subtraction, multiplication etc.
• The PHP assignment operators are used with numeric values to write a value to a variable.
• The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of
the assignment expression on the right.
PHP Comparison Operators

• The PHP comparison operators are used to compare two values (number or string):
PHP Comparison Operators

• The PHP comparison operators are used to compare two values (number or string):
PHP Comparison Operators

<?php
$x = 100;
$y = "100";
var_dump($x === $y); // returns false because types are not equal
?>
Output:
bool(false)
PHP Comparison Operators

<?php
$x = 100;
$y = "100";
var_dump($x !== $y); // returns true because types are not equal
?>
Output:
bool(true)
PHP Comparison Operators

<?php Output:
$x = 5; -1
$y = 10; 0
1
echo ($x <=> $y); // returns -1 because $x is less than $y
echo "<br>";

$x = 10;
$y = 10;

echo ($x <=> $y); // returns 0 because values are equal


echo "<br>";

$x = 15;
$y = 10;

echo ($x <=> $y); // returns +1 because $x is greater than


$y
?>
<!DOCTYPE html>
<html>
<body>

<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
?>

</body>
</html>

Output:
Hello world!
<!DOCTYPE html>
<html>
<body>

<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");

print_r($x + $y); // union of $x and $y


?>

</body>
</html>

Output:
Array ( [a] => red [b] => green [c] => blue [d] => yellow )
PHP Comparison Operators

<!DOCTYPE html>
<!DOCTYPE html>
<html>
<html>
<body>
<body>
<?php
<?php
$x = array("a" => "red", "b" => "green");
$x = array("a" => "red", "b" => "green");
$y = array("a" => "red", "b" => "green");
$y = array("b" => "green", "a" => "red" );
var_dump($x === $y);
var_dump($x === $y);
?>
?>
</body>
</body>
</html>
</html>

Output: Output:
bool(true) bool(false)
PHP Comparison Operators

<!DOCTYPE html>
<!DOCTYPE html>
<html>
<html>
<body>
<body>
<?php
<?php
$x;
$x;
$y='hello';
$y='hello';
var_dump($red);
var_dump($red);
$output = $x ?? $y ;
$output = $y ?? $z ;
echo $output;
echo $output;
?>
?>
</body>
</body>
</html>
</html>

Output: Output:
NULL hello NULL hello
PHP Form Data: index.php
<body>
<h2>Login Form</h2>
<form action="process_login.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"
required><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"
required><br>

<input type="submit" value="Login">


</form>
</body>
PHP Form Data: process_login.php
<body>
<h2>Login Details</h2>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve login details from the form
$username = $_POST["username"];
$password = $_POST["password"];

// Display login details


echo "<p>Username: $username</p>";
echo "<p>Password: $password</p>";
}
?>

</body>
PHP Form Data(on same page): index.php
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
//var_dump($_POST);
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
<!DOCTYPE html>
<html>
<body>
<?php
$a = 5;

if ($a == 2 || $a == 3 || $a == 4 || $a == 5 || $a == 6 || $a == 7) {
echo "$a is a number between 2 and 7";
}
?>
</body>
</html>
Output:
5 is a number between 2 and 7
<?php
$t = date("h");
echo "<p>The hour (of the server) is " . $t;
echo ", and will give the following message:</p>";

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Output:
• The hour (of the server) is 11, and will give the following message:
• Have a good day!
<!DOCTYPE html>
<html>
<body>

<?php
$a = 5;

if ($a < 10) $b = "Hello";

echo $b
?>

</body>
</html>
Output:
• Hello
<?php
$a = 13;

if ($a > 10) {


echo "Above 10";
if ($a > 20) {
echo " and also above 20";
} else {
echo " but not above 20";
}
}
?>
Output:
• Above 10 but not above 20
<?php
$favcolor = "red";

switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
Output:
• Your favorite color is red!
<?php <?php <?php
$i = 1; $i = 0; $i = 1;

while ($i < 6) { while ($i < 6) { while ($i < 6):
if ($i == 3) break; $i++; echo $i;
echo $i; if ($i == 3) continue; $i++;
$i++; echo $i; endwhile;
} } ?>
?> ?> Output:
Output: Output: 12345
12 12456
<body> <body>
<?php <?php
for ($i = 1; $i <= 5; $i++) { $counter = 1;
echo "Iteration $i <br>"; do {
} echo "Iteration $counter <br>";
?> $counter++;
</body> } while ($counter <= 5);
Output: ?>
</body>
Iteration 1
Output:
Iteration 2
Iteration 1
Iteration 3
Iteration 2
Iteration 4
Iteration 3
Iteration 5
Iteration 4
Iteration 5
<body>
<?php
$colors = array("Red", "Green", "Blue");
foreach ($colors as $i) {
echo "Color is: $i <br>";
}
?>
</body>
Output:
Color is: Red
Color is: Green
Color is: Blue
<?php
$members = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach ($members as $x => $y) {


echo "$x : $y <br>";
}
?>
Output:
Peter : 35
Ben : 37
Joe : 43
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
}

$myCar = new Car("red", "Volvo");

foreach ($myCar as $x => $y) {


echo "$x: $y<br>";
}
?>
Output:
color: red
model: Volvo
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $x) {


if ($x == "blue")
{
$x = "pink";
}
}

var_dump($colors);
?>

Output:
array(4) { [0]=> string(3) "red" [1]=> string(5) "green" [2]=> string(4) "blue" [3]=> string(6) "yellow" }
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as &$x) {


if ($x == "blue")
{
$x = "pink";
}
}

var_dump($colors);
?>

Output:
array(4) { [0]=> string(3) "red" [1]=> string(5) "green" [2]=> string(4) "pink" [3]=> &string(6) "yellow" }
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $x) :


echo "$x <br>";
endforeach;
?>

Output:
red
green
blue
yellow
PHP Functions

•A function is a block of statements that can be used repeatedly in a program.


•A function will not execute automatically when a page loads.
•A function will be executed by a call to the function.
<?php
function myMessage() {
echo "Hello world!";
}

myMessage();
?>
Output:
Hello world!
PHP Functions

<?php
function paraName($pname) {
echo "The Parameter is $pname.<br>";
}

paraName("One");
paraName("Two");
paraName("Three");
paraName("Four");
paraName("Five");
?>
Output:
The Parameter is One.
The Parameter is Two.
The Parameter is Three.
The Parameter is Four.
The Parameter is Five.
PHP Functions

The following example shows how to use a default parameter.


<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
Output:
The height is : 350
The height is : 50
The height is : 135
The height is : 80
PHP Functions

When a function argument is passed by reference, changes to the argument also change the
variable that was passed in.
To turn a function argument into a reference, the & operator is used:
<?php
function add_five(&$value) {
$value += 5;
}

$num = 2;
add_five($num);
echo $num;
?>

Output:
7
PHP Array
PHP Array

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.
PHP Array
<?php
function myFunction() {
echo "This text comes from a function";
}

$myArr = array("Volvo", 15, ["apples", "bananas"], myFunction);

var_dump($myArr[0]);
echo '<br>';
var_dump($myArr[1]);
echo '<br>';
var_dump($myArr[2]);
echo '<br>';
var_dump($myArr[2][0]);
echo '<br>';
var_dump($myArr[3]);
echo '<br>';
$myArr[3](); // calling the function from the array item:
//print_r($myArr);
?>
PHP Array
Output:
string(5) "Volvo"
int(15)
array(2) { [0]=> string(6) "apples" [1]=> string(7) "bananas" }
string(6) "apples"
string(10) "myFunction"
This text comes from a function
PHP Array Functions
The array functions are part of the PHP core. There is no installation needed to use
these functions.

• count()
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Output: 3
PHP Array Functions
The array_keys() function returns an array containing the keys.
array_keys(array, value, strict)

<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
print_r(array_keys($a));
?>

Output:
Array ( [0] => Volvo [1] => BMW [2] => Toyota )
PHP Array Functions
The array_keys() function returns an array containing the keys.
array_keys(array, value, strict)

<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
print_r(array_keys($a,"Highlander"));
?>

Output:
Array ( [0] => Toyota )
PHP Array Functions
The array_keys() function returns an array containing the keys.
array_keys(array, value, strict)

<?php
$a=array(10,20,30,"10");
print_r(array_keys($a,"10",false));
?>
Output:
Array ( [0] => 0 [1] => 3 )
PHP Array Functions
The array_merge() function merges one or more arrays into one array.
You can assign one array to the function, or as many as you like.
If two or more array elements have the same key, the last one overrides the others.

<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
Output:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
PHP Array Functions
The array_merge() function merges one or more arrays into one array.
You can assign one array to the function, or as many as you like.
If two or more array elements have the same key, the last one overrides the others.

<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>

Output:
Array ( [a] => red [b] => yellow [c] => blue )
PHP Array Functions
The array_reverse() function returns an array in the reverse order..

<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>
Output:
Array ( [c] => Toyota [b] => BMW [a] => Volvo )
PHP Strings
In PHP, a string is a sequence of characters, which can include letters, numbers, symbols, and
whitespace. Strings are used to represent and manipulate textual data. PHP provides various
functions and features to work with strings efficiently.

String Declaration: You can declare strings using single quotes (') or double quotes ("). For
example:

$singleQuotedString = 'This is a single-quoted string.’;


$doubleQuotedString = "This is a double-quoted string.";

Double-quoted strings allow variable interpolation, meaning you can directly include variables in the
string:
$name = 'John’;
$greeting = "Hello, $name!"; // Results in 'Hello, John!’
PHP Strings
PHP supports escape characters within double-quoted strings, such as \n for a new line or \t for a tab.

<?php
$x = "Joh\nn";
echo $x; # Joh n
?>

<?php
$x = 'Joh\nn’;
echo $x; # Joh\nn
?>
PHP Strings
Concatenation: You can concatenate strings using the . operator:
$str1 = 'Hello’;
$str2 = 'World’;
$result = $str1 . ' ' . $str2; // Results in 'Hello World'
PHP Strings
Heredoc:
Heredoc is a syntax in PHP that allows you to declare multiline strings.
It starts with <<< followed by a delimiter (often in uppercase, but it can be any
valid identifier), and ends with the same delimiter on a line by itself. Heredoc
strings can span multiple lines and can include variable interpolation.

$name = 'John’;
$age = 30;
$heredocString=<<<EOD My name
is $name,and
I am $age years
old.EOD;

echo $heredocString;
In this example, the <<<EOD syntax indicates the start of a heredoc string, and it ends with EOD;. The variables
$name and $age are interpolated within the string. When you echo the heredoc string, it will output:
PHP Strings
Nowdoc:
Nowdoc is similar to heredoc, but it treats everything literally, including
variable names. It starts with <<<' followed by a delimiter and ends with
the same delimiter on a line by itself. Nowdoc strings are useful when you
want to ensure that variables are not interpolated and are treated as plain
text.
Here's an example:
$name = 'John’;
$age = 30;
$nowdocString = <<<'EOD'
My name is $name,
and I am $age years
old. EOD;
echo $nowdocString;
PHP Strings Functions
<?php
echo ucfirst("hello world!"); // Hello world!
?>

<?php
echo lcfirst("Hello world!"); //hello world!
?>

<?php
echo ucwords("hello world"); // Hello World
?>

<?php
echo strtoupper("Hello WORLD!"); // HELLO WORLD!
?>
PHP Strings Functions
<?php
echo strtolower("Hello WORLD."); // hello world.
?>

<?php
echo strlen("Hello"); // 5
?>

<?php
echo strlen(" Hello world! "); 14 (whitespaces are included)
?>

<?php
echo strlen(trim(" Hello world! “)); 12
?>
PHP Strings Functions
<?php
echo strlen(ltrim(" Hello world!")); // 12
?>

<?php
echo strlen(rtrim("Hello world! ")); //12
?>
PHP Strings Functions
<?php
// PHP program to demonstrate the use of trim()
// function when second parameter is present

// removes the predefined characters from


// front and back
$str = "Hello World!";
echo trim($str, "Hell!"); // o World
?>
PHP Strings Functions
<?php
// PHP program to demonstrate the use of trim()
// function when second parameter is present

// removes the predefined characters from


// front and back
$str = "Hello World!";
echo trim($str, "Hell!"); // o World
?>
PHP Strings Functions
<?php
$str = "Hello World!Hell";
echo rtrim($str, "Hell"); // Hello World!
?>

<?php
$str = "Hello World!Hell";
echo ltrim($str, "Hell"); // o World!Hell
?>

<?php
echo strrev("Hello World!"); // !dlroW olleH
?>
PHP Regular Expressions
Regular expressions (regex) in PHP are a powerful tool for pattern matching
and manipulation of strings. Regular expressions commonly known as a regex
(regexes) are a sequence of characters describing a special search pattern in
the form of text string. They are basically used in programming world
algorithms for matching some loosely defined patterns to achieve some
relevant tasks. Some times regexes are understood as a mini programming
language with a pattern notation which allows the users to parse text strings.
PHP Regular Expressions
•Basic Patterns:
•\d: Matches any digit.
•\w: Matches any word character (alphanumeric + underscore).
•\s: Matches any whitespace character.
•Quantifiers:
•*: Matches 0 or more occurrences.
•+: Matches 1 or more occurrences.
•?: Matches 0 or 1 occurrence.
•{n}: Matches exactly n occurrences.
•{n,}: Matches n or more occurrences.
•{n,m}: Matches between n and m occurrences.
PHP Regular Expressions

Character Classes:
•[]: Matches any single character within the brackets.
•[^]: Matches any single character not within the brackets.

Anchors:
•^: Matches the start of a string.
•$: Matches the end of a string.
PHP Regular Expressions
aryan The string “aryan”
^aryan The string which starts with “aryan”
aryan$ The string which have “aryan” at the end.
^aryan$ The string where “aryan” is alone on a string.
[abc] a, b, or c
[a-z] Any lowercase letter
[^A-Z] Any letter which is NOT a uppercase letter
(gif|png) Either “gif” or “png”
[a-z]+ One or more lowercase letters
^[a-zA-Z0-9]{1, }$ Any word with at least one number or one letter
([ax])([by]) ab, ay, xb, xy
[^A-Za-z0-9] Any symbol other than a letter or other than number
([A-Z]{3}|[0-9]{5}) Matches three letters or five numbers
Regular Expression Functions
PHP provides a variety of functions that allow you to use regular
expressions. The preg_match(), preg_match_all() and preg_replace()
functions are some of the most commonly used.
Function Description

preg_match() Returns 1 if the pattern was found in the string and 0 if not

preg_match_all() Returns the number of times the pattern was found in the string, which may also be 0

preg_replace() Returns a new string where matched patterns have been replaced with another string
PHP Strings Functions
<?php
$str = "Apples and bananas.";
$pattern = "/bana/";
$result = preg_match($pattern, $str,$out);
echo $result;
echo '<br>';
echo print_r($out);
?>

Output:

1
Array ( [0] => bana )
PHP Strings Functions
<?php
$str = "Apples and bananas.";
$pattern = "/ba(na){2}/";
echo preg_match($pattern, $str,$out);
echo '<br>';
echo print_r($out);
?>
Output:

1
Array ( [0] => banana [1] => na )

*Note: Capturing groups are created by placing parentheses () around the desired sub-pattern.
*echo print_r($out) => will print the details of the matches in the array, which includes the full match at
index 0 and the capturing group at index 1. In this case, the full match is "banana," and the capturing
group is "na."
PHP Strings Functions
<?php
<?php
$str = "apple banana cherry";
$pattern = "/(apple) (banana) (cherry)/";
preg_match($pattern, $str, $matches);

print_r($matches);
?>
?>
Output:
Array
(
[0] => apple banana cherry
[1] => apple
[2] => banana
[3] => cherry
)
PHP Strings Functions
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
$result = preg_match_all($pattern, $str, $out);
echo $result; // Outputs the total number of matches found
echo '<br>';
print_r($out); // Outputs details of all matches
?>
Output:
4
Array ( [0] => Array ( [0] => ain [1] => AIN [2] => ain [3] => ain ) )
PHP Strings Functions
<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "Aryan", $str);

?>

Output:
Visit Aryan!
PHP Strings Functions
<?php
$email = "[email protected]";
$pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
$result = preg_match($pattern, $email);
echo $result;
?>

Output:
1
PHP Strings Functions
<?php
$email = "[email protected]";
$pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
$result = preg_match($pattern, $email);
echo $result;
?>

Output:
Array([0] => 2022-01-01)
PHP Strings Functions
<?php
$phone = "+1 (555) 123-4567";
$pattern = "/^\+\d{1,3}\s?\(\d{3}\)\s?\d{3}-\d{4}$/";
$result = preg_match($pattern, $phone);
echo $result;
?>

Output:
1
PHP Strings Functions
<?php
$string = "The price is $25.99";
$pattern = "/\d+\.\d{2}/";
preg_match($pattern, $string, $price);
echo $price[0];
?>

Output:
25.99
PHP Database Connectivity
Database Connection Parameters:

1.Hostname:
•Definition: The server where your MySQL database is hosted.
•Example: $hostname = "localhost";
•Note: For local development, the hostname may be "localhost" or "127.0.0.1".
2.Username:
•Definition: The MySQL user with privileges to access the specified database.
•Example: $username = "root";
•Note: The username is case-sensitive, and you should avoid using the root user in
production for security reasons.
PHP Database Connectivity
Database Connection Parameters:

3. Password:
•Definition: The password associated with the MySQL user.
•Example: $password = "your_password";

4. Database Name:
•Definition: The name of the MySQL database you want to connect to.
•Example: $database = "your_database";
•Note: Make sure the specified database exists on the MySQL server.
PHP Database Connectivity
mysqli

mysqli stands for MySQL Improved. It is an extension for


PHP that provides an improved and object-oriented
interface to interact with MySQL databases.
mysqli is designed to replace the older mysql extension,
providing enhanced features, better security, and support
for new MySQL functionalities.
PHP Database Connectivity
<?php
$hostname = "localhost";
$username = "root";
$password = "your_password";
$database = "your_database";
// Creating a connection
$conn = new mysqli($hostname, $username, $password, $database);
// Checking the connection
if ($conn->connect_error) {
// If there's an error, print the error message and terminate the script
die("Connection failed: " . $conn->connect_error);
} else {
// If the connection is successful, print a success message
echo "Connected successfully";
}
// Performing database operations...
// Closing the connection
$conn->close();
?>
PHP Database Connectivity
In the context of the mysqli extension in PHP, the $conn->connect_error is a
property of the mysqli object ($conn in this case) that holds the error message
from the most recent connection attempt. It is used to check whether the
connection to the MySQL database was successful and, if not, to retrieve
information about the error.
Here's how it works:
1.When you attempt to establish a connection using $conn = new
mysqli($hostname, $username, $password, $database);, the mysqli object
($conn) is created.
2.After attempting to connect, you can check if the connection was successful
by evaluating the $conn->connect_error property.
3.If the connection is successful, $conn->connect_error will be an empty
string or null. If there's an error, it will contain a string describing the error.
PHP Database Connectivity

In PHP, the die function is used to print a message and terminate the execution of
the script. It is often used for handling errors or exceptional situations where
continuing the script execution is not possible or meaningful.
The die function takes a single argument, which is the message to be displayed
before terminating the script. The message can be a string or any other data type that
can be converted to a string.
Create DB
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>
PHP Database Connectivity

In the mysqli extension of PHP, the query method is used to execute SQL queries
against a MySQL database. This method is part of the mysqli class and allows you to
perform various operations like SELECT, INSERT, UPDATE, DELETE, or even
database structure modifications.
The query method returns different types of values based on the type of query
executed:
•For SELECT, SHOW, DESCRIBE queries:
•Returns a mysqli_result object for successful SELECT queries.
•Returns FALSE on failure.
•For other queries (INSERT, UPDATE, DELETE, etc.):
•Returns TRUE on success.
•Returns FALSE on failure.
•For successful queries that don't return data (e.g., CREATE TABLE, INSERT without
SELECT):
•Returns TRUE.
<?php
$hostname = "localhost";
$username = "root";
$password = "your_password";
$database = "your_database";
// Creating a connection to the MySQL server
$conn = new mysqli($hostname, $username, $password, $database);
// Checking the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to create a table
$sql = "CREATE TABLE example_table (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT
)";
// Executing the SQL query to create the table
if ($conn->query($sql) === TRUE) {
echo "Table 'example_table' created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Closing the connection
$conn->close();
?>
<?php

// SQL query to insert a new record into the 'MyGuests' table


$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

// Execute the query and check if it was successful


if ($conn->query($sql) === TRUE) {
// If the record insertion was successful, print a success message
echo "New record created successfully";
} else {
// If there's an error in the SQL query, print an error message
echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close the MySQL connection


$conn->close();
?>
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"].
"<br>";
}
} else {
echo "0 results";
}
$conn->close();
• The function num_rows() checks if there are more than zero rows
returned.
• If there are more than zero rows returned, the function fetch_assoc()
puts all the results into an associative array that we can loop through.
• The while() loop loops through the result set and outputs the data from
the id, firstname and lastname columns.
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"].
"<br>";
}
} else {
echo "0 results";
}
$conn->close();
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
<?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit();


var_dump($apple instanceof Fruit); // bool(true)
?>
<?php
$a=5;
var_dump(print($a)); // 5int(1)
?>
Introspection in PHP offers the useful ability to examine classes, interfaces, properties,
and methods. PHP offers a large number functions that you can use to accomplish the
task. Important functions:
• class_exists() – checks whether a class has been defined
• get_class() – returns the class name of an object
• get_parent_class() – returns the class name of an object’s parent class
• is_subclass_of() – checks whether an object has a given parent class

You can determine whether or not the given class has been defined using
the class_exists()method, which takes a string argument representing the name of the
desired class to check.
The get_class() and get_parent_class() methods return the class name of an object or its
parent’s class name respectively. Both takes as arguments an object instance.
The is_subclass_of() methods takes an object instance as its first argument and a string,
representing the parent class name, and returns whether the object belongs to a class
which is a subclass of the class given as argument.
• get_declared_classes() – returns a list of all declared classes
• get_class_methods() – returns the names of the class’ methods
• get_class_vars() – returns the default properties of a class
• interface_exists() – checks whether the interface is defined
• method_exists() – checks whether an object defines a method
The interface_exists() method is very similar to class_exists(). It determines
whether or not the given interface has been defined and takes a string argument for
the interface name.
The get_declared_classes() method returns an array with the names of all of the defined
classes and takes no arguments.
The get_class_method() takes either an object instance or a string as argument
representing the desired class and returns an array of method names defined by the
class.
PHP - What are Interfaces?
Interfaces allow you to specify what methods a class should implement.

<?php
interface InterfaceName {
public function someMethod1();
public function someMethod2($name, $color);
public function someMethod3() : string;
}
?>
<?php
interface Animal {
public function makeSound();
}

class Cat implements Animal {


public function makeSound() {
echo "Meow";
}
}

$animal = new Cat();


$animal->makeSound();
?>
PHP OOP - Abstract Classes:
Abstract classes and methods are when the parent class has a named method, but need its child class(es)
to fill out the tasks.
An abstract class is a class that contains at least one abstract method. An abstract method is a method that
is declared, but not implemented in the code.
An abstract class or method is defined with the abstract keyword:

<?php
abstract class ParentClass {
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3() : string;
}
?>
When inheriting from an abstract class, the child class method must be defined with the
same name, and the same or a less restricted access modifier. So, if the abstract method
is defined as protected, the child class method must be defined as either protected or
public, but not private. Also, the type and number of required arguments must be the
same.

PHP - Interfaces vs. Abstract Classes


Interface are similar to abstract classes. The difference between interfaces and abstract
classes are:
•Interfaces cannot have properties, while abstract classes can
•All interface methods must be public, while abstract class methods is public or
protected
•All methods in an interface are abstract, so they cannot be implemented in code and
the abstract keyword is not necessary
•Classes can implement an interface while inheriting from another class at the same
time
PHP - Static Methods
Static methods can be called directly - without creating an instance of the class first.
Static methods are declared with the static keyword:

<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}

// Call static method


greeting::welcome();
?>
PHP - Static Properties
Static properties can be called directly - without creating an instance of a class.
Static properties are declared with the static keyword:

<?php
class pi {
public static $value = 3.14159;
}

// Get static property


echo pi::$value;
?>
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);

$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
Output:
BMW
Toyota
Volvo
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);

$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);

$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
?>
Output:
22
11
6
4
2
<?php
$age = array("Peter"=>"44", "Ben"=>"37", "Joe"=>"43");
asort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output:
Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=44
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output:
Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output:
Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);

foreach($age as $x => $x_value) {


echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Output:
Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
Function with variable number of arguments:
• By using the ... operator in front of the function parameter, the function
accepts an unknown number of arguments. This is also called a variadic
function.
• The variadic function argument becomes an array.
<?php
function sumMyNumbers(...$x) {
$n = 0;
$len = count($x);
for($i = 0; $i < $len; $i++) {
$n += $x[$i];
}
return $n;
}

$a = sumMyNumbers(5, 2, 6, 2, 7, 7);
echo $a;
?>
Output:
29
PHP isset() Function
Check whether a variable is empty. Also check whether the variable is
set/declared:
<?php
$a = 0;
// True because $a is set
if (isset($a)) {
echo "Variable 'a' is set.<br>";
}

$b = null;
// False because $b is NULL
if (isset($b)) {
echo "Variable 'b' is set.";
}
?>
Output:
Variable 'a' is set.
Internet Current State: The internet has evolved into a vast network
connecting billions of devices globally. It facilitates communication,
information sharing, and various online services. Technologies like 5G are
enhancing speed and connectivity.
Hardware and Software Requirements: Hardware: Basic requirements
include a computer or smart device, network interface card, modem/router,
and cables. Software: An operating system (e.g., Windows, macOS,
Linux), web browsers (e.g., Chrome, Firefox), and security software.
ISP (Internet Service Provider): ISP provides internet access. Types
include broadband, DSL(Digital Subscriber Line), fiber-optic, and satellite.
ISPs deliver connectivity, assign IP addresses, and offer various plans
based on speed and data.
Internet Account: Users usually create accounts with ISPs to access the
internet. This involves subscribing to a service plan, obtaining login
credentials, and configuring network settings.
Web Homepage: A web homepage is the initial page displayed when a
browser is launched. Users often customize it with frequently visited sites
or a search engine.
URL (Uniform Resource Locator): URL is the web address specifying a
resource's location. It consists of a protocol (http/https), domain name,
and path, enabling browsers to locate and retrieve web pages.
Browser: A web browser is a software application for accessing
information on the internet. Popular browsers include Chrome, Firefox,
Safari, and Edge.
Security on the Web: Web security involves measures like HTTPS for
secure data transfer, firewalls, antivirus software, and regular updates to
protect against malware and cyber threats.
Searching Tools: Searching tools encompass various methods to find
information online, including search engines, directories, and specialized
databases.
Search Engines: Search engines like Google, Bing, and Yahoo index and
retrieve web pages based on user queries. They use algorithms to rank
and display relevant results.
File Transfer Protocol (FTP):
FTP is a client-server protocol that allows users to transfer files over a TCP-based network, such as the internet. It is
widely used for uploading and downloading files to and from servers. Here's an overview of how FTP works:
1.Client-Server Architecture:
1. Client: The user or software that initiates the file transfer.
2. Server: The remote system that hosts the files and responds to client requests.
2.Communication Channels:
1. FTP uses two channels for communication: the command channel (control channel) and the data channel.
2. The command channel is used for sending commands from the client to the server (e.g., login, list
directory, retrieve file).
3. The data channel is used for the actual transfer of files.
3.Modes of Operation:
1. FTP supports two modes of operation: active mode and passive mode.
2. Active mode has the client open a random port for data transfer, and the server connects to it.
3. Passive mode has the server open a random port, and the client connects to it. Passive mode is often used
when the client is behind a firewall.
4.Authentication:
1. Users need to authenticate themselves using a username and password to access the FTP server.
2. Anonymous FTP allows users to log in with a generic username (e.g., "anonymous") and use their email
address as the password.
File Transfer Protocol (FTP):
FTP is a client-server protocol that allows users to transfer files over a TCP-based network, such as the internet. It is
widely used for uploading and downloading files to and from servers. Here's an overview of how FTP works:
1.Client-Server Architecture:
1. Client: The user or software that initiates the file transfer.
2. Server: The remote system that hosts the files and responds to client requests.
2.Communication Channels:
1. FTP uses two channels for communication: the command channel (control channel) and the data channel.
2. The command channel is used for sending commands from the client to the server (e.g., login, list
directory, retrieve file).
3. The data channel is used for the actual transfer of files.
3.Modes of Operation:
1. FTP supports two modes of operation: active mode and passive mode.
2. Active mode has the client open a random port for data transfer, and the server connects to it.
3. Passive mode has the server open a random port, and the client connects to it. Passive mode is often used
when the client is behind a firewall.
4.Authentication:
1. Users need to authenticate themselves using a username and password to access the FTP server.
2. Anonymous FTP allows users to log in with a generic username (e.g., "anonymous") and use their email
address as the password.
Gopher was an early protocol used for distributing, searching, and retrieving documents over the internet. It predates
the World Wide Web and was popular in the early 1990s. Developed at the University of Minnesota in 1991, Gopher
provided a way to organize and access information in a hierarchical structure. However, it eventually declined in
popularity as the World Wide Web, which offered more flexibility and multimedia capabilities, gained widespread
adoption.
Here are the key features and aspects of the Gopher protocol:
1.Hierarchical Structure:
•Gopher organized information in a hierarchical menu-like structure, where each item in the hierarchy could
represent a document, directory, or an application.
2.Text-Based:
•Gopher was primarily a text-based protocol. Unlike the World Wide Web, which evolved to support
multimedia content, Gopher was limited to text and hyperlinks.
3.Client-Server Architecture:
•Similar to other early internet protocols, Gopher used a client-server model. Users would use Gopher clients to
connect to Gopher servers to retrieve information.
4.Uniform Resource Locator (URL) Format:
•Gopher URLs were simple and used a hierarchical format. They typically looked like this:
gopher://<host>:<port>/<selector>. The host and port specified the Gopher server, and the selector indicated
the specific item or document to retrieve.
5.Limited Functionality:
•Gopher had a more straightforward functionality compared to the later-developed World Wide Web. It lacked
support for images, multimedia, and dynamic content.
Telnet, short for "telecommunication network," is a protocol used for two-way interactive communication between
computers over a TCP/IP network. It was initially designed for remote login to computers and network devices,
allowing users to access a remote system's command-line interface as if they were physically present at the machine.
However, due to security concerns associated with transmitting data in plaintext, Telnet has largely been replaced by
more secure protocols like SSH (Secure Shell).
Here are the key aspects of Telnet:
1.Protocol:
•Telnet operates on the application layer of the Internet Protocol Suite (TCP/IP). It uses TCP (Transmission
Control Protocol) to establish a connection between the client and the server.
2.Client-Server Model:
•Telnet follows a client-server architecture. The user's device (client) connects to a remote system (server) over
the network.
3.Port Number:
•The default port for Telnet is 23. When connecting to a Telnet server, users typically specify the hostname or
IP address of the remote system along with the port number (e.g., telnet example.com 23).
Trivial File Transfer Protocol (TFTP) is a simple file transfer protocol that operates on the User
Datagram Protocol (UDP). It is designed for minimal file transfer functionality and is commonly used in
scenarios where a lightweight and basic file transfer service is sufficient. TFTP is defined in RFC 1350
and subsequent RFCs.
Here are the key details about TFTP:
1.Connectionless Protocol:
1. TFTP uses UDP, a connectionless protocol, for communication. Unlike other file transfer
protocols like FTP, which use TCP for reliable data transfer, TFTP does not establish a connection
before transferring data.
2.Port Numbers:
1. The standard port numbers for TFTP are UDP port 69. The server listens on port 69, and the
client uses a dynamically assigned port.
3.Simplicity:
1. TFTP is intentionally designed to be simple and lightweight. It lacks many features found in more
complex protocols like FTP, such as directory listings, authentication, and error recovery
mechanisms.
Simple Network Management Protocol (SNMP) is an Internet standard protocol used for managing and monitoring
network devices and their functions. SNMP is widely employed in network management systems to collect
information from various devices, such as routers, switches, servers, printers, and more. It allows administrators to
monitor the performance, identify issues, and configure settings on network devices.
Here are the key details about SNMP:
1.Components:
1. SNMP involves three main components: managed devices, agents, and network management systems.
1. Managed Devices: These are the network devices being monitored or managed, such as routers,
switches, servers, printers, etc.
2. Agents: Agents are software modules installed on managed devices. They collect and store information
about the device and make it available for retrieval via SNMP.
3. Network Management Systems (NMS): NMS is the software or system responsible for monitoring and
managing the network. It communicates with SNMP agents to gather information and configure
devices.
2.Versions:
1. SNMP has several versions, with SNMPv3 being the most widely used and recommended. SNMPv3
introduced security enhancements, including authentication and encryption, addressing some of the
security concerns associated with earlier versions.
3.Communication:
1. SNMP uses a client-server model. The NMS acts as the client, and the SNMP agent on the managed device
acts as the server. The NMS communicates with SNMP agents using SNMP messages, which consist of
requests, responses, and traps.
Hypertext Transfer Protocol (HTTP) is the foundation of data communication on the World Wide Web. It is an
application layer protocol used for transmitting hypertext, which includes text, images, videos, and other
multimedia files. HTTP defines how messages are formatted and transmitted and how web browsers and servers
should respond to various commands.
Here are key details about HTTP:
1.Client-Server Model:
1. HTTP follows a client-server model. Clients (usually web browsers) send requests to servers, and servers
respond with the requested resources or information.
2.Stateless Protocol:
1. HTTP is stateless, meaning each request from a client to a server is independent, and the server does not
maintain any information about the client's state between requests. This simplifies the implementation but
requires additional mechanisms for managing state (e.g., cookies, sessions) when needed.
3.Connectionless:
1. HTTP is connectionless, which means that after a request is made and a response is sent, the connection
between the client and server is closed. Subsequent requests require the opening of a new connection.
4.Request Methods:
1. HTTP defines various request methods or verbs, including:
1. GET: Requests data from a specified resource.
2. POST: Submits data to be processed to a specified resource.
3. PUT: Updates a resource or creates a new resource if it doesn't exist.
4. DELETE: Requests the removal of a resource.
5. HEAD: Requests headers of a specified resource without the actual data.
•Browser Engine: The browser engine is responsible for coordinating web content that
is fetched from the server and user interactions. It keeps a note of which button is
clicked, which URL is asked to parse, and how the web content will be processed and
displayed on the browser.
•Rendering Engine: The rendering engine, on the other hand, interprets and renders
web content. In most browsers, both the browser engine and the rendering engine work
together in order to provide better results to the user.

You might also like