PHP Full Course With Coding Examples and Chapter Vice

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

PHP Overview

PHP is a server-side scripting language, which is used to manage dynamic web pages, databases and build websites w
, Rasmus Lerdorf unleashed the first version of “Hypertext Preprocessor” also known as the PHP language. It is also i
Microsoft SQL Server, Oracle etc.

Uses of PHP
PHP can perform several system functions like opening files, CRUD operations on data stores, general-purpose scrip
e

Handling Forms: PHP can handle form operations. It can gather data, save data to a file and send data through emai
Database Operations: PHP can also create, read, update and delete elements in your database.
Encryption: It can perform advanced encryption and encrypt data for you.
Dynamic Page Content: It can generate dynamic page content.

Basic Syntax PHP


A PHP script can be written anywhere inside the HTML document. A PHP script starts with <?php tag and ends with ?
cordingly.

<?php
// PHP code goes here
?>
Displaying output in php
In php,Output is displayed on the browser using echo as follows:

<?php
echo "hello";
?>
Hello World
A basic PHP Hello World program looks something like this. We will use a built-in PHP function “echo” to output the t

<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

PHP Comments
A comment is a part of the coding file that the programmer does not want to execute, rather the programmer uses i
pecific part of code while testing.

PHP supports several ways of commenting:


Single Line Comments

<?php
// This is a single-line comment
# This is also a single-line comment
?>

Multiple-Line Comments
<?php
/*
This is a
multiple line
Comment.
*/
?>

Variables in PHP
Variables are containers that can store information which can be manipulated or referenced later by the programme

In PHP, we don’t need to declare the variable type explicitly. The type of variable is determined by the value it stores.
PHP.

All variables should be denoted with a Dollar Sign ($)


Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluate
Variable names can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
Variables must start with a letter or the underscore “_” character.
Variables are case sensitive
Variable names cannot start with a number.

For Example:

<?php
$txt = "Hello world!"; # Type String
$x = 5; # Type int
$y = 10.5; # Type Float
?>

Variable Scope
The scope of the variable is the area within which the variable has been created. Based on this a variable can either h

Global Variable:
A variable which was created in the main body of the code and that can be accessed anywhere in the program is call
ed in or outside of a function with GLOBAL keyword before variable. However, we can also call them without the glob

For Example:

<?php
$name = "Harry Bhai"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Output:

Variable inside the function: Harry Bhai


Variable outside the function: Harry Bhai
Local Variable:
A local variable is created within a function and can be only used inside the function. This means that these variables
cope.

For Example:

<?php
function mytest()
{
$capital = "Delhi";
echo "Capital of India is: " .$capital;
}
mytest(); //Calling the function
//using $capital outside the function will generate an error
echo $capital;
?>
Output:

Capital of India is: Delhi Notice: Undefined variable: capital in D:\xampp\htdocs\pro

Static Variable:
PHP has a feature that deletes the variable once it has finished execution and frees the memory. When we need a lo
use the static keyword before it and the variable is called static variable.

These variables only exist in a local function and do not get deleted after the execution has been completed.

For Example:

<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in non-static variable which will increment its value to 7
$num1++;
//increment in static variable which will increment its value to 4 after first execution and 5 after second executio
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}

//first function call


static_var();

//second function call


static_var();
?>
Output:

Static: 4
Non-static: 7
Static: 5
Non-static: 7

PHP DataTypes
Data type specifies the type of value a variable requires to do various operations without causing an error. By defaul
String
Integer
Float
Boolean
Array
NULL

1. String
A string is a sequence of characters that holds letters and numbers. It can be anything written inside single or double

For Example:

<?php
$x = "Hello world!";
echo $x;
?>

2. Integer
An integer is a non-decimal number typically ranging between -2,147,483,648 and 2,147,483,647.

<?php
$x = 55;
var_dump($x);
?>

3. Float
A float is a number with a decimal point. It can be an exponential number or a fraction.

<?php
$x = 52.55;
var_dump($x);
?>

4. Boolean
A Boolean represents two values: True or False.

<?php
$x = true;
$y = false;
?>

5. Array
Array is a collection of similar data elements stored in a single variable.

<?php
$x =array("Rohan", "Lovish", "Harry");
var_dump($x);
?>

6. NULL
Null is a special data type with only one value which is NULL. In PHP, if a variable is created without passing a value, i

<?php
$x =null;
?>

PHP Operators
PHP has different types of operators for different operations. They are as follows:

1. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations.

Name Operator Example

Addition + $x+$y

Subtraction - $x-$y

Multiplication * $x*$y

Division / x/$y

Modulus % $x%$y

Exponentiation ** $x**$y

2. Assignment Operators
These operators are used to assign values to variables.

Name Evaluated as

= a=b

+= a=a+b

-= a=a-b

*= a=a*b

/= a=a/b

%= a=a%b

3. Comparison Operators
These operators are used to compare two values.

Name Operator Example

Equal == $x==$y

Identical === $x===$y

Not equal != $x!=$y

Not equal <> $x<>$y

Not Identical !=== $x!===$y


Greater than > $x>$y

Less than < $x<$y

Greater than or equal to >= $x >= $y

Less than or equal to <= $x <= $y

Spaceship <=> $x <=> $y

4. PHP Increment/ Decrement Operators


These operators are used to increment/ decrement variable’s value.

Name Operator

Pre-Increment ++$x

Post-Increment $x--

Pre-decrement –$x

Post-decrement $x- -

5. PHP Logical Operators


These are the logical operators that combine conditional statements.

Name Operator Example

And and $x and $y

Or or $x or $y

Xor xor $x xor $y

And && $x && $y

Or || $x || $y

Not ! !&x

6. PHP String Operators


PHP has these two operators designed for strings.

Name Operator Example

Concatenation . $text1 . $text2

Concatenation Assignment .= $text1 .= $text2

7. PHP Array Operators


These Operators are used to compare arrays.

Name: Operator: Example:

Union + $x + $y

Equality == $x = $y

Identity === $x === $y

Inequality != $x != $y

Inequality <> $x <> $y

!==Non-Identity !== $x !== $y

8. PHP Conditional Operators


These operators assign values to operands based on the outcome of a certain condition.

Name : Ternary : Null Coalescing:

Operator ?: ??

Example $x = exp1 ? exp2 : exp3 $x = exp1 ?? exp2

PHP Conditional Statements


Conditional Statements are used to perform actions based on different conditions. Sometimes when we write a prog
We can solve this by using conditional statements.

In PHP we have these conditional statements:

if Statement.
if-else Statement
If-elseif-else Statement
Switch statement

1. if Statement
This statement executes the block of code inside the if statement if the expression is evaluated as True.

Example:

<?php
$x = "22";
if ($x < "20") {
echo "Hello World!";
}
?>

2. if-else Statement
This statement executes the block of code inside the if statement if the expression is evaluated as True and executes
s evaluated as False.

Example:

<?php
$x = "22";
if ($x < "20") {
echo "Less than 20";
} else {
echo "Greater than 20";
}
?>

3. If-else-if-else
This statement executes different expressions for more than two conditions.

Example:

<?php
$x = "22";
if ($x == "22") {
echo "correct guess";
} else if ($x < "22") {
echo "Less than 22";
} else {
echo "Greater than 22";
}
?>

4. Switch Statement
This statement allows us to execute different blocks of code based on different conditions. Rather than using if-elseif

Example:

<?php
$i = "2";
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>

PHP Iterative Statements


Iterative statements are used to run same block of code over and over again for a certain number of times.

In PHP, we have the following loops:

while Loop
do-while Loop
for Loop
foreach loop

1. While Loop
The While loop in PHP is used when we need to execute a block of code again and again based on a given condition.
executed. Such a loop is known as an infinite loop.

Example:

<?php
$x = 1;
while($x <= 10) {
echo "The number is: $x <br>";
$x++;
}
?>

2. Do-While Loop
The do-while loop is similar to a while loop except that it is guaranteed to execute at least once. After executing a pa
based on a given boolean condition.

Example:

<?php
$x =10;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 9);
?>

3. For Loop
The for loop is used to iterate a block of code multiple times.

Example:

<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>

4. Foreach loop
The foreach loop in PHP can be used to access the array indexes in PHP. It only works on arrays and objects.

Example:

<?php
echo "Welcome to the world of foreach loops <br>";
$arr = array("Bananas", "Apples", "Harpic", "Bread", "Butter");
foreach ($arr as $value) {
echo "$value <br>";
}
?>

Function Basics
Function arguments are variables of some supported data type that are processed within the body of the function. It

PHP has more than 1000 built-in functions, and in addition, you can also create your own functions.

Advantages:
Functions reduce the complexity of a program and give it a modular structure.
A function can be defined only once and called many times.
It saves a lot of code writing because you don't need to write the same logic multiple times, you can write the logic on

Built-in Functions: PHP has thousands of built-in functions. For a complete reference and examples, you can go to th

User Defined Functions: Apart from built-in functions, We can also create our own functions and call them easily.

A user-defined function looks something like this:

<?php
Function functionname(){
//Code
}
functionname(); // Calling Function
?>

Note: A function name should only start with letters and underscore only. It can’t start with numbers and special sym

Example:

<?php
function helloMsg() {
echo "Hello world!";
}
helloMsg(); // call the function
?>

Function Arguments
Function Arguments: Argument is just like a variable which can be used to pass through information to functions.

PHP supports Call by Value, Call by Reference, Default Argument Values and Variable-length argument.

1. Call by Value
In Call by Value, the value of a variable is passed directly. This means if the value of a variable within the function is c

Example:

<?php
function incr($i)
{
$i++;
}
$i = 5;
incr($i);
echo $i;
?>
Output:

2. Call by Reference
In call by reference, the address of a variable (their memory location) is passed. In the case of call by reference, we p
definition. Any change in variable value within a function can reflect the change in the original value of a variable.

Example:

<?php
function incr&$i)
{
$i++;
}
$i = 5;
incr($i);
echo $i;
?>
Output:

3. Default Argument Values


If we call a function without arguments, then PHP function takes the default value as an argument.

Example:

<?php
function Hello($name="Aakash"){
echo "Hello $name <br>";
}
Hello("Rohan");
Hello();//passing no value
Hello("Lovish");
?>
Output:

Hello Rohan
Hello Aakash
Hello Lovish

4. Variable Length Argument


It is used when we need to pass n number of arguments in a function. To use this, we need to write three dots inside

Example:

<?php
function add(...$nums) {
$sum = 0;
foreach ($nums as $n) {
$sum += $n;
}
return $sum;
}
echo add(1, 2, 3, 4);
?>
Output:

10

Arrays
An array is a collection of data items of the same data type. And it is also known as a subscript variable.

Example:

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

There are three different kinds of arrays.

1. Numeric Array
These are arrays with a numeric index where values are stored and accessed in a linear fashion.

Example:

<?php
$bike = array("TVS", "YAMAHA", "RAJDOOT");
echo "I like " . $bike[0] . ", " . $bike[1] . " and " . $bike[2] . ".";
?>

2. Associative Array
These are arrays with string as an index where it stores element values associated with key values.

Example:

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

3. Multidimensional Arrays
A multidimensional Array is an array containing one or more arrays where values are accessed using multiple indice

Example:

<?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>";
?>

Introduction to OOPS
OOP stands for Object-Oriented Programming.

Object-oriented programming is a core of PHP Programming, which is used for designing a program using classes an

Advantages of OOPS
Programs are faster to execute.
Better code reusability.
Easy to understand code structure.
Very easy to partition the work in a project based on objects.
Easy to make fully reusable programs with less code and less development time.

Disadvantages of OOPS
OOPS cannot be applied everywhere as it is not a universal language.
Need to have a good understanding of classes and objects to apply OOPS.
It takes a lot of effort to create.
It is slower than other programs.
OOPS programs are large in size when compared to normal programs.

Classes
Classes are the blueprint of objects. Classes hold their own data members and member functions, which can be acce
defined using the class keyword, followed by the name of classes and curly braces ({}).

Example:

<?php
class class_name {
// code goes here...
}
?>

Creating a Class in PHP


We will create a class Employee where we will have two properties and two methods for setting and getting the prop

<?php
class Employee {
// Properties
public $name;
public $surname;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Note: The $this keyword refers to the current object, and is only available inside methods.

Objects
Object is an instance of class. An Object is a self-contained component which consists of methods and properties to
ects from a class and each object will have all the properties and methods defined in the class, but they will have diff
new keyword.
Example:

$object_name = new ClassName();

Creating an Object in PHP


We will create two objects in the following example.

<?php
class Employee {
// Properties
public $name;
public $surname;

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

$emp1 = new Employee();


$emp2= new Employee();
$emp1->set_name('Harry');
$emp2->set_name('Shayan');

echo $emp1->get_name();
echo "<br>";
echo $emp2->get_name();
?>
Output:

Harry
Shayan

Inheritance
When a class is defined by inheriting the existing function of a parent class then it is called inheritance. Here child cla
s of a parent class. We can define an inherited class by using the extends keyword.

Inheritance has three types Single, Multiple and Multilevel Inheritance but PHP only supports single inheritance, whe

Example:

<?php
class exm {
public function func1()
{
echo "example of inheritance ";
}
}
class exm1 extends exm {
public function func2()
{
echo "in php";
}
}
$obj= new exm1();
$obj->func1();
$obj->func2();
?>
Output:

example of inheritance in php

Final Keyword
The final keyword can be used to prevent method overriding or to prevent class inheritance.

Example:

<?php
final class Employee {
// some code
}
// This will result in error as the final keyword is used
class human extends Employee {
// some code
}
?>

Constructors and Destructors


Constructor
In PHP, a constructor allows you to initialize an object's properties upon the creation of the object. The constructor fu
_construct() function, then PHP will automatically call this function when we create an object from a class.

Example:

<?php
class Employee {
public $name;
public $surname;

function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$emp1= new Employee("Lovish");
echo $emp1->get_name();
?>
Output:

Lovish

Destructor
Destructor is a special member function which is exactly the reverse of the constructor method. When it is called an
function starts with two underscores (__) and if we create a __destruct() function, then PHP will automatically call this

Example:

<?php
class Employee {
public $name;

function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "Employee name is {$this->name}.";
}
}

$emp1= new Employee("Izhaan");


?>
Output:

Employee name is Izhaan.

Access Modifiers
In the PHP programming language, every property and method of a class can have access modifiers which control th

There are three access modifiers in PHP:

Public
Protected
Private

Below is a table for a better understanding of the access modifiers

Class Member Access Specifier Access from own class Accessible from derived class Accessible by Object
Private Yes No No
Protected Yes Yes No
Public Yes Yes Yes

Public
Public property or method can be accessed by any code whether that code is inside or outside of that class. If a prop
ere from the code.

Example:

<?php
class Employee{
public $name;
}

$emp1= new Employee();


$emp1->name = 'Harry';
?>

Protected
Protected property or method can only be accessed within the class and by the classes derived from that class.

Example:
<?php
class ParentClass {
protected $parentMsg = "protected parent attribute<br>";
protected function parentDisplay() {
echo "protected parent method<br>";
echo $this->parentMsg;
}
}
class ChildClass extends ParentClass {
protected $childMsg = "Protected Child attribute.<br>";
public function childDisplay() {
echo "Public Child method to display protected parent members:<br>";
$this->parentDisplay();
}
}
$child = new ChildClass();
$child->childDisplay();
?>
Output:

Public Child method to display protected parent members:


protected parent method
protected parent attribute

Private
The Private property or method can only be accessed within the class. If it is called outside of the class, then it will th

Example:

<?php
class Employee {
public $salary;

private function set_salary($n) { // a private function


$this->salary= $n;
}
}

$emp1= new Employee();


$emp1->set_salary('300'); //It will throw error as It can not Access the Private Function
?>

Interface
Interfaces permit users to programmatically define the public methods that a class should implement without bothe
ular method. Interfaces make it easy to use different classes in the same way. When one or more classes use the sam

Interfaces are declared with interface keyword.

Example:

<?php
interface InterfaceName {
public function Method1();
public function Method2($name, $surname);
public function Method3() : string;
}
?>

Implementing Interface
To implement an interface on a class, we need to use implements keyword.

Example:

<?php
interface Human {
public function makeSound();
}

class Programmer implements Human{


public function makeSound() {
echo "Hello World";
}
}

$human = new Programmer();


$human->makeSound();
?>

Abstract Classes
Abstract classes and methods are when the parent class has a named method but the child class needs to complete

An abstract class is a class that contains at least one abstract method. Abstract methods are methods that are declar

We can define an Abstract class or method with the abstract keyword.

Example:

<?php
abstract class ParentClass {
abstract public function Method1();
abstract public function Method2($name);
abstract public functionMethod3() : string;
}
?>

When inheriting from an abstract class, methods in subclasses must be defined with the same name and with the sa
defined as protected, the subclass's method must be either protected or defined as public, but not private. Also, the
, subclasses can specify additional optional arguments.

So, when a child class is inherited from an abstract class, we have the following rules:

The child class method must be defined with the same name.
The child class method must be defined with the same or a less restrictive access modifier
The number of required arguments must be the same. However, the child class may have optional arguments in add
Example
<?php
// Parent class
abstract class Bike {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function intro() : string;
}

// Child classes
class Yamaha extends Bike {
public function intro() : string {
return "I'm a $this->name!";
}
}

class splendor extends Bike {


public function intro() : string {
return "I'm a $this->name!";
}
}

class Vespa extends Bike {


public function intro() : string {
return "I'm a $this->name!";
}
}

// Create objects from the child classes


$yamaha = new yamaha("Yamaha");
echo $yamaha->intro();
echo "<br>";

$splendor = new splendor("Splendor");


echo $splendor->intro();
echo "<br>";

$vespa = new vespa("Vespa");


echo $vespa->intro();
?>
Output

I'm a Yamaha!
I'm a Splendor!
I'm a Vespa!

Class Constants
Constants are like variables except that once they are defined, they cannot be changed. If we need to define some co
constants are case-sensitive and they can be declared inside a class with the const keyword. We can also access a co
operator with constant name.

Example:

<?php
class Namaste {
const GREETING_MSG= "Namaskaram Dosto!!";
}

echo Namaste::GREETING_MSG;
?>

We can also use the self keyword to access the constant inside the class.

Example:

<?php
class HelloWorld {
const New_Message = "Did I leave the Stove on?";
public function ByeWorld() {
echo self::New_Message;
}
}

$helloworld= new HelloWorld();


$helloworld->ByeWorld();
?>

Traits
PHP language only supports single-level inheritance where a child class can inherit only from one single parent. If we
use Traits to solve this.

Traits are used to declare methods that can be used in multiple classes which can have any access modifier (public, p
ract methods that can be used in multiple classes.

Traits are declared with the trait class and to use a train in a class we need to use the use keyword.

Example:

<?php
trait message1 {
public function msg1() {
echo "give me cheeseburgers ";
}
}

class Welcome {
use message1;
}

$obj = new Welcome();


$obj->msg1();
?>
Output:

give me cheeseburgers

Static Methods
In certain cases where we need to access methods and properties in terms of class rather than an object, the static m
sed without creating an object.

Static methods are declared with the static keyword.

Example

<?php
class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
?>

To access a static method we need to use the class name followed by a double colon (::), and the method name.

Example:

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

// Call static method


greeting::welcome();
?>

A static method can be accessed from a method in the same class using the self keyword followed by a double colon

Example:

<?php
class greeting {
public static function welcome() {
echo "Hello Bro!";
}
public function __construct() {
self::welcome();
}
}
new greeting();
?>

Static Properties
Static properties can be accessed directly without creating an instance of a class. Static properties can be declared by

To access a static property we need to write the class name followed by a double colon (::), and the property name.\

Example:

<?php
class pi {
public static $value = 3.14;
}
// Getting static property
echo pi::$value;
?>

A static method can be accessed from a method in the same class using the self keyword followed by a double colon

Example

<?php
class pi {
public static $value=3.14159;
public function staticValue() {
return self::$value;
}
}

$pi = new pi();


echo $pi->staticValue();
?>

If we need to call a static property from a child class, we can use the parent keyword inside the child class.

Example:

<?php
class pi {
public static $value=3.14;
}
class x extends pi {
public function xStatic() {
return parent::$value;
}
}
// Get value of static property directly via child class
echo x::$value;

Superglobals
Superglobals are built-in variables that are always available in all scopes. There is no need to do global $variable; to a

The PHP superglobal variables are:

$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
$GLOBALS
$GLOBALS is a superglobal variable, which is also an array that stores all the global scope variables and is used to ac

Example:

<?php
$x = 10;
$y = 11;

function add() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

add();
echo $z;
?>

Output:

21

$_SERVER
$_SERVER is a superglobal variable which holds the data about the headers, script locations, network addresses, path

Example:

<?php
echo $_SERVER['PHP_SELF'] . '<br>';
echo $_SERVER['DOCUMENT_ROOT'] . '<br>';
echo $_SERVER['SERVER_ADDR'] . '<br>';
echo $_SERVER['SERVER_NAME'] . '<br>';
echo $_SERVER['REQUEST_METHOD'] . '<br>';
echo $_SERVER['REQUEST_TIME'] . '<br>';
echo $_SERVER['HTTP_USER_AGENT'] . '<br>';
echo $_SERVER['REMOTE_ADDR'];
?>

The following table lists some of the important elements of $_SERVER

Element/Code Description
$_SERVER['PHP_SELF'] Returns the filename of the currently executing script
$_SERVER['GATEWAY_INTERFACE'] Returns the version of the Common Gateway Interface the server is using
$_SERVER['SERVER_ADDR'] Returns the IP address of the host server
$_SERVER['SERVER_NAME'] Returns the name of the host server
$_SERVER['SERVER_SOFTWARE'] Returns the server identification string
$_SERVER['SERVER_PROTOCOL'] Returns the name and revision of the information protocol
$_SERVER['REQUEST_METHOD'] Returns the request method used to access the page
$_SERVER['REQUEST_TIME'] Returns the timestamp of the start of the request
$_SERVER['QUERY_STRING'] Returns the query string if the page is accessed via a query string
$_SERVER['HTTP_ACCEPT'] Returns the Accept header from the current request
$_SERVER['HTTP_ACCEPT_CHARSET'] Returns the Accept_Charset header from the current reques
$_SERVER['HTTP_HOST'] Returns the Host header from the current request
$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page
$_SERVER['HTTPS'] Is the script queried through a secure HTTP protocol
$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page
$_SERVER['REMOTE_HOST'] Returns the Hostname from where the user is viewing the current page
$_SERVER['REMOTE_PORT'] Returns the port being used on the user's machine to communicate with the we
$_SERVER['SCRIPT_FILENAME'] Returns the absolute pathname of the currently executing script
$_SERVER['SERVER_ADMIN'] Returns the value given to the SERVER_ADMIN directive in the web server configu
$_SERVER['SERVER_PORT'] Returns the port on the server machine being used by the web server for commu
$_SERVER['SERVER_SIGNATURE'] Returns the server version and virtual host name which are added to server-ge
$_SERVER['PATH_TRANSLATED'] Returns the file system-based path to the current script
$_SERVER['SCRIPT_NAME'] Returns the path of the current script
$_SERVER['SCRIPT_URI'] Returns the URI of the current page

$_REQUEST
The PHP $_REQUEST is a PHP superglobal variable that is used to collect the data after submitting an HTML form. Th
the contents of $_GET, $_POST and $_COOKIE superglobals.

Example:

<html>
<body>

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


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

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

</body>
</html>

$_POST
The PHP $_POST is a PHP superglobal which is used to collect form data after submitting an HTML form using metho
l to collect a value.

htmlentities() Function: The htmlentities() function is an inbuilt function that is used to transform all characters which

Example:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_REQUEST['fname']); //Collecting Value
if (empty($name)) {
echo "Empty Name";
} else {
echo $name;
}
}
?>

$_GET
The PHP $_GET is a PHP superglobal which is used to collect form data after submitting an HTML form using method
played in the browser's address bar making it less secure than POST.

Let's assume we have a HTML form that takes name and email as an input and sends it to anothe file named "name_
lobal.

HTML FORM

<html>
<body>

<form action="name_get.php" method="get">


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

</body>
</html>

name_get.php

<html>
<body>

Welcome <?php echo $_GET["name"]; ?>!


Your email address is <?php echo $_GET["email"]; ?>

</body>
</html>

Output:

Welcome Harry!
Your email address is harry@example.com

$_COOKIE
Cookie
Cookie is a small file that the server embeds on the user's computer. Each time the computer opens a webpage, the
function to create a cookie object to be sent to the client along with HTTP response.

Creating Cookies with PHP


A cookie can be created with the setcookie() function.

Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);

Parameters
Name − Name of the cookie stored.
Value − This sets the value of the named variable.
Expiry − This specifes a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
Path − Directories for which the cookie is valid.
Domain − Specifies the domain name in very large domains.
Security − 1 for HTTPS. Default 0 for regular HTTP.

Example:

<?php
$cookie_name = "username";
$cookie_value = "rohan";
//The setcookie() function must appear BEFORE the <html> tag.
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

Modifying a Cookie
To modify a cookie, just set the cookie again using the setcookie() function.

Example:

<?php
$cookie_name = "username";
$cookie_value = "aakash";
//The setcookie() function must appear BEFORE the <html> tag.
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

Delete a Cookie
To delete a cookie, we need to use the setcookie() function with a date that has already expired.

Example:

<?php
// set the expiration date to one day ago
setcookie("username", "", time() - 86400);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>

$_SESSION
A session is a way to store information to be used across multiple pages. Session variables store user information wh
til the user closes the browser.

Starting a PHP Session


In PHP a session can be started with the session_start() function. Sessions variables are set with the $_SESSION varia
his page, we will start a new PHP session and set session variables.

example1.php

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["uname"] = "shayan";
$_SESSION["upass"] = "hunter";
echo "Session variables are set.";
?>

</body>
</html>
Get PHP Session Variable Values
Now we will create a new page named example2.php. Now from this page, we will access the session variables we ha

example2.php

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["uname"] . ".<br>";
echo "Favorite animal is " . $_SESSION["upass"] . ".";
?>

</body>
</html>
We can also see all the session variables by using print_r($_SESSION).

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>

Modifying a Session Variable


To modify a session variable we just need to overwrite it.

Example:

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["uname"] = "aakash";
print_r($_SESSION);
?>

</body>
</html>

Destroying a PHP Session


To delete all the session variables and destroy the session, we can use session_unset() and session_destroy().
Example:

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>

You might also like