PHP Module 3
PHP Module 3
UNIT- III
INTRODUCTION TO PHP
PHP - INTRODUCTION
PHP started out as a small open source project “Personal Home Page” that gave
users access to their server logs and to process online form. Rasmus Lerdorf
created the first version of PHP way back in 1994.
Characteristics of PHP
Form handling, i.e. gather data from files, save data to a file.
Web server is a computer where the web content is stored. Basically web
server is used to host the web sites but there exists other web servers also such
as gaming, storage, FTP, email etc. The top web servers today are: Apache, IIS
(Internet Information Services) by Microsoft, GWS (Google Web Server)
by Google etc.
UNIT III S.A
Web site is collection of web pages and web server is software that responds to
the request for web resources. The web server run web server software (called
as daemon). It understands HTTP.
Web server respond to the client request in either of the following two ways:
Sending the file to the client associated with the requested URL.
Generating response by invoking a script and communicating with
database
1. Obtaining the IP Address from domain name: Our web browser first
obtains the IP address of the site. It can obtain the IP address in 2 ways-
2. Browser requests the full URL: After knowing the IP Address, the
browser now demands a full URL from the web server.
3. Web server responds to request: The web server responds to the browser
by sending the desired pages, and in case, the pages do not exist or some
other error occurs, it will send the appropriate error message.
For example:
You may have seen Error 404, while trying to open a webpage, which is
the message sent by the server when the page does not exist.
Another common one is Error 401 when access is denied to us due to
incorrect credentials, like username or password, provided by us.
4. Browser displays the web page: The Browser finally gets the webpages
and displays it, or displays the error message.
UNIT III S.A
When client sends request for a web page, the web server search for the
requested page. If requested page is found then it will send the page to
client with an HTTP response.
If the requested web page is not found, web server will the send an
HTTP response: Error 404 Not found.
If client has requested for some other resources then the web server will
contact to the application server and data store to construct the HTTP
response.
Features of web server
Hosts one or more websites. A server can contain more than onewebsite.
Configure log files settings such as where the log files are saved, what
data are included in the log file etc.
Configure website security.
Create FTP (File Transfer Protocol) sites. FTP sites allow transferring
files to and from the site.
Configure custom error pages. It displays user friendly error messages.
(404 Page Not Found).
UNIT III S.A
Web servers are used to execute server side scripting. They are basically
used tocreate dynamic pages. It can also access the file system residing at web
server. Server-side environment that runs on a scripting language is a web-
server.
Scripts can be written in any of a number of server-side scripting languages
available. It is used to retrieve and generate content for dynamic pages.
Languages used in server scripting are Ruby, PHP, ASP.NET, ADOBE
COLDFUSION etc.
PHP PROGRAMMING
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php
?>
UNIT III S.A
</body>
</html>
Hello, World!
PHP Editors
Text editors and IDE’s are used to code PHP SCRIPT. It is saved using the
extension .php.
Notepad++
Eclipse
Geany
PHP Coder
Netbeans IDE
Basic PHP Syntax (Canonical PHP tags): A PHP script can be placed
anywhere in the document. A PHP script starts with <?php and ends with ?>:
<?php
?>
</script>
UNIT III S.A
Short tags (Short-open (SGML-style) tags): Short or short-open tags look like
this −
<?
?>
php.ini
short_open_tag = on
ASP-style tags
ASP-style tags mimic the tags used by Active Server Pages to delineate code
blocks. ASP style tags look like this –
<%...%>
To use ASP-style tags, you will need to set the configuration option in your
php.ini file.
asp_tags = 0n
We can also insert PHP in HTML by putting it in a separate file and calling
them using include and require constructs.
The include or require statement takes all the text/code/markup that exists in the
specified file and copies it into the file that uses the include statement.
Including files is very useful when you want to include the same PHP,
HTML,or text on multiple pages of a website.
UNIT III S.A
include(“filename”);
require(“filename”);
or
include ‘filename’;
require ‘filename’;
It is possible to insert the content of one PHP file into another PHP file (before
the server executes it), with the include or require statement.
The include and require statements are identical, except upon failure:
Web server send request to PHP parser which is built in the web server.
Parser executes the php code and places the result in the file.
A comment is the portion of a program that exists only for the human reader.
PHP engine ignores a comment. There are two commenting formats in PHP −
Single-line comments − they are generally used for short explanations or notes
relevant to the local code. Here are the examples of single line comments.
<?php
# This is a comment, and
// This is a comment too. Each style comments only
print "An example with single line comments";
?>
<?php
/* This is a comment with multiline
Author : Mohammad Mohtashim
Purpose: Multiline Comments Demo
Subject: PHP
*/
print "An example with multi line comments";
?>
Php Is Whitespace Insensitive
PHP whitespace is insensitive means that it almost never matters how many
whitespace characters you have in a row.
UNIT III S.A
Variable capital is 67
Variable CaPiTaL is
<?php
?>
UNIT III S.A
PHP - VARIABLE
Here are the most important things to know about variables in PHP.
are assigned with the = operator, with the variable on the left-hand
side and the expression to be evaluated on the right.
when necessary.
PHP data types are used to hold different types of data or values. PHP supports
8 primitive data types that can be categorized further in 3 types:
It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string
1. array
2. object
1. Resource
2. NULL
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.
Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
?>
Output:
Decimal number: 34
HexaDecimal number: 69
PHP Float
Example:
<?php
$n1 = 19.34;
$n2 = 54.472;
?>
Output:
PHP String
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";
echo "</br>";
?>
Output:
Hello Javatpoint
Hello $company
PHP Boolean
They have only two possible values either true or false. PHP provides a couple
of constants especially for use as Booleans: TRUE and FALSE, which can be
used like so −
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
<?php
$x = true;
$y =false;
var_dump($x);
?>
PHP Array
An array is a compound data type. It can store multiple values of same data type
in a single variable.
UNIT III S.A
Example:
<?php
echo "</br>";
?>
Output:
Array Element2: C
PHP Object
Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared. An object is a data type that stores
data and also information about how to process that data. An object is a specific
instance of a class. Objects are created based on this template via the new
keyword.
Every object has properties and methods corresponding to those of its parent
class. Every object instance is completely independent, with its own properties
and methods
First we must declare a class of object. For this, we use the class keyword. A
class is a structure that can contain properties and methods:
UNIT III S.A
<?php
class Color
// create an object
var_dump($blue);
?>
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
var_dump($handle);
echo "<br>";
?>
PHP Null
Null is a special data type that has only one value: NULL. There is a convention
of writing it in capital letters. It represents empty variable in PHP. It does not
mean blank space or zero.
The special type of data type NULL defined a variable with no predefined
value.
It has been assigned NULL specifically.
It has been erased using unset().
UNIT III S.A
Example:
<?php
$nl = NULL;
?>
Eg: Whenever performing arithmetic operations on different data types PHP try
to converts string type to integer first.
<?php
$var2 =10;
echo $sum;
?>
Type casting
The process of explicitly converting values from one data type to another is
called type casting or explicit conversion. PHP’s cast types are:
<?php
$foo = 10; // $foo is an integer
$bar = (bool) $foo; // $bar is a boolean
?>
Defined constants
example:
define(“PI”, 3.141592);
echo PI;
<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
UNIT III S.A
constant() function
As indicated by the name, this function will return the value of the constant.
<?php
define("MINSIZE", “HELLO”);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (boolean, integer, float and string) can be contained in
constants.
1 LINE
The current line number of the file.
UNIT III S.A
2 FILE
The full path and filename of the file.
3 FUNCTION
The function name.
4 CLASS
The class name.
5 METHOD
The class method name.
o echo
o print
echo and print are language constructs, and they never behave like a function.
Therefore, there is no requirement for parentheses. However, both the
statements can be used with or without parentheses. We can use these
statements to output variables or strings.
echo
o echo is a language construct, which is used to display the output.
o echo can be used with or without parentheses.
o echo does not return any value.
o We can pass multiple strings separated by comma (,) in echo.
o echo is marginally faster than print statement.
UNIT III S.A
print
o print is also a language construct, 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.
Echo statement
The echo statement is a language construct that can output one or more strings.
It can output any values such as number, variables, strings etc.
Display Variables
The following example will show you how to display variable using the echo
statement:
<?php
$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");
UNIT III S.A
// Displaying variables
echo $txt;
echo "<br>";
echo $num;
echo "<br>";
echo $colors[0];
?>
The output of the above PHP code will look something like this:
Hello World!
123456789
Red
Both echo and print statement works exactly the same way except that the print
statement can only output one string, and always returns 1. That's why the
echo statement considered marginally faster than the print statement since it
doesn't return any value.
Print accepts only one argument.
<?php
$var=”hello”
print $var;
?>
UNIT III S.A
VARIABLE SCOPE
The scope of a variable is defined as the range in the program under which it
can be accessed. In other words, "The scope of a variable is the portion of the
program within which the variable is defined and can be accessed." A variable
can be declared anywhere in the PHP script.
Local variable
Function parameter
Global variable
Static Variable
When a variable is accessed outside its scope it will cause PHP error Undefined
Variable.
Here we have declared a variable $count inside this function. This variable is
said to be a local variable of this function and it is in the local scope of the
function block.
<?php
function calculate_count() {
$count = 5;
echo $count++;
?>
UNIT III S.A
Local variables will be destroyed once the end of the code block is reached.
Hence the same named variables can be declared within different local scopes.
The global scope provides widespread access to the variable declared in this
scope. Variables in global scope can be accessed from anywhere in the program.
i.e from outside a function or class independent of its boundary.
PHP global variables can be defined by using global keyword. If we want to use
global variables inside a function, we have to prefix the global keyword with the
variable. The following code shows a code block to learn how to use the global
keyword with a PHP variable to declared it as a global variable.
<?php
$count = 0;
function calculate_count()
global $count;
calculate_count();
echo $count;
?>
A static variable is a variable with local scope. But it is not destroyed outside
the scope boundary. A variable can be defined by using the ‘static’ keyword
inside a function.
UNIT III S.A
A static variable does not lose its value when the program execution goes past
the scope boundary. But it can be accessed only within that boundary. Let me
demonstrate it using the following example code,
<?php
function counter()
static $count = 0;
echo $count;
$count++;
?>
The above counter function has the static variable ‘count’ declared within its
local scope. When the function execution is complete, the static count variable
still retains its value for further computation.
Function parameters (arguments) are local variables defined within the local
scope of the function on which it is used as the argument.
Function parameters are declared after the function name and inside
parentheses. They are declared much like a typical variable would be −
<?php
$x=10;
print "value outside function $x \n";
function multiply ($x)
{
$x = $x * 10;
Print "value inside function $x \n";
}
UNIT III S.A
multiply($x);
print "value outside function $x \n";
?>
This will produce the following result −
value outside function 10
PREDEFINED VARIABLES
Predefined variables are accessible from anywhere within the PHP script,
regardless of scope. This gives information about user session, users operating
environment etc. Some of the predefined variables are called super globals,
which means they are present and available anywhere in the script.
PHP SUPERGLOBALS
1 $GLOBALS
This array contains a reference to every variable which is currently available within
the global scope of the script.
2
$_SERVER
This is an array containing information such as headers, paths, and script locations.
The entries in this array are created by the web server.
3 $_GET
UNIT III S.A
An associative array of variables passed to the current script via the HTTP GET
method.
4
$_POST
An associative array of variables passed to the current script via the HTTP POST
method.
5
$_FILES
An associative array of items uploaded to the current script via the HTTP POST
method.
6
$_COOKIE
An associative array of variables passed to the current script via HTTP cookies.
7 $_SESSION
An associative array containing session variables available to the current script.
PHP OPERATORS
Arithmetic operators
Assignment operators
Comparison operators (Relational operators)
Increment/Decrement operators
Logical operators
Bitwise operators
String operators
Conditional assignment operators
UNIT III S.A
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 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.
UNIT III S.A
The PHP comparison operators are used to compare two values (number or
string):
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.
UNIT III S.A
PHP has two operators that are specially designed for strings.
The PHP conditional assignment operators are used to set a value depending on
conditions:
Sequential – this one involves executing all the codes in the order in
which they have been written.
Decision – this one involves making a choice from a number of options.
The code executed depends on the value of the condition.
Syntax
if (condition) {
}
UNIT III S.A
Example
<html>
<body>
<?php
$a = 100;
$b = 20;
if ($a>$b)
echo "$a is the larger number” ;
?>
</body>
</html>
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
<html>
<body>
<?php
$a = 100;
$b = 200;
UNIT III S.A
if ($a>$b)
echo "$a is the larger number” ;
else
echo "$b is larger number";
?>
</body>
</html>
Syntax
if (condition1)
code to be executed if condition1 is true;
elseif (condition2)
code to be executed if condition2 is true;
elseif(condition3)
code to be executed if condition3 is true;
else
code to be executed if all other conditions are false;
<html>
<body>
<?php
$d = date("D");
if ($d == "Fri")
echo "Have a nice weekend!";
</body>
</html>
It will produce the following result −
Have a nice day!
It only executes a single block of code depending on the value of the condition.
The switch statement selects one of many blocks of code to be executed. It is a
multiple case selection statement.
If no condition has been met then the default block of code is executed.
Syntax
switch (expression )
{
case value: statement1;
break;
Example
<html>
<body>
<?php
$d = date("D");
switch ($d)
{
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
UNIT III S.A
default:
echo "Default value”;
}
?>
</body>
</html>
It will produce the following result −
Today is Tuesday
The for loop, loops through a block of code a specified number of times. It
repeats the block of code until a certain condition is met.
Syntax
for (initialization; condition; increment/derement)
{
code to be executed;
}
UNIT III S.A
The initializer is used to set the start value for the counter of loop iterations. A
variable may be declared here for this purpose and it is traditional to name it $i.
Initialisation only happens once.
Example
<!DOCTYPE html>
<html>
<body>
<?php
for ($i = 0; $i <= 10; $i++)
{
echo "The number is: $i <br>";
}
?>
</body>
</html>
This will produce the following result −
The while statement will execute a block of code as long as a test expression is
true.
If the test expression is true then the code block will be executed. After the
code has executed the test expression will again be evaluated and the loop will
continue until the test expression is found to be false.
Syntax
while (condition)
{
code to be executed;
}
Example
<?php
$x = 1;
while($x <= 5)
{
echo "The number is: $x <br>";
UNIT III S.A
The do...while statement will execute a block of code at least once - it then
will repeat the loop as long as a condition is true.
Syntax
do
{
code to be executed;
}
while (condition);
Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = 1;
do
{
echo "The number is: $x <br>";
UNIT III S.A
$x++;
} while ($x <= 5);
?>
</body>
</html>
The foreach statement is used to loop through arrays. For each pass, the value
of the current array element is assigned to $value and the array pointer is
moved by one and in the next pass next element will be processed.
Syntax
foreach (array as $value)
{
code to be executed;
}
Example
Try out following example to list out the values of an array.
<html>
<body>
<?php
$array1 = array( 1, 2, 3, 4, 5);
UNIT III S.A
JUMP STATEMENTS
The PHP break keyword is used to terminate the execution of a loop before it
ends. It is a jump statement.
The break statement is situated inside the statement block. It gives you full
control and whenever you want to exit from the loop you can come out. After
coming out of a loop the immediate statement after the loop will be executed.
UNIT III S.A
Example
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x < 10; $x++)
{
if ($x == 4)
{
break;
}
echo "The number is: $x <br>";
}
?>
</body>
</html>
This will produce the following result –
The break statement can be used to jump out of a loop.
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The PHP continue keyword is used to halt the current iteration of a loop but it
does not terminate the loop. Continue statement is also termed as jump
statement.
Just like the break statement the continue statement is situated inside the
statement block. For the pass encountering continue statement, rest of the loop
code is skipped and next pass starts.
UNIT III S.A
Example
<!DOCTYPE html>
<html>
<body>
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
</body>
</html>
This will produce the following result −
The number is: 0
PHP has over 1000 built-in functions that can be called directly, from within a
script, to perform a specific task. Besides the built-in PHP functions, it is
possible to create user defined functions.
Example:
<?php
//function definition
function sayHello()
//function call
sayHello();
?>
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When the
familyName() function is called, we also pass name value to the function and
the name is used inside the function.
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname) {
}
UNIT III S.A
familyName("Jane");
familyName("Alan");
?>
</body>
</html>
Following example takes two integer parameters and add them together and
then print them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
UNIT III S.A
We can specify a default value for parameters in function. While calling PHP
function if you don't specify any argument, it will take the default argument.
Let's see a simple example of using default argument value in PHP function.
<?php
function sayHello($name="Aravi")
{
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello(); //passing no value
sayHello("John");
?>
Output:
Hello Rajesh
Hello Aravi
Hello John
A function can return a value back to the script that called the function using the
return statement. The value may be of any type, including arrays and objects.
<?php
// Defining function
function getSum($num1, $num2)
{
$total = $num1 + $num2;
return $total;
}
The return keyword is used to return value back to the part of program,
from where it was called. The returning value may be of any type including
the arrays and objects. Normally a function cannot return multiple values. But
the similar result can be obtained using arrays.
<?php
?>
In PHP there are two ways you can pass arguments to a function: by
value and by reference. By default, function arguments are passed by value so
that if the value of the argument within the function is changed, it does not get
affected outside of the function.
Pass by Value: On passing arguments using pass by value, the value of the
argument gets changed within a function, but the original value outside the
function remains unchanged. That means a copy of the original value is
passed as an argument.
Pass by Reference: On passing arguments as pass by reference, the
original value is passed. Therefore, the original value gets altered. In pass
by reference we actually pass the address of the value, where it is stored
using ampersand sign(&)
UNIT III S.A
<!DOCTYPE html>
<html>
<body>
<?php
function add_five(&$value) {
$value += 5;
echo "$value" ."<br>";
}
$num = 2;
add_five($num);
echo $num;
?>
</body>
</html>
In PHP, arguments are usually passed by value, which means that a copy of the
value is used in the function and the variable that was passed into the function
cannot be changed.