Chapter1-Introduction To PHP
Chapter1-Introduction To PHP
of CS
Introduction to PHP, History and Features of PHP, Installation & Configuration of PHP, Embedding PHP
code in Your Web Pages, Understanding PHP, HTML and White Space, Writing Comments in PHP,
Sending Data to the Web Browser, Data types in PHP, Keywords in PHP, Using Variables, Constants in
PHP, Expressions in PHP, Operators in PHP.
PHP is an open-source, interpreted, and object-oriented scripting language that can be executed at the server-side.
PHP is well suited for web development. Therefore, it is used to develop web applications (an application that
executes on the server and generates the dynamic page.).
History of PHP
• The first version of PHP is PHP/FI (Form Interpreter) developed by Ramous Lerdorf, monitoring page
view for his online resume.
• This version supports some basic function, capable to handle form data and mSql db.
• PHP/FI 1.0 followed by PHP/FI 2.0 and quickly supplanted in1997 by PHP3.0.
• PHP3.0 developed by Anti Gutmus and Zee Surakshi, complete rewrite of PHP/FI.
• It supports a wide range of database such as MySQL and Oracle.
• In 2003 PHP4.0 was released with better performance, greater reliability, and support for web server other
than Apache. Support OOPs concept.
• PHP 5.0 support message passing, abstract classes, destructor, and better memory management.
• PHP is used on over 15 million website.
• Loosely-typed language– Developers can use a variable without declaring the datatype during scripting and is
automatically used during execution depending on the data type containing the related valuation.
• Syntax familiarity– The syntax of PHP is very simple to understand and is suitable for different web
development needs.
• Error reporting– There are pre-defined error reporting constants available under PHP. It can produce real-
time error warnings, like E_WARNING, E_PARSE, and E_STRICT.
• Better control quality– There is no need for excess or long codes or scripts with PHP. It has higher control on
web solutions; developers can make changes without extra coding.
• High-security– Among the different scripting language types available, PHP is one of the most secure options
with multiple security levels in place. The multi-layered structure safeguards against hacking attempts,
malware, etc.
HTML is compatible with almost all Browsers. PHP also compatible with all types of Browsers.
HTML is used to organize the content of the PHP is used to “interact” with the database to
websites. It focuses on how the contents need to retrieve the information, storing the data, e-mail
display with different fonts, size and sending and provides the content to
colors etc. The HTML pages to display on the screen.
<html> <?PHP
<body>
</body>
</html> ?>
Below is 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:
Example
<?php
echo "Hello World!";
?>
Note: PHP statements end with a semicolon (;).
PHP Echo
PHP echo is a language construct, not a function. Therefore, there is no need to use parenthesis with it. But if more
than one parameter, it is required to use parenthesis. PHP echo statement can be used to print the string, multi-line
strings, escaping characters, variable, array, etc.
Example
<?php
echo "Hello by PHP echo";
?>
PHP Print
Like PHP echo, PHP print is a language construct, so no need to use parenthesis with the argument list. Print
statement can be used with or without parentheses: print and print(). Unlike echo, it always returns 1. PHP print
statement can be used to print the string, multi-line strings, escaping characters, variable, array, etc.
print
o print is also a statement, used as an alternative to echo at many times to display the output.
o print can be used with or without parentheses.
o print always returns an integer value, which is 1.
o Using print, we cannot pass multiple arguments.
o print is slower than echo statement.
Understanding PHP
PHP is a server-side scripting language, which is used to design the dynamic web applications with MySQL
database.
o It handles dynamic content, database as well as session tracking for the website.
o You can create sessions in PHP.
Comments in PHP
PHP comments can be used to describe any line of code so that other developer can understand the code easily. It
can also be used to hide any code.
PHP supports single line and multi-line comments. These comments are similar to C/C++ and Perl style (UNIX shell
style) comments.
The GET method is limited to 1024 characters and is used to submit HTML form data. The information is collected
by the predefined $_GET variable and is visible to everyone in the browser's address bar. The page and the
encoded information are separated by the ? character.
The POST method does not have any restriction on data size to be sent. Before the browser sends the information,
it encodes it using a scheme called URL encoding. The data submitted by this method is collected by the
predefined $_POST variable instead of $_GET. The encoded information is embedded in the body of the HTTP
request, so the data is not visible in the page URL.
Keywords in PHP
PHP keywords are words that have meaning and are automatically understood by PHP. They are fundamental
building blocks that help developers write efficient, maintainable, and powerful code. PHP keywords cannot be
used as variable names, class names, method names, or constants.
PHP Keywords
__halt_compiler() abstract and array() as
yield from
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
• As PHP is a loosely typed language, so we do not need to declare the data types of the variables. It automatically
analyzes the values and makes conversions to its correct datatype.
• After declaring a variable, it can be reused throughout the code.
• Assignment Operator (=) is used to assign the value to a variable.
File: variable1.php
<?php
$str="hello string";
$x=200;
$y=44.6;
echo "string is: $str <br/>";
echo "integer is: $x <br/>";
echo "float is: $y <br/>";
?>
Global Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
Example
Variable with global scope:
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
Output:
Variable x inside function is:
Variable x outside function is: 5
Local Scope
The variables that are declared within a function are called local variables for that function. These local variables
have their scope only in that particular function in which they are declared. This means that these variables cannot
be accessed outside the function, as they have local scope.
A variable declaration outside the function with the same name is completely different from the variable declared
inside the function.
Example
Variable with local scope:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
Output:
Variable x inside function is: 5
Variable x outside function is:
Static Variable
It is a feature of PHP to delete the variable, once it completes its execution and memory is freed. Sometimes we
need to store a variable even after completion of function execution. Therefore, another important feature of
variable scoping is static variable. We use the static keyword before the variable to define a variable, and this
variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the program execution leaves the
scope.
Example:
File: static_variable.php
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in non-static variable
$num1++;
//increment in static variable
$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
Notice that $num1 regularly increments after each function call, whereas $num2 does not. This is why because
$num1 is not a static variable, so it freed its memory after the execution of each function call.
1. PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script
(also from within functions or methods).
PHP stores all global variables in an array called $GLOBALS [index]. The index holds the name of the variable.
The example below shows how to use the super global variable $GLOBALS:
Example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
In the example above, since z is a variable present within the $GLOBALS array, it is also accessible from outside the
function!
2. 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:
Example
<?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['SCRIPT_NAME'];
?>
The following table lists the most important elements that can go inside $_SERVER:
Element/Code Description
$_SERVER['HTTP_REFERER'] Returns the complete URL of the current page (not reliable because not
all user-agents support it)
3. $_REQUEST: It is used to collect the data after submitting a html form. It is not widely used.$_GET and $_POST
perform the same task.
4. $_GET: It is a default form request. The data passed through get request is visible on the URL browser, so it is
notsecured. We can get limited amount of data through get request.
5. $_POST: Post request is widely used to submit form that have large amount of data such as file upload, image
upload etc. The data passed through post request is not visible on URL so it is secured. We can send large
amount of data through this.
6. $_SESSION: It is a way to store the information to be used at the multiple pages. By default, session variables
will be lost after closes the browser. Session_start() must be the very first in the document before any HTML
tags.
7. $_COOKIE: Cookies are small text files loaded from a server to a client computer. It stores the information
regarding the client computer so that the same page is visited by the user again and again. It decreases the
latency period to open the page.
8. $_FILES: It is used to upload the files. It is associated with 2-D array and it keeps all the information related to
the uploadedfile.
9. $_ENV: it is a super global variable that contains the environment variable where that environment variable is
provided by the shell under which php is running.
PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE (0). It is often
used with conditional statements. If the condition is correct, it returns TRUE otherwise FALSE.
Example:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers, i.e., numbers without
fractional part or decimal points.
Rules for integer:
o An integer can be either positive or negative.
o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -2^31 to 2^31.
Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold numbers with a fractional or
decimal point, including a negative or positive sign.
Example:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special characters.
String values must be enclosed either within single quotes or in double quotes. But both are treated differently. To
clarify this, see the example below:
Example:
<?php
$company = "Javatpoint";
//both single and double quote statements will treat different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>
PHP Array
An array is a compound data type. It can store multiple values of same data type in a single variable.
Example:
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
PHP object
Objects are the instances of user-defined classes that can store both values and functions. They must be explicitly
declared.
Example:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function calls or references to
external PHP resources. For example - a database call. It is an external resource.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it in capital letters as it is
case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
Implicit Casting
Implicit casting is something done by PHP according to your code, but you are not capable of customizing. When
dividing an integer by another integer the result can either be integer or float. The decision is taken by PHP. See the
below example.
PHP Implicit Casting Example
<?php
$x = 2;
$y = 4;
var_dump($x / $y); // 2/4 = 0.5 (Float)
var_dump($y / $x); // 4/2 = 2 (Int)
Explicit Casting
We can explicitly cast a variable to different data types. For instance, we can convert a float to an integer like
following. (The decimal portion will be dropped)
PHP Explicit Casting - Float to Integer
<?php
$x = 5.35;
$y = (int) $x; // cast $x to integer
var_dump($y);
The data type you need to change the variable into should be written inside parentheses, before the variable.
Cast Description
(int) or (integer) Cast to an integer.
The following example shows a useful way that you can use casting for. Casting any string that starts with a
number followed by a phrase to an integer will return the starting number as an integer.
2. Casting to a float
(float) , (double) and (real) are valid casts. All of them casts the variable to float data type.
When casting an integer to float there won't be any data loss, as integers do not have any decimal portion.
PHP Explicit Casting - Integer to Float
<?php
$x = 7;
$y = (float) $x; // $y is 7, but float
var_dump($y);
3. Casting to a boolean
Both bool and boolean are valid.
PHP Explicit Casting to Boolean
<?php
$a = (bool) 0;
$b = (bool) 5;
$c = (bool) '';
$d = (bool) 'Hyvor';
$e = (bool) [];
$f = (bool) [2,5];
$g = (bool) null;
var_dump($a); // false
var_dump($b); // true
var_dump($c); // false
var_dump($d); // true
var_dump($e); // false
var_dump($f); // true
var_dump($g); // false
$h = (boolean) 'Hyvor'; // boolean also valid
var_dump($h); // true
4. Casting to an array
We can add any single variable into an array which has only one element.
PHP Explicit Casting to Array
<?php
$a = (array) 5;
$b = (array) 'Hyvor';
$c = (array) true;
var_dump($a); // [5]
var_dump($b); // ['Hyvor']
var_dump($c); // [true]
Output:
3291
Output:
68
Pre-Set Variables
PHP has set a number of variables for you containing information about the server, the environment, and the
request from your visitor. These are stored in the super global arrays for you, and you can get a fairly complete list
of what is available by using the phpinfo() output.
The most commonly used variables, all of which are stored in the $_SERVER super global, are as follows:
Name Value
REQUEST_METHOD Either GET or POST
PHP_SELF The name of the current script
PATH_INFO Any data passed in the URL after the script name
HTTP_REFERER If the user clicked a link to get the current page, this will contain the
URL of the previous page they were at, or it will be empty if the user
entered the URL directly.
HTTP_USER_AGENT The name reported by the visitor's browser
QUERY_STRING Includes everything after the question mark in a GET request
Constants
PHP constants are name or identifier that can't be changed during the execution of the script except for magic
constants, which are not really constants. PHP constants can be defined by 2 ways:
1. Using define() function
2. Using const keyword
Constants are similar to the variable except once they defined, they can never be undefined or changed. They
remain constant across the entire program. PHP constants follow the same PHP variable rules. For example, it can
be started with a letter or underscore only.
Constant() function
There is another way to print the value of constants using constant() function instead of using the echo statement.
Syntax
The syntax for the following constant function:
constant (name)
File: constant5.php
<?php
define("MSG", "JavaTpoint");
echo MSG, "</br>";
echo constant("MSG");
//both are similar
?>
Pre-Set Constants
Pre-set Constants are reserved constants. Some constant names are reserved by PHP andcannot be redefined.
I we redefine these constants in your PHP program then, Notice will be issued By the Interpreter.
Some of the pre-defined constants of PHP are:
M_PI , M_SQRT2 , M_LOG2E , NAN , false , true , M_E , INF , M_PI_2 , M_LOG2E , M_LN10 etc.,
Expressions in PHP
An expression is a combination of values, variables, operators, and function calls that can be evaluated to produce a
value.
In PHP, an expression is a combination of values, variables, operators, and function calls that can be evaluated to
produce a single value. These elements come together to form a logical operation, and the result of this operation is
the output of the expression.
Components of an Expression:
1. Values: These are the raw data elements in programming. Examples include numbers (3, 10.2), strings (‘Hello
World'), and booleans (true, false).
2. Variables: Variables are containers for holding values. They have names and can store different values at
different points in program’s execution.
3. Operators: Operators are symbols or keywords that perform operations on values and variables. Examples
include arithmetic operators (+, -, * /), comparison operators (==, !=, <, >) and logical operators (&&, || ).
4. Function Calls: Functions are reusable blocks of code that perform specific tasks. When you call a function, it
can return a value. Function calls typically involve passing arguments enclosed in parentheses.
Examples of Expressions
1. Arithmetic Expression:
$result = 5 + 3;
Here, the expression 5+3 adds the values 5and 3, resulting in the value 8.
2. String Concatenation Expression:
$name = 'John';
$greetings = 'Hello, ' . $name;
The expression "Hello, " . $name concatenates the string "Hello, " with the value store in the variable $name .
Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to
perform operations on variables or values. For example:
$num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
o Unary Operators: works on single operands such as ++, -- etc.
o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".
Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as addition, subtraction,
etc. with numeric values.
Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators allow the evaluation
and manipulation of specific bits within the integer.
Xor Xor $a xor $b Return TRUE if either $ or $b is true but not both
Assignment Operators
The assignment operators are used to assign value to different variables. The basic assignment operator is "=".
Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators allow the evaluation
and manipulation of specific bits within the integer.
& And $a & $b Bits that are 1 in both $a and $b are set to 1, otherwise 0.
~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set to 1
<< Shift left $a << $b Left shift the bits of operand $a $b steps
>> Shift right $a >> $b Right shift the bits of $a operand by $b number of places
Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list of comparison
operators are given:
=== Identical $a === $b Return TRUE if $a is equal to $b, and they are of same data
type
Return TRUE if $a is not equal to $b, and they are not of same
!== Not identical $a !== $b
data type
<= Less than or equal to $a <= $b Return TRUE if $a is less than or equal $b
String Operators
The string operators are used to perform the operation on strings. There are two string operators in PHP, which
are given below:
Array Operators
The array operators are used in case of array. Basically, these operators are used to compare the values of arrays.
=== Identity $a === $b Return TRUE if $a and $b have same key/value pair of same
type in same order
In PHP, the double colon :: is defined as Scope Resolution Operator. It used when when we want to access
constants, properties and methods defined at class level. When referring to these items outside class definition,
name of class is used along with scope resolution operator. This operator is also called Paamayim Nekudotayim,
which in Hebrew means double colon.
<?php
class A{
const PI=3.142;
static $x=10;
}
echo A::PI;
echo A::$x;
$var='A';
echo $var::PI;
echo $var::$x;
?>
Inside class
To access class level items inside any method, keyword - self is used
<?php
class A{
const PI=3.142;
static $x=10;
static function show(){
echo self::PI . self::$x;
}
}
A::show();
?>
In child class
If a parent class method overridden by a child class and you need to call the corresponding parent method, it must
be prefixed with parent keyword and scope resolution operator
<?php
class testclass{
public function sayhello(){
echo "Hello World";
} }
class myclass extends testclass{
public function sayhello(){
parent::sayhello();
echo "Hello PHP";
} }
$obj=new myclass();
$obj->sayhello();
?>
var_dump() function: The var_dump() function in PHP displays information about one or more variables,
including their type and value. The syntax for var_dump() is void var_dump ($expsn), where $expsn is a single-
argument function that accepts a single variable or an expression containing several space separated variables of
any type. The function returns no value.
• Example 1: var_dump(var_dump(2, 2.1, TRUE, array(1, 2, 3, 4)));
• Example 2: $a = array(1, 2, array(``a'', ``b'', ``c'')); var_dump($a);`
• Example 3: $a = 32; echo var_dump($a) ;
• $b = ``Hello world! ''; echo var_dump($b) ;
• $c = 32.5; echo var_dump($c) ;
The var_dump() function explores arrays and objects recursively, with values indented to show structure. It is
available in PHP 4.0 and later.
************************