PHP Web Devlopenment Usingopensource
PHP Web Devlopenment Usingopensource
1. Website
Website is a collection of related WebPages and media content which can be accessed through network.
In WAN websites can be accessed using internet protocols (IP) and in LAN Websites can be accessed
using URL-uniform resource locator.
Functions of website
Main function of website is to provide particular information using network and internet
worldwide. Various types of information can be provided worldwide users by website, like textual
information, graphical information and some information like audio and video. Now a day’s complex map
and rout information are also available over the internet.
Examples of websites
Informative websites
a. www.Yahoo.com
b. www.msn.com
c. www.rediffmail.com
a. www.google.com
b. www.bing.com
c. www.ask.com
Ecommerce websites
a. www.amazon.com
b. www.flipkart.com
c. www.uber.com
a. https://ojas.gujarat.gov.in
b. www.monsterjob.com
c. www.jobs.com
Government websites
a. www.Incometaxindiaefiling.com
b. www.Uidai.gov.in
c. www.Digitalgujarat.gov.in
Now a day’s companies and individuals also have their websites to deliver information using this
technology.
Example
1. HTML
2. CSS
3. Javascript
4. Introduction to PHP
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source
general-purpose scripting language. It is especially suited for web development and can be
embedded into HTML
PHP code is executed on the server, generating HTML which is then sent to the client. The
client would receive the results of running that script, but would not know the PHP code.
PHP is a server side scripting language; server side scripting language is one, which has the
capability of executing the script on the server and serving the output as a HTML File, server
side script has the main advantage of interacting with the databases and to perform all types
of server manipulations directly. Server side scripting language is responsible for
manipulating the data which is filled in the entire web forms, anywhere in the net
PHP sits between your browser and the web server. When you type in the URL of a PHP website
in your browser, your browser sends out a request to the web server. The web server then calls
the PHP script on that page. The PHP module executes the script, which then sends out the result
in the form of HTML back to your browser, which you see on the screen. Here is a basic php
diagram which illustrates the process.
Features of PHP
PHP is cross-platform. It can be run on Windows, Linux, BSD, Mac OS X, and Solaris,
as well as a variety of other platforms.
PHP is free. You can download the source code, use it, and even make changes to it
without ever having to pay any licensing costs. You can even give away your own
modified version of PHP. Note to critics: just because PHP is free, it doesn't mean you
need to give your scripts away for free.
PHP is fast. In the majority of scripts beyond basic benchmarks, PHP will easily compete
with both Perl and Python, and usually match Microsoft's ASP.NET. Add to that the fact
that PHP code can be cached for execution, and PHP's performance is first-class.
PHP is capable. There are thousands of pre-written functions to perform a wide variety of
helpful tasks - handling databases of all sorts (MySQL, Oracle, MS SQL, PostgreSQL,
and many others), file uploads, FTP, email, graphical interfaces, generating Flash movies,
and more.
PHP is extendable. Writing your own extension to PHP is a common and easy way to
implement speed-critical functionality, and PHP's extension API is a particularly rich and
flexible system.
PHP is reliable. It already runs on millions of servers around the world, which means it is
mature enough for even the most demanding of situations.
PHP is easy to debug. There are a number of debuggers, both commercial and freeware,
that make debugging PHP a snap.
Example
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<?php
echo "Hi, I'm a PHP script!";
?>
</body>
</html>
Advantages of PHP
5. They depend entirely on Browsers. Wide variations 5. They do not depends entirely on
exist in capability of each browsers, some people browsers.
disable JavaScript for security reasons.
System requirement
For php 5.6 and above, windows 8 32 bit or 64 bit is needed and VC runtime 2011 from
Microsoft or updated is needed.
Go to the official WAMP server website (http://www.wampserver.com/en/) and download the WampServer setup
according to your Windows 10 version. If you have 64bit then download the Wamp server (x64) otherwise the 32-bit
(X86). To check your Windows 10 version right click on “This PC” and select the properties.
As I said it needs up to date redistributable packages of VC9, VC10, VC13, VC14, and Vc15. Either go to your Control
Panel-> Program and features and check whether you have the Visual C++ packages installed or not, or just Click on
the Next button and program will automatically identify it. In case, the program not able to find the packages, it will warn
you and then you can install them from below given links:
1. Visual C++ Redistributable for Visual Studio 2015
2. Visual C++ Redistributable Packages for Visual Studio 2013
3. Visual C++ Redistributable for Visual Studio 2012 Update 4
4. Microsoft Visual C++ 2010 Redistributable Package (x64)
5. Microsoft Visual C++ 2010 Redistributable Package (x86)
6. Microsoft Visual C++ 2010 SP1 Redistributable Package (x86)
7. Microsoft Visual C++ 2010 SP1 Redistributable Package (x64)
Step 5: Change the Internet Explorer Browser and Text editor of WAMP server on Windows
10
While installing the setup of WampServer, it will ask which browser you want as default in the WAMP server. By default,
it uses the iexplore.exe (Internet Explorer) to change it to Google Chrome or Mozilla Firefox click on YES otherwise NO.
When you click on YES, the Windows Explorer will open from where go to C:Program Files
(x86)GoogleChromeApplication and select the Chrome.exe and click on Open.
After selecting the default browser, the Wamp Server will also ask to select the default Text editor which we need in case
we want to edit Apache or PHP config files such as http.config or php.ini. By default, it uses the notepad of Windows, I
think it doesn’t need to be changed, so that’s why just click on NO. However, if you want to change the Text editor then
click on YES and locate your third-party installed text editor as we do above for selecting the Google chrome.
While completing the installation the setup also provides you login information of your phpMyAdmin; “After Installing
Wampserver the default username is “root” without quotes and there is no password, which means you must leave
Password box empty to login into the phpMyAdmin.
To ensure whether our Apache web server is up and running on our Windows 10 click on Localhost.
When you click on Localhost a tab will open with a page showing all server configuration in your browser. For reference
see the screenshot.
If you want to know which port is using which service of WAMP server or some other information, you just need to go
tools:
Restart DNS
Check HTTP.conf syntax
Check stats of services
Check DNS search order
Check compiler VC, compatibility and ini files
Show VirtualHost examined by Apache
Show Apache loaded Modules
Delete Unused PHP versions
And more…
<?php
Statement 1;
Statement 2;
Statement 3;
?> or it can omit ‘ ; ‘ from last statement like
<?php
Statement 1;
Statement 2;
Statement 3
?>
Example.
<html>
<head>
<title>embedding php with html</title>
</head>
<body>
<p><b> Hello how are you
<?php echo “<u> $username </u>”; ?>
</b></p>
</body>
</html>
9. Variables in PHP
Variables in PHP are defined by placing ‘$’ sign before variable name. This PHP
parser and interpreter considers all other character as a string but when it finds ‘$’
sign before any character, it considers that as a variable.
In PHP, a variable does not need to be declared before adding a value to it.
In the example above, you see that you do not have to tell PHP which data type the
variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In a strongly typed programming language, you have to declare (define) the type and
name of the variable before using it.
In PHP, the variable is declared automatically when you use it.
1.$varname=value;
2. settypy($varname,datatype) – to set variable or to convert variable’s datatype
Example
<?php
$a=10; //setting integer variable $a
?>
1. Integers
Integers are whole numbers, like 1, 12, and 256. The range of acceptable values varies according
to the details of your platform but typically extends from -2,147,483,648 to +2,147,483,647.
Specifically, the range is equivalent to the range of the long data type of your C compiler.
Unfortunately, the C standard doesn't specify what range that long type should have, so on some
systems you might see a different integer range.
Integer literals can be written in decimal, octal, or hexadecimal. Decimal values are represented
by a sequence of digits, without leading zeros. The sequence may begin with a plus ( +) or minus
(-) sign. If there is no sign, positive is assumed. Examples of decimal integers include the
following:
1998
-641
+33
Octal numbers consist of a leading 0 and a sequence of digits from 0 to 7. Like decimal numbers,
octal numbers can be prefixed with a plus or minus. Here are some example octal values and
their equivalent decimal values:
0755 // decimal 493
+010 // decimal 8
Hexadecimal values begin with 0x, followed by a sequence of digits (0-9) or letters (A-F). The
letters can be upper- or lowercase but are usually written in capitals. Like decimal and octal
values, you can include a sign in hexadecimal numbers:
0xFF // decimal 255
0x10 // decimal 16
-0xDAD1 // decimal -56017
If you try to store a too-large integer in a variable, it will automatically be turned into a floating-
point number.
Use the is_int( ) function (or its is_integer( ) alias) to test whether a value is an integer:
if (is_int($x)) {
// $x is an integer
}
2. Floating-Point Numbers
Floating-point numbers (often referred to as real numbers) represent numeric values with
decimal digits. Like integers, their limits depend on your machine's details. PHP floating-point
numbers are equivalent to the range of the double data type of your C compiler. Usually, this
allows numbers between 1.7E-308 and 1.7E+308 with 15 digits of accuracy.
PHP recognizes floating-point numbers written in two different formats. There's the one we all
use every day:
3.14
0.017
-7.1
The read format of double is –x.y where – is optionally for negative number and x and y are
sequence of number between 0 to 9.
3. Booleans
A boolean value represents a "truth value"—it says whether something is true or not. Like most
programming languages, PHP defines some values as true and others as false. Truth and
falseness determine the outcome of conditional code such as:
if ($alive) { ... }
4. NULL
There's only one value of the NULL data type. That value is available through the case-
insensitive keyword NULL. The NULL value represents a variable that has no value.
$aleph = "beta";
$aleph = null; // variable's value is gone
$aleph = Null; // same
$aleph = NULL; // same
Use the is_null( ) function to test whether a value is NULL—for instance, to see whether a variable
has a value:
if (is_null($x)) {
// $x is NULL
}
5. Strings
Because strings are so common in web applications, PHP includes core-level support for creating
and manipulating strings. A string is a sequence of characters of arbitrary length. String literals
are delimited by either single or double quotes:
'big dog'
"fat hog"
Variables are expanded within double quotes, while within single quotes they are not:
$name = "Guido";
echo "Hi, $name\n";
echo 'Hi, $name';
Hi, Guido
Hi, $name
\n Newline
\r Carriage return
\t Tab
\\ Backslash
\$ Dollar sign
\{ Left brace
\} Right brace
\[ Left bracket
\] Right bracket
A single-quoted string only recognizes \\ to get a literal backslash and \' to get a literal single
quote:
$dos_path = 'C:\\WINDOWS\\SYSTEM';
$publisher = 'Tim O\'Reilly';
echo "$dos_path $publisher\n";
C:\WINDOWS\SYSTEM Tim O'Reilly
To test whether two strings are equal, use the == comparison operator:
if ($a == $b) { echo "a and b are equal" }
6. Arrays
An array holds a group of values, which you can identify by position (a number, with zero being
the first position) or some identifying name (a string):
$person[0] = "Edison";
$person[1] = "Wankel";
$person[2] = "Crapper";
There are several ways to loop across arrays, but the most common is a foreach loop:
<?php
foreach ($person as $name) {
echo "Hello, $name\n";
}
foreach ($creator as $invention => $inventor) {
echo "$inventor created the $invention\n";
}
?>
Hello, Edison
Hello, Wankel
Hello, Crapper
Edison created the Light bulb
Wankel created the Rotary Engine
Crapper created the Toilet
You can sort the elements of an array with the various sort functions:
sort($person);
// $person is now array('Crapper', 'Edison', 'Wankel')
asort($creator);
// $creator is now array('Toilet' => 'Crapper',
// 'Light bulb' => 'Edison',
// 'Rotary Engine' => 'Wankel');
There are functions for returning the number of items in the array, fetching every value in the
array, and much more. Arrays are described in Chapter 5.
7. Objects
PHP supports object-oriented programming (OOP). OOP promotes clean modular design,
simplifies debugging and maintenance, and assists with code reuse.
Classes are the unit of object-oriented design. A class is a definition of a structure that contains
properties (variables) and methods (functions). Classes are defined with the class keyword:
class Person {
var $name = '';
Once a class is defined, any number of objects can be made from it with the new keyword, and
the properties and methods can be accessed with the -> construct:
$ed = new Person;
$ed->name('Edison');
printf("Hello, %s\n", $ed->name);
$tc = new Person;
$tc->name('Crapper');
printf("Look out below %s\n", $tc->name);
Hello, Edison
Look out below Crapper
8. Resources
Many modules provide several functions for dealing with the outside world. For example, every
database extension has at least a function to connect to the database, a function to send a query to
the database, and a function to close the connection to the database. Because you can have
multiple database connections open at once, the connect function gives you something by which
to identify that connection when you call the query and close functions: a resource.
Resources are really integers under the surface. Their main benefit is that they're garbage
collected when no longer in use. When the last reference to a resource value goes away, the
extension that created the resource is called to free any memory, close any connection, etc. for
that resource:
The benefit of this automatic cleanup is best seen within functions, when the resource is assigned
to a local variable. When the function ends, the variable's value is reclaimed by PHP:
function search ( ) {
$res = database_connect( );
$database_query($res);
}
static variables
static variables in php are declared using ‘static’ keyword before variable name.
for example
function foo() {
static $index = 0;
$index++;
echo "$index\n";
constant variable
Syntax
Parameters:
case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
?>
Global variables
The scope of a variable is the context within which it is defined. For the most part all PHP
variables only have a single scope. This single scope spans included and required files as well.
For example:
<?php
$a = 1;
include 'b.inc';
?>
Here the $a variable will be available within the included b.inc script. However, within user-
defined functions a local function scope is introduced. Any variable used inside a function is by
default limited to the local function scope. For example:
<?php
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
?>
This script will not produce any output because the echo statement refers to a local version of
the $a variable, and it has not been assigned a value within this scope. You may notice that this is
a little bit different from the C language in that global variables in C are automatically available
to functions unless specifically overridden by a local definition. This can cause some problems in
that people may inadvertently change a global variable. In PHP global variables must be declared
global inside a function if they are going to be used in that function.
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
The above script will output 3. By declaring $a and $b global within the function, all references
to either variable will refer to the global version. There is no limit to the number of global
variables that can be manipulated by a function.
A second way to access variables from the global scope is to use the special PHP-
defined $GLOBALS array. The previous example can be rewritten as:
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo $b;
?>
The $GLOBALS array is an associative array with the name of the global variable being the key
and the contents of that variable being the value of the array element. Notice
how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. Here's an
example demonstrating the power of superglobals:
<?php
function test_superglobal()
{
echo $_POST['name'];
}
?>
PHP Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
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.
x += y x=x+y Addition
x -= y x=x-y Subtraction
x *= y x=x*y Multiplication
x /= y x=x/y Division
x %= y x=x%y Modulus
or Or $x or $y True if either $x or $y is
true
|| Or $x || $y True if either $x or $y is
true
FALSE
Conditional Statements
Conditional Statements allow you to branch the path of execution in a script based on whether a
single, or multiple conditions, evaluate to true or false. Put simply, they let you test things and
perform various actions based on the results.
If Statements
<?php
$x=1;
This example illustrates the simplest kind of If Statement. If Statements always begin with "if",
followed by a condition surrounded in parentheses. If the condition evaluates to true, then the
statement or statements immediately following the condition will be executed. In this case, had
the condition been false, nothing would have occurred and you would have seen a blank browser
<?php
$x=1;
if ($x == 1) {
print '$x is equal to 1';
$x++;
print 'now $x is equal to 2';
}
?>
Keep in mind that the positioning of the elements does not affect the execution of the script. All
of the example arrangements below are perfectly valid not only for If Statements, but for every
form of control loop.
if ($x == 1)
print '$x is equal to 1';
if ($x == 1) {
print '$x is equal to 1';
}
In the interests of clarity, many programmers opt to use indenting and brackets even on one-line
blocks of code; however, it is ultimately a matter of personal coding preference.
You can also include multiple conditions within parentheses. For the nested statements to
execute, all of the conditions must evaluate to true.
<?php
$x=1;
Else Statements
As the name implies, Else Statements allow you to do something else if the condition within an
If Statement evaluated to false:
<?php
$x=1;
if ($x == 2) {
print '$x is equal to 2';
} else {
print '$x is equal to 1';
}
?>
Else If Statements
Thus far, we have been able to respond to one condition, and do something if that condition is
not true. But what about evaluating multiple conditions? You could use a series of If Statements
to test each potential condition, but in some situations that is not a suitable option. Here is where
Else If Statements come in.
A combination of If and Else Statements, Else If Statements are evaluated sequentially if the
condition within the If Statement is false. When a condition within an Else If Statement evaluates
to true, the nested statements are parsed, the script stops executing the entire If/Else if/Else
Structure. The rest of the script proceeds to be parsed.
<?php
$x=1;
if ($x == 2) {
print '$x is equal to 2';
} else if ($x == 1) {
print '$x is equal to 1';
} else {
print '$x does not equal 2 or 1';
}
?>
The final else statement can be left off if you do not want anything to happen if none of the If or
Else If Statements are true:
<?php
$x=0;
if ($x == 2) {
print '$x is equal to 2';
} else if ($x == 1) {
print '$x is equal to 1';
}
?>
In this case, since neither the condition within the If or Else if Conditions are true, and no Else
Statement was provided, nothing would be outputted to the browser.
Switches
Switches are a good alternative to If/Else if/Else Statements in situations where you want to
check multiple values against a single variable or condition. This is the basic syntax:
<?php
$var = "yes";
switch ($var) {
case "yes":
print '$var is equal to yes';
break;
case "no":
print '$var is equal to no';
break;
}
?>
After running this code snippet, much of what is here will probably make sense to you. In the
first line of the switch statement, we have the identifier "switch" followed by a variable
surrounded by parenthesis. Each case includes a possible value for the variable.
Switches execute a little differently than If/Else if/Else statements. Once a case value matches
the value of the switch expression, every following statement is executed, including those
following other cases.
To prevent this from happening, a break statement is used. "Break;" ends the execution of the
switch statement, and lets the script continue execution; it can also be used in while or for loops.
Optionally, you may also include a special case called "default". This case works much like and
Else Statement, and will execute if all the other cases are found to be false. This case should be
the very last one you include.
<?php
$var = "yes";
switch ($var) {
case "maybe":
print '$var is equal to yes';
break;
case "no":
print '$var is equal to no';
break;
default:
print 'none of the other two cases were true, so this sentance will be
printed out instead.';
}
?>
Similar to the Break Statement is the Exit Statement. Exit is particularly useful in situations
where you run into what would be considered a "fatal error" (for example, if the user had entered
a password that was incorrect) or any other time you needed to end the execution of a script
before it naturally terminated.
<?php
$var = "yes";
switch ($var) {
case "yes":
print '$var is equal to yes';
exit;
case "no":
print '$var is equal to no';
break;
}
print "this will not be printed, because the script will have terminate before
this line is reached";
?>
Unlike break, exit may be used anywhere in your scripts, inside \or outside of control structures.
The Ternary Operator
Though Technically an Operator, not a Control Structure, the Ternary Operator, represented by
"?", can be used as shorthand for simple If/Else Statements. It can only be used in situations
where you want execute a single expression based on whether a single condition is true or false:
<?php
$x = 1;
($x==1) ? (print '$x is equal to 1') : (print '$x is not equal to 1');
?>
The condition is contained within the first set of parentheses. If it evaluates to true, then the
expression within the second set of parentheses will be performed. Otherwise, the expression in
the third set will be performed:
You will see how this can be particular useful a little later on.
Control Loops
Frequently in PHP there are instances where you need to perform repetitive tasks, such as
formatting data pulled from a database, sending out emails to a mailing list, or cycling through
the contents of an array. Control Loops allow you to perform these tasks almost effortlessly.
While Loops
<?php
$x=1;
When you run this snippet, you will see the numbers 1 through 10 printed on your screen. Take a
look at the code. In many ways, it's very similar to an If Statement. First is the while identifier,
followed by a condition surrounded by parentheses.
The statements nested within the loop will execute as long as the condition within the
parentheses evaluates to true. Since the validity of the condition is checked before the loop is
executed, if the condition is false, then the statements within the loop will not be executed at all.
Do...While Loops
Do...While Loops are close cousins of While Loops:
<?php
$x=11;
do {
print "$x<br>";
$x++;
} while ($x <=10);?>
The primary difference in how these work is that the validity of the condition in a Do...While
Loop is tested after the loop has itinerated once. This means that in the example above, $x would
be printed out one time, and then the execution of the loop would end, because $x is greater than
10.
For Loops
<?php
for($x=1; $x<=10; $x++) {
print "$x<br>";
}
?>
foreach
This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue
an error when you try to use it on a variable with a different data type or an uninitialized
variable. There are two syntaxes; the second is a minor but useful extension of the first:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
The first form loops over the array given by array_expression. On each loop, the value of the
current element is assigned to $value and the internal array pointer is advanced by one (so on the
next loop, you'll be looking at the next element).
The second form does the same thing, except that the current element's key will be assigned to
the variable $key on each loop.
<?php
/* foreach example value only */
$a = array(1, 2, 3, 17);
break
break ends execution of the current for, foreach, while, do-while or switch structure.
<?php
switch ($i) {
case "apple":
echo "i is apple";
break;
case "bar":
continue
continue is used within looping structures to skip the rest of the current loop iteration and
continue execution at the condition evaluation and then the beginning of the next iteration.
<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue;
print "$i\n"; }
?>
OUTPUT IS
0134
Syntax
function functionName() {
code to be executed;
}
Example
<?php
function writeMsg() {
echo "Hello world!";
}
Information can be passed to functions through arguments. An argument is just like a variable.
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 along a name (e.g. Jani), and the name is used inside the function,
which outputs several different first names, but an equal last name:
Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
The following example shows how to use a default parameter. If we call the function setHeight()
without arguments it takes the default value as argument:
Example
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Example
PHP supports variable length argument function. It means you can pass 0, 1 or n number of
arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name.
The 3 dot concept is implemented for variable length argument since PHP 5.6.
<?php
function add(...$numbers) {
$sum = 0;
$sum += $n;
return $sum;
?>
Variable functions
PHP supports the concept of variable functions. This means that if a variable name has
parentheses appended to it, PHP will look for a function with the same name as whatever the
variable evaluates to, and will attempt to execute it. Among other things, this can be used to
implement callbacks, function tables, and so forth.
<?php
function foo() {
echo "In foo()<br />\n";
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
?>
Object methods can also be called with the variable functions syntax.
<?php
class Foo
{
function Variable()
{
$name = 'Bar';
function Bar()
{
echo "This is Bar";
}
}
$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // This calls $foo->Variable()
?>
<?php
$a=$user;
return $a;
} };
print_r ($ar);
?>
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
This chapter will explain some of the superglobals, and the rest will be explained in later
chapters.
$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;
?>
$_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['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
$_REQUEST
The example below shows a form with an input field and a submit button. When a user submits
the data by clicking on "Submit", the form data is sent to the file specified in the action attribute
of the <form> tag. In this example, we point to this file itself for processing form data. If you
wish to use another PHP file to process form data, replace that with the filename of your choice.
Then, we can use the super global variable $_REQUEST to collect the value of the input field:
Example
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
$_POST
PHP $_POST is widely used to collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.
The example below shows a form with an input field and a submit button. When a user submits
the data by clicking on "Submit", the form data is sent to the file specified in the action attribute
of the <form> tag. In this example, we point to the file itself for processing form data. If you
wish to use another PHP file to process form data, replace that with the filename of your choice.
Then, we can use the super global variable $_POST to collect the value of the input field:
Example
<html>
<body>
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
$_GET
PHP $_GET can also be used to collect form data after submitting an HTML form with
method="get".
<html>
<body>
</body>
</html>
When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to
"test_get.php", and you can then access their values in "test_get.php" with $_GET.
Example
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>
GET POST
Restrictions on data length Yes, when sending data, the GET No restrictions
method adds the data to the URL;
and the length of a URL is limited
(maximum URL length is 2048
characters)
Restrictions on data type Only ASCII characters allowed No restrictions. Binary data is also
allowed
Security GET is less secure compared to POST is a little safer than GET
POST because data sent is part of because the parameters are not
the URL stored in browser history or in web
server logs
Never use GET when sending
passwords or other sensitive
information!
Visibility Data is visible to everyone in the Data is not displayed in the URL
URL
PHP Session
A session is a way to store information (in variables) to be used across multiple pages.
When you work with an application, you open it, do some changes, and then you close it. This is
much like a Session. The computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web server does not know who
you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple pages
(e.g. username, favorite color, etc). By default, session variables last until the user closes the
browser.
So; Session variables hold information about one single user, and are available to all pages in
one application.
Tip: If you need a permanent storage, you may want to store the data in a database.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Next, we create another page called "demo_session2.php". From this page, we will access the
session information we set on the first page ("demo_session1.php").
Notice that session variables are not passed individually to each new page, instead they are
retrieved from the session we open at the beginning of each page (session_start()).
Also notice that all session variable values are stored in the global $_SESSION variable:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>
Another way to show all the session variable values for a user session is to run the following
code:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
Syntax
Only the name parameter is required. All other parameters are optional.
The following example creates a cookie named "user" with the value "John Doe". The cookie
will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire
website (otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also
use the isset() function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
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>
To modify a cookie, just set (again) the cookie using the setcookie() function:
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<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, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
The following example creates a small script that checks whether cookies are enabled. First, try
to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
a. Variable functions
gettype()
You can use PHP4's built-in function gettype() to test the type of any variable. If you
place a variable between the parentheses of the function call, gettype() returns a
string representing the relevant type
Example
<html>
<head>
<title>Testing the type of a variable</title>
</head>
<body>
<?php
$testing = 5;
print gettype( $testing ); // integer
print "<br>";
$testing = "five";
print gettype( $testing ); // string
print("<br>");
$testing = 5.0;
print gettype( $testing ); // double
print("<br>");
$testing = true;
print gettype( $testing ); // boolean
print "<br>";
?>
</body>
</html>
settype()
PHP provides the function settype() to change the type of a variable. To use
settype(), you must place the variable to change (and the type to change it to)
between the parentheses and separated by commas
<html>
<head>
<title>Listing 4.5 Changing the type of a variable with settype()</title>
</head>
<body>
<?php
$undecided = 3.14;
print gettype( $undecided ); // double
print " -- $undecided<br>"; // 3.14
settype( $undecided, string );
print gettype( $undecided ); // string
print " -- $undecided<br>"; // 3.14
settype( $undecided, integer );
print gettype( $undecided ); // integer
Isset()
— Determine if a variable is declared and is different than NULL
Description
Determine if a variable is considered set, this means if a variable is declared and is different
than NULL.
If a variable has been unset with the unset () function, it is no longer considered to be set.
isset() will return FALSE when checking a variable that has been assigned to NULL. Also note
that a null character ("\0") is not equivalent to the PHP NULL constant.
If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are
considered set. Evaluation goes from left to right and stops as soon as an unset variable is
encountered.
Parameters
var
...
Return Values
Returns TRUE if var exists and has any value other than NULL. FALSE otherwise.
Example isset()
<?php
$var = '';
$a = "test";
$b = "anothertest";
var_dump(isset($a)); // TRUE
var_dump(isset($a, $b)); // TRUE
unset ($a);
var_dump(isset($a)); // FALSE
var_dump(isset($a, $b)); // FALSE
$foo = NULL;
var_dump(isset($foo)); // FALSE
?>
Strval()
(PHP 4, PHP 5, PHP 7)
Description
Get the string value of a variable. See the documentation on string for more information on
converting to string.
This function performs no formatting on the returned value. If you are looking for a way to
format a numeric value as a string, please see sprintf () or number_format().
Parameters
var
var may be any scalar type or an object that implements the __toString() method. You cannot
use strval() on arrays or on objects that do not implement the __toString() method.
Return Values
Examples
<?php
$var_name = 11.010;
echo strval ($var_name);
?>
Floatval()
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
Description
Parameters
var
May be any scalar type. floatval() should not be used on objects, as doing so will emit
an E_NOTICE level error and return 1.
Return Values
The float value of the given variable. Empty arrays return 0, non-empty arrays return 1.
Strings will most likely return 0 although this depends on the leftmost characters of the string.
The common rules of float casting apply.
Example #1 floatval()
<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>
<?php
$var = 'The122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 0
?>
Intval()
(PHP 4, PHP 5, PHP 7)
Description
Returns the integer value of var, using the specified base for the conversion (the default is base
10). intval() should not be used on objects, as doing so will emit an E_NOTICE level error and
return 1.
Parameters
var
base
Note:
if string includes a "0x" (or "0X") prefix, the base is taken as 16 (hex); otherwise,
Return Values
The integer value of var on success, or 0 on failure. Empty arrays return 0, non-empty arrays
return 1.
The maximum value depends on the system. 32 bit systems have a maximum signed integer
range of -2147483648 to 2147483647. So for example on such a
system, intval('1000000000000') will return 2147483647. The maximum signed integer value for
64 bit systems is 9223372036854775807.
Strings will most likely return 0 although this depends on the leftmost characters of the string.
The common rules of integer casting apply.
Example #1 intval()
<?php
echo intval(42); // 42
echo intval(4.2); // 4
echo intval('42'); // 42
echo intval('+42'); // 42
echo intval('-42'); // -42
echo intval(042); // 34
echo intval('042'); // 42
echo intval(1e10); // 1410065408
echo intval('1e10'); // 1
echo intval(0x1A); // 26
echo intval(42000000); // 42000000
echo intval(420000000000000000000); // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8); // 42
echo intval('42', 8); // 34
echo intval(array()); // 0
echo intval(array('foo', 'bar')); // 1
?>
print_r()
(PHP 4, PHP 5, PHP 7)
Description
print_r(), var_dump() and var_export() will also show protected and private properties of objects.
Static class members will not be shown.
Parameters
expression
return
If you would like to capture the output of print_r(), use the return parameter. When this
parameter is set to TRUE, print_r() will return the information rather than print it.
Return Values
If given a string, integer or float, the value itself will be printed. If given an array, values will be
presented in a format that shows keys and elements. Similar notation is used for objects.
When the return parameter is TRUE, this function will return a string. Otherwise, the return
value is TRUE.
Note:
When the return parameter is used, this function uses internal output buffering so it cannot be
used inside an ob_start() callback function.
Examples
<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>
<pre>
Array
[0] => x
[1] => y
[2] => z
</pre>
b. String Functions
Chr()
Return characters from different ASCII values:
The chr() function returns a character from the specified ASCII value
Syntax
chr(ascii)
Parameter Description
Example
<?php
echo chr(52) . "<br>"; // Decimal value
echo chr(052) . "<br>"; // Octal value
echo chr(0x52) . "<br>"; // Hex value
?>
Output
4
*
R
The ASCII value can be specified in decimal, octal, or hex values. Octal values are defined by a
leading 0, while hex values are defined by a leading 0x.
ord() Function
Definition and Usage
The ord() function returns the ASCII value of the first character of a string.
Syntax
ord(string)
Parameter Description
Example
<?php
echo ord("h")."<br>";
echo ord("hello")."<br>";
?>
104
104
strtolower()
Definition and Usage
Syntax
strtolower(string)
Parameter Description
Example
<?php
echo strtolower("Hello WORLD.");
?>
Output
hello world.
strtoupper() Function
Syntax
strtoupper(string)
Parameter Description
Example
<?php
echo strtoupper("Hello WORLD!");
?>
HELLO WORLD!
substr() Function
Definition and Usage
Syntax
substr(string,start,length)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
Output
World
strcmp() Function
Definition and Usage
Syntax
strcmp(string1,string2)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
strcasecmp() Function
Definition and Usage
Tip: This function is similar to the strncasecmp() function, with the difference that you can
specify the number of characters from each string to be used in the comparison with
strncasecmp().
Syntax
strcasecmp(string1,string2)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
stristr() Function
Definition and Usage
The stristr() function searches for the first occurrence of a string inside another string.
Syntax
stristr(string,search,before_search)
Parameter Description
search Required. Specifies the string to search for. If this parameter is a number, it will search
for the character matching the ASCII value of the number
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
Output
o world!
substr() Function
Definition and Usage
Syntax
substr(string,start,length)
Parameter Description
A negative number - Start at a specified position from the end of the string
length Optional. Specifies the length of the returned string. Default is to the end
of the string.
Negative number - The length to be returned from the end of the string
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
output
world
strlen() Function
Syntax
strlen(string)
Parameter Description
Return Value: Returns the length of a string (in bytes) on success, and 0 if the string is
empty
<!DOCTYPE html>
<html>
<body>
<?php
echo strlen("Hello");
?>
</body>
</html>
Output
strpos() Function
Definition and Usage
The strpos() function finds the position of the first occurrence of a string inside another string.
Syntax
strpos(string,find,start)
Parameter Description
Return Value: Returns the position of the first occurrence of a string inside another
string, or FALSE if the string is not found. Note: String positions start at
0, and not 1.
Example
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
output
strrpos() Function
Definition and Usage
The strrpos() function finds the position of the last occurrence of a string inside another string.
Syntax
strrpos(string,find,start)
Parameter Description
Return Value: Returns the position of the last occurrence of a string inside another string,
or FALSE if the string is not found. Note: String positions start at 0, and
not 1.
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
19
stripos() Function
Definition and Usage
The stripos() function finds the position of the first occurrence of a string inside another string.
Syntax
stripos(string,find,start)
Parameter Description
Return Value: Returns the position of the first occurrence of a string inside another
string, or FALSE if the string is not found. Note: String positions start at
0, and not 1.
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
Output
19
strrev() Function
Syntax
strrev(string)
Parameter Description
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
!dlroW olleH
strripos() Function
The strripos() function finds the position of the last occurrence of a string inside another string.
Syntax
strripos(string,find,start)
Parameter Description
Return Value: Returns the position of the last occurrence of a string inside another string,
or FALSE if the string is not found. Note: String positions start at 0, and
not 1.
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
19
str_replace() Function
Definition and Usage
The str_replace() function replaces some characters with some other characters in a string.
If the string to be searched is an array, find and replace is performed with every array element
If both find and replace are arrays, and replace has fewer elements than find, an empty string will
be used as replace
If find is an array and replace is a string, the replace string will be used for every find value
Syntax
str_replace(find,replace,string,count)
Parameter Description
Before PHP 4.3.3, this function experienced trouble when using arrays as both find and replace
parameters, which caused empty find indexes to be skipped without advancing the internal
pointer on the replace array. Newer versions will not have this problem.
<!DOCTYPE html>
<html>
<body>
<p>Search the string "Hello World!", find the value "world" and replace it with "Peter":</p>
<?php
?>
</body>
</html>
Search the string "Hello World!", find the value "world" and replace it with "Peter":
Hello Peter!
echo() Function
Definition and Usage
The echo() function is not actually a function, so you are not required to use parentheses with it.
However, if you want to pass more than one parameter to echo(), using parentheses will generate
a parse error.
The echo() function also has a shortcut syntax. Prior to PHP 5.4.0, this syntax only works with
the short_open_tag configuration setting enabled.
Syntax
echo(strings)
Parameter Description
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
OUTPUT
Hello world!
print() Function
The print() function is not actually a function, so you are not required to use parentheses with it.
Syntax
print(strings)
Parameter Description
<!DOCTYPE html>
<html>
<body>
<?php
?>
OUTPUT
</body>
</html>
Hello world!
trim() Function
Definition and Usage
The trim() function removes whitespace and other predefined characters from both sides of a
string.
Syntax
trim(string,charlist)
Parameter Description
charlist Optional. Specifies which characters to remove from the string. If omitted,
all of the following characters are removed:
"\0" - NULL
"\t" - tab
EXAMPLE
<!DOCTYPE html>
<html>
<body>
<?php
echo trim($str,"Hed!");
?>
</body>
</html>
OUTPUT
Hello World!
llo Worl
ltrim() Function
Definition and Usage
The ltrim() function removes whitespace or other predefined characters from the left side of a
string.
Syntax
ltrim(string,charlist)
Parameter Description
charlist Optional. Specifies which characters to remove from the string. If omitted,
all of the following characters are removed:
"\0" - NULL
"\t" - tab
example
<!DOCTYPE html>
<html>
<body>
<?php
echo ltrim($str,"Hello");
?>
</body>
</html>
Output
Hello World!
World!
rtrim() Function
Definition and Usage
The rtrim() function removes whitespace or other predefined characters from the right side of a
string.
Syntax
rtrim(string,charlist)
Parameter Description
charlist Optional. Specifies which characters to remove from the string. If omitted,
all of the following characters are removed:
"\0" - NULL
"\t" - tab
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo rtrim($str,"World!");
?>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
?php
echo strlen("Hello");
?>
</body>
</html>
output
c. math functions
abs()
The abs() function returns the absolute (positive) value of a number.
Syntax
abs(number);
Parameter Description
number Required. Specifies a number. If the number is of type float, the return type is also
float, otherwise it is integer
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo(abs(6.7) . "<br>");
echo(abs(-6.7) . "<br>");
echo(abs(-3) . "<br>");
echo(abs(3));
?>
</body>
</html>
Out put
6.7
6.7
3
3
ceil() Function
Definition and Usage
Syntax
ceil(number);
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo(ceil(0.60) . "<br>");
echo(ceil(0.40) . "<br>");
echo(ceil(5) . "<br>");
echo(ceil(5.1) . "<br>");
echo(ceil(-5.1) . "<br>");
echo(ceil(-5.9));
?>
</body>
</html>
1
1
5
6
-5
-5
floor() Function
The floor() function rounds a number DOWN to the nearest integer, if necessary.
Syntax
floor(number);
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo(floor(0.60) . "<br>");
echo(floor(0.40) . "<br>");
echo(floor(5) . "<br>");
echo(floor(5.1) . "<br>");
echo(floor(-5.1) . "<br>");
echo(floor(-5.9));
?>
</body>
</html>
Output
0
0
5
5
-6
-6
round() Function
Definition and Usage
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo(round(0.60) . "<br>");
echo(round(0.50) . "<br>");
echo(round(0.49) . "<br>");
echo(round(-4.40) . "<br>");
echo(round(-4.60));
?>
</body>
</html>
Output
1
1
0
-4
-5
fmod() Function
Syntax
fmod(x,y);
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
$x = 7;
$y = 2;
$result = fmod($x,$y);
echo $result;
?>
</body>
</html>
Output
min() Function
The min() function returns the lowest value in an array, or the lowest value of several specified
values.
Syntax
min(array_values);
or
min(value1,value2,...);
Parameter Description
value1,value2,... Required. Specifies the values to compare (must be at least two values)
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo(min(2,4,6,8,10) . "<br>");
echo(min(22,14,68,18,15) . "<br>");
echo(min(array(4,6,8,10)) . "<br>");
echo(min(array(44,16,81,12)));
?>
</body>
</html>
Output
2
14
4
12
max() Function
The max() function returns the highest value in an array, or the highest value of several specified
values.
Syntax
max(array_values);
or
max(value1,value2,...);.
Parameter Description
value1,value2,... Required. Specifies the values to compare (must be at least two values)
<!DOCTYPE html>
<html>
<body>
example
<?php
echo(max(2,4,6,8,10) . "<br>");
echo(max(22,14,68,18,15) . "<br>");
echo(max(array(4,6,8,10)) . "<br>");
echo(max(array(44,16,81,12)));
?>
</body>
</html>
10
68
10
81
pow() Function
Syntax
pow(x,y);
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo(pow(2,4) . "<br>");
echo(pow(-2,4) . "<br>");
echo(pow(-2,-4) . "<br>");
echo(pow(-2,-3.2));
?>
</body>
</html>
16
16
0.0625
NAN
sqrt() Function
Syntax
sqrt(number);
Parameter Description
Return Value: The square root of number, or NAN for negative numbers
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo(sqrt(0) . "<br>");
echo(sqrt(1) . "<br>");
echo(sqrt(9) . "<br>");
echo(sqrt(0.64) . "<br>");
echo(sqrt(-9));
?>
</body>
</html>
Output
0
1
3
0.8
NAN
rand() Function
If you want a random integer between 10 and 100 (inclusive), use rand (10,100).
Syntax
rand();
or
rand(min,max);
Parameter Description
Return Value: A random integer between min (or 0) and max (or getrandmax() inclusive)
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo(rand() . "<br>");
echo(rand() . "<br>");
echo(rand(10,100));
?>
</body>
</html>
output
1554955389
961018293
32
d. Date/Time Functions
date() Function
The date() function formats a local date and time, and returns the formatted date string.
Syntax
date(format, timestamp)
Parameter Description
format Required. Specifies the format of the outputted date string. The following
characters can be used:
S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well
with j)
a - Lowercase am or pm
A - Uppercase AM or PM
I (capital i) - Whether the date is in daylights savings time (1 if Daylight Savings Time, 0
otherwise)
Z - Timezone offset in seconds. The offset for timezones west of UTC is negative (-43200 to
50400)
r - The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200)
U - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo date(DATE_ATOM,mktime(0,0,0,10,3,1975));
?>
</body>
</html>
Output
Saturday
Saturday 24th of August 2019 05:42:30 AM
Oct 3,1975 was on a Friday
Sat, 24 Aug 19 05:42:30 +0000
1975-10-03T00:00:00+00:00
getdate() Function
Definition and Usage
The getdate() function returns date/time information of a timestamp or the current local
date/time.
Syntax
getdate(timestamp)
Parameter Description
timestamp Optional. Specifies an integer Unix timestamp. Default is the current local
time (time())
Return Value: Returns an associative array with information related to the timestamp:
[seconds] - seconds
[minutes] - minutes
[hours] - hours
[mon] - month
[year] - year
Example
<!DOCTYPE html>
<html>
<body>
<?php
print_r(getdate());
echo "<br><br>";
$mydate=getdate(date("U"));
?>
</body>
</html>
Output
Array ( [seconds] => 28 [minutes] => 53 [hours] => 5 [mday] => 24 [wday] => 6 [mon] => 8
[year] => 2019 [yday] => 235 [weekday] => Saturday [month] => August [0] => 1566626008 )
setDate() Function
date_date_set
Description
Procedural style
date_date_set ( DateTime $object , int $year , int $month , int $day ) : DateTime
Parameters
object
Procedural style only: A DateTime object returned by date_create(). The function modifies this
object.
year
month
day
Return Values
Examples
<?php
$date = new DateTime();
$date->setDate(2001, 2, 3);
echo $date->format('Y-m-d');
?>
Procedural style
<?php
$date = date_create();
date_date_set($date, 2001, 2, 3);
echo date_format($date, 'Y-m-d');
?>
2001-02-03
checkdate() Function
Definition and Usage
Syntax
Parameter Description
<!DOCTYPE html>
<html>
<body>
Example
<?php
var_dump(checkdate(12,31,-400));
echo "<br>";
var_dump(checkdate(2,29,2003));
echo "<br>";
var_dump(checkdate(2,29,2004));
?>
</body>
</html>
Output
bool(false)
bool(false)
bool(true)
time() Function
Definition and Usage
The time() function returns the current time in the number of seconds since the Unix Epoch
(January 1 1970 00:00:00 GMT).
Syntax
time()
Return Value: Returns an integer containing the current time as a Unix timestamp
Example
<!DOCTYPE html>
<html>
<body>
<?php
$t=time();
echo($t . "<br>");
echo(date("Y-m-d",$t));
?>
</body>
</html>
Output
1566626420
2019-08-24
mktime() Function
Tip: This function is identical to gmmktime() except the passed parameters represents a date (not
a GMT date).
Syntax
Parameter Description
is_dst Optional. Set this parameter to 1 if the time is during daylight savings time (DST), 0 if it
is not, or -1 (the default) if it is unknown. If it's unknown, PHP tries to find out itself (which may
cause unexpected results). Note: This parameter is removed in PHP 7.0. The new timezone
handling features should be used instead
Exmple
<!DOCTYPE html>
<html>
<body>
<?php
//The mktime() function is useful for doing date arithmetic and validation.
//It will automatically calculate the correct value for out-of-range input:
?>
</body>
</html>
Jan-05-2002
Feb-01-2002
Jan-01-2001
Jan-01-1999
e. Array Functions
array() Function
Definition and Usage
Syntax
array(key=>value,key=>value,key=>value,etc.)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
Output
Asosiative Array
Associative arrays are arrays that use named keys that you assign to them.
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
Output
count() Function
Definition and Usage
Syntax
count(array, mode)
Parameter Description
1 - Counts the array recursively (counts all the elements of multidimensional arrays)
Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
</body>
</html>
output
list() Function
The list() function is used to assign values to a list of variables in one operation.
Syntax
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
$my_array = array("Dog","Cat","Horse");
?>
</body>
</html>
Output
in_array() Function
Definition and Usage
If the search parameter is a string and the type parameter is set to TRUE, the search is case-
sensitive.
Syntax
Parameter Description
type Optional. If this parameter is set to TRUE, the in_array() function searches for the
search-string and specific type in the array.
<!DOCTYPE html>
<html>
<body>
<?php
if (in_array("Glenn", $people))
else
?>
</body>
</html>
Output
Match found
Return Value: Returns TRUE if the value is found in the array, or FALSE otherwise
current() Function
The current() function returns the value of the current element in an array.
Every array has an internal pointer to its "current" element, which is initialized to the first
element inserted into the array.
Tip: This function does not move the arrays internal pointer.
Syntax
current(array)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
Output
Peter
next() Function
Definition and Usage
The next() function moves the internal pointer to, and outputs, the next element in the array.
Syntax
next(array)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo next($people);
?>
</body>
</html>
Output
Peter
Joe
Return Value: Returns the value of the last element in the array on success, or FALSE if
the array is empty
prev() Function
Definition and Usage
The prev() function moves the internal pointer to, and outputs, the previous element in the array.
Syntax
prev(array)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo prev($people);
?>
</body>
</html>
output
Peter
Joe
Peter
Return Value: Returns the value of the previous element in the array on success, or FALSE if
there are no more elements
reset() Function
Definition and Usage
The reset() function moves the internal pointer to the first element of the array.
Syntax
reset(array)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo reset($people);
?>
</body>
</html>
Output
Peter
Joe
Peter
Return Value: Returns the value of the first element in the array on success, or FALSE if
the array is empty
each() Function
Definition and Usage
The each() function returns the current element key and value, and moves the internal pointer
forward.
This element key and value is returned in an array with four elements. Two elements (1 and
Value) for the element value, and two elements (0 and Key) for the element key.
Syntax
each(array)
Parameter Description
Return Value: Returns the current element key and value. This element key and value is
returned in an array with four elements. Two elements (1 and Value) for
the element value, and two elements (0 and Key) for the element key. This
function returns FALSE if there are no more array elements
<!DOCTYPE html>
<html>
<body>
<?php
print_r (each($people));
?>
</body>
</html>
Output
Array ( [1] => Peter [value] => Peter [0] => 0 [key] => 0 )
sort() Function
Definition and Usage
Syntax
sort(array, sorttype)
Parameter Description
sorttype Optional. Specifies how to compare the array elements/items. Possible values:
5 = SORT_FLAG_CASE –
Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
sort($cars);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
echo $cars[$x];
echo "<br>";
?>
</body>
</html>
Output
BMW
Toyota
Volvo
rsort() Function
Definition and Usage
Syntax
rsort(array, sorttype)
Parameter Description
sorttype Optional. Specifies how to compare the array elements/items. Possible values:
5 = SORT_FLAG_CASE –
Example
<!DOCTYPE html>
<html>
<body>
<?php
$cars=array("Volvo","BMW","Toyota");
rsort($cars);
$clength=count($cars);
for($x=0;$x<$clength;$x++)
echo $cars[$x];
echo "<br>";
?>
</body>
</html>
Output
Volvo
Toyota
BMW
arsort() Function
Definition and Usage
The arsort() function sorts an associative array in descending order, according to the value.
Syntax
arsort(array, sorttype)
Parameter Description
sorttype Optional. Specifies how to compare the array elements/items. Possible values:
5 = SORT_FLAG_CASE –
Example
<!DOCTYPE html>
<html>
<body>
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
foreach($age as $x=>$x_value)
echo "<br>";
?>
</body>
</html>
Output
Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35
array_merge() Function
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.
If you assign only one array to the array_merge() function, and the keys are integers, the function
returns a new array with integer keys starting at 0 and increases by 1 for each value (See example
below).
The difference between this function and the array_merge_recursive() function is when two or
more array elements have the same key. Instead of override the keys, the
array_merge_recursive() function makes the value as an array.
Syntax
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
</body>
</html>
Output
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
array_reverse() Function
Definition and Usage
Syntax
array_reverse(array, preserve)
Parameter Description
preserve Optional. Specifies if the function should preserve the keys of the array or not.
Exampe
<!DOCTYPE html>
<html>
<body>
<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>
</body>
</html>
Output
Array ( [c] => Toyota [b] => BMW [a] => Volvo )
f. Filesystem Functions
move_uploaded_file() Function
Definition and Usage
This function only works on files uploaded via PHP's HTTP POST upload mechanism.
Syntax
move_uploaded_file(file, dest)
Parameter Description
Example
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>
fopen() Function
Definition and Usage
When writing to a text file, be sure to use the correct line-ending character! Unix systems use \n,
Windows systems use \r\n, and Macintosh systems use \r as the line ending character. Windows
offers a translation flag ('t') which will translate \n to \r\n when working with the file. You can
also use 'b' to force binary mode. To use these flags, specify either 'b' or 't' as the last character of
the mode parameter.
Syntax
Parameter Description
mode Required. Specifies the type of access you require to the file/stream.
Possible values:
"w" - Write only. Opens and truncates the file; or creates a new file if it doesn't exist. Place file
pointer at the beginning of the file
"w+" - Read/Write. Opens and truncates the file; or creates a new file if it doesn't exist. Place file
pointer at the beginning of the file
"a" - Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist
"a+" - Read/Write. Preserves file content by writing to the end of the file
"x" - Write only. Creates a new file. Returns FALSE and an error if file already exists
"x+" - Read/Write. Creates a new file. Returns FALSE and an error if file already exists
"c" - Write only. Opens the file; or creates a new file if it doesn't exist. Place file pointer at the
beginning of the file
"c+" - Read/Write. Opens the file; or creates a new file if it doesn't exist. Place file pointer at the
beginning of the file
nclude_path Optional. Set this parameter to '1' if you want to search for the file in the
include_path (in php.ini) as well
context Optional. Specifies the context of the file handle. Context is a set of options that can
modify the behavior of a stream
example
<!DOCTYPE html>
<html>
<body>
<?php
$file = fopen("test.txt","r");
//Output lines until EOF is reached
while(! feof($file)) {
$line = fgets($file);
echo $line. "<br>";
}
fclose($file);
?>
</body>
</html>
Output
Return Value: TRUE on success, FALSE and an error on failure. You can hide the error
by adding an "@" in front of the function name.
fwrite() Function
Definition and Usage
The function will stop at the end of the file (EOF) or when it reaches the specified length,
whichever comes first.
Syntax
Parameter Description
Example
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>
Output
fread() Function
Definition and Usage
The function will stop at the end of the file or when it reaches the specified length, whichever
comes first.
Syntax
fread(file, length)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
$file = fopen("test.txt","r");
$data=fread($file,"10");
echo $data;
fclose($file);
?>
</body>
</html>
Output
file data will be in $data variable and it will be printed by echo statement.
fclose() Function
Definition and Usage
Syntax
fclose(file)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
$file = fopen("test.txt","r");
fclose($file);
?>
</body>
</html>
feof() Function
Definition and Usage
The feof() function checks if the "end-of-file" (EOF) has been reached for an open file.
Syntax
feof(file)
Parameter Description
Example
<!DOCTYPE html>
<html>
<body>
<?php
$file = fopen("test.txt","r");
fclose($file);
?>
</body>
</html>
Output
file_exists() Function
Definition and Usage
The result of this function is cached. Use clearstatcache() to clear the cache.
Syntax
file_exists(path)
Parameter Description
<!DOCTYPE html>
<html>
<body>
<?php
echo file_exists("webdictionary.txt");
?>
</body>
</html>
Output
1(true)-file exists
fgetc() Function
Definition and Usage
This function is slow and should not be used on large files. If you need to read one character at a
time from a large file, use fgets() to read data one line at a time and then process the line one
single character at a time with fgetc().
Syntax
fgetc(file)
Parameter Description
file Required. Specifies the open file to return a single character from
Example
<!DOCTYPE html>
<html>
<body>
<?php
$file = fopen("test.txt","r");
echo fgetc($file);
fclose($file);
?>
</body>
</html>
Output
fgets() Function
Definition and Usage
Syntax
fgets(file, length)
Parameter Description
length Optional. Specifies the number of bytes to read. Reading stops when length-1 bytes have
been reached, or when a new line occurs, or on EOF. If no length is specified, it reads until end
of the line
Example
<!DOCTYPE html>
<html>
<body>
<?php
$file = fopen("test.txt","r");
echo fgets($file);
fclose($file);
?>
</body>
</html>
Output
fseek() Function
Definition and Usage
This function moves the file pointer from its current position to a new position, forward or
backward, specified by the number of bytes.
Syntax
Parameter Description
offset Required. Specifies the new position (measured in bytes from the beginning of the
file)
SEEK_END - Set position to EOF plus offset (to move to a position before EOF,
the offset must be a negative value)
Example
<!DOCTYPE html>
<html>
<body>
<?php
$file = fopen("test.txt","r");
// Read first line
echo fgets($file);
// Move back to beginning of file
fseek($file,0);
fclose($file);
?>
</body>
</html>
Output
ftell() Function
Definition and Usage
The ftell() function returns the current position of the read/write pointer in an open file.
Syntax
ftell(file)
Parameter Description
example
<!DOCTYPE html>
<html>
<body>
<?php
$file = fopen("test.txt","r");
fclose($file);
?>
</body>
</html>
Output
0
15
is_uploaded_file() Function
The is_uploaded_file() function checks whether the specified file is uploaded via HTTP POST.
Syntax
is_uploaded_file(file)
Parameter Description
Example
<?php
$file = "test.txt";
if(is_uploaded_file($file)) {
echo ("$file is uploaded via HTTP POST");
} else {
echo ("$file is not uploaded via HTTP POST");
}
?>
Output
g. Miscellaneous Functions
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.
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:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
So, if you want the execution to go on and show users the output, even if the include file is
missing, use the include statement. Otherwise, in case of FrameWork, CMS, or a complex PHP
application coding, always use the require statement to include a key file to the flow of
execution. This will help avoid compromising your application's security and integrity, just in-
case one key file is accidentally missing.
Including files saves a lot of work. This means that you can create a standard header, footer, or
menu file for all your web pages. Then, when the header needs to be updated, you can only
update the header include file.
Syntax
include 'filename';
or
require 'filename';
Example
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
</body>
</html>
The require statement is also used to include a file into the PHP code.
However, there is one big difference between include and require; when a file is included with
the include statement and PHP cannot find it, the script will continue to execute:
Example
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php include 'noFileExists.php';
echo "I have a $color $car.";
?>
</body>
</html>
If we do the same example using the require statement, the echo statement will not be executed
because the script execution dies after the require statement returned a fatal error:
Example
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php require 'noFileExists.php';
echo "I have a $color $car.";
?>
</body>
</html>
require_once(), include_once()
Description
require_once()
this function can be used to include a php file in another one, when you may need to include the
called file more than once. If it is found that the file has already been included, calling script is
going to ignore further inclusions.
If a.php is a php script calling b.php with require_once() statement, and does not find b.php,
a.php stops executes causing a fatal error.
Syntax:
Example:
<?php
?>
The above file abc.php, is included twice with require_once() statement in the following file
y.php. But from the output you will get that the second instance of inclusion is ignored, since
require_once() statement ignores all the similar inclusions after the first one.
<?php
require_once('abc.php');
require_once('abc.php');
?>
If a calling script does not find a called script with the require_once statement, it halts the
execution of the calling script.
include_once()
Description
The include_once() statement can be used to include a php file in another one, when you may
need to include the called file more than once. If it is found that the file has already been
included, calling script is going to ignore further inclusions.
If a.php is a php script calling b.php with include_once() statement, and does not find b.php,
a.php executes with a warning, excluding the part of the code written within b.php.
Syntax:
Example:
<?php
?>
The above file abc.php, is included twice with include_once() statement in the following file
y.php. But from the output you will get that the second instance of inclusion is ignored, since
include_once() statement ignores all the similar inclusions after the first one.
<?php
include_once('abc.php');
include_once('abc.php');
?>
header() Function
PHP headers can perform certain things, some of them are listed below:
<?php
header("Location: http://www.example.com/");
?>
Please note that Location starts with capital L, some browsers might not redirect if small l is
used.
Even though you redirected the user successfully, yet this is not the proper way to do it. The
above command does not generate the 301 response which means the target page will lose a hit
count and SEO ranking. To avoid that, you have to add an additional header.
<?php
header("Location: http://www.example.com/");
?>
Furthermore, you can add some redirection interval by using the following code:
<?php
?>
You can prevent the browser to cache pages by using the following code:
<?php
//Date in the past, tells the browser that the cache has expired
/* The following tell the browser that the last modification is right not so it must load the page
again */ header("Last-Modified: ". gmdate("D, d M Y H:i:s"). "GMT");
//HTTP/1.0
header("Pragma: no-cache");
?>
The above code will let the browser load the page fresh from the server every time it is called.
The reason is simple; we tell the browser that the content just expired and it was just last
modified too. Furthermore, we also tell it Pragma: no-cache to make sure it gets a fresh server
copy each time.
<?php
?>
Example
Let the user be prompted to save a generated PDF file (Content-Disposition header is used to
supply a recommended filename and force the browser to display the save dialog box):
<html>
<body>
<?php
header("Content-type:application/pdf");
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");
// The PDF source is in original.pdf
readfile("original.pdf");
?>
</body>
</html>
Example
<?php
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>
<html>
<body>
die() Function
Definition and Usage
Syntax
die(message)
Parameter Description
message Required. A message or status number to print before terminating the script. A
status number will not be written to the output, just used as the exit status.
Example
<?php
$site = "https://www.w3schools.com/";
fopen($site,"r")
or die("Unable to connect to $site");
?>
Output
16. Form Handling passing data from html form to php file
The PHP superglobals $_GET and $_POST are used to collect form-data.
The example below displays a simple HTML form with two input fields and a submit button:
Example
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
Output
Name:
E-mail:
Submit
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST
method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks
like this:
Welcome.php
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
Welcome John
Your email address is [email protected]
The same result could also be achieved using the HTTP GET method:
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
welcome_get.php
<html>
<body>
</body>
</html>
Only ASCII characters are permitted. No constraints, even binary data is permitted.
This article discussed two important methods of form handling in PHP. They are GET and POST
methods. Generally speaking, developers prefer POST method for sending data than using the
GET method. The key difference Between GET and POST method in PHP is that GET method
sends the information by appending them to the page request while POST method sends
information via HTTP header.
Syntax
Parameter Description
Return Value: Returns an object representing the connection to the MySQL server
Example
<?php
$con = mysqli_connect("localhost","root","","ksv");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
mysqli_connect_errno() Function
Return an error code from the last connection error, if any:
<?php
$con=mysqli_connect("localhost","wrong_user","my_password","my_db");
// Check connection
if (!$con)
?>
The mysqli_connect_errno() function returns the error code from the last
connection error, if any.
Syntax
mysqli_connect_errno();
mysqli_connect_error() Function
Return an error description from the last connection error, if any:
<?php
$con=mysqli_connect("localhost","wrong_user","my_password","my_db");
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
?>
The mysqli_connect_error() function returns the error description from the last
connection error, if any.
Syntax
mysqli_connect_error();
Return Value: Returns a string that describes the error. NULL if no error
occurred
mysqli_connect_errno() Function
<?php
$con=mysqli_connect("localhost","wrong_user","my_password","my_db");
// Check connection
if (!$con)
?>
The mysqli_connect_errno() function returns the error code from the last
connection error, if any.
Syntax
mysqli_connect_errno();
mysqli_query() Function
Definition and Usage
Syntax
mysqli_query(connection,query,resultmode);
Parameter Description
resultmode
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_close($con);
?>
mysqli_affected_rows() Function
Definition and Usage
Syntax
mysqli_affected_rows(connection)
Parameter Description
Return Value: The number of rows affected. -1 indicates that the query
returned an error
Example
Return number of affected rows from different queries:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
mysqli_fetch_array() Function
Definition and Usage
Syntax
mysqli_fetch_array(result,resulttype);
Parameter Description
MYSQLI_ASSOC
MYSQLI_NUM
MYSQLI_BOTH
Return Value: Returns an array of strings that corresponds to the fetched row.
NULL if there are no more rows in result-set
Example
Fetch a result row as a numeric array and as an associative array:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
mysqli_close($con);
?>
mysqli_fetch_assoc() Function
Definition and Usage
Syntax
mysqli_fetch_assoc(result);
Parameter Description
Return Value: Returns an associative array of strings representing the fetched row.
NULL if there are no more rows in result-set
Example
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Associative array
$row=mysqli_fetch_assoc($result);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
mysqli_close($con);
?>
mysqli_fetch_row() Function
Definition and Usage
The mysqli_fetch_row() function fetches one row from a result-set and returns it as
an enumerated array.
Syntax
mysqli_fetch_row(result);
Parameter Description
Return Value: Returns an array of strings that corresponds to the fetched row.
NULL if there are no more rows in result set
Example
Fetch rows from a result-set:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($result=mysqli_query($con,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf ("%s (%s)\n",$row[0],$row[1]);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
mysqli_fetch_object() Function
Definition and Usage
The mysqli_fetch_object() function returns the current row of a result set, as an object.
Syntax
mysqli_fetch_object(result,classname,params);
Parameter Description
classname Optional. Specifies the name of the class to instantiate, set the properties of, and
return
params Optional. Specifies an array of parameters to pass to the constructor for classname
objects
Return Value: Returns an object with string properties for the fetched row. NULL if there
are no more rows in the result set
Example
Return the current row of a result set, then print each field's value:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($result=mysqli_query($con,$sql))
{
while ($obj=mysqli_fetch_object($result))
{
printf("%s (%s)\n",$obj->Lastname,$obj->Age);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql))
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?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
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname",
"email" and "reg_date":
The data type specifies what type of data the column can hold. For a complete reference of all
the available data types, go
After the data type, you can specify other optional attributes for each column:
NOT NULL - Each row must contain a value for that column, null values are not allowed
DEFAULT value - Set a default value that is added when no other value is passed
UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a new record is
added
PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is
often an ID number, and is often used with AUTO_INCREMENT
Each table should have a primary key column (in this case: the "id" column). Its value must be
unique for each record in the table.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql))
{
echo "Table MyGuests created successfully";
else
{
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
{
echo "Table MyGuests created successfully";
}
else
{
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn = null;
?>
The INSERT INTO statement is used to add new records to a MySQL table:
In the previous chapter we created an empty table named "MyGuests" with five columns: "id",
"firstname", "lastname", "email" and "reg_date". Now, let us fill the table with data.
If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP with default update
of current_timesamp (like the "reg_date" column), it is no need to be specified in the SQL query;
MySQL will automatically add the value.
Form register.html/.php
Example
<html>
<head><title>register please</title>
<h1>Register Please</h1>
</head>
<body>
<form name=f1 action=’signup.php’ method=’get’>
Enter First Name<input type=text name=’firstname’><br>
Enter Last Name<input type=text name=’lastname’><br>
Enter Email <input type=text name=’email’><br>
<input type=submit value=’register’>
</form>
</body>
</html>
-signup.php
(signup.php MySQLi Procedural)- Get variable from form and insert in database
<?php
$fn=$_GET[‘firstname’];
$ln=$_GET[‘lastname’];
$em=$_GET[‘email’];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
signup.php MySQLi Object-oriented- Get variable from form and insert in database
<?php
$fn=$_GET[‘firstname’];
$ln=$_GET[‘lastname’];
$em=$_GET[‘email’];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
{
echo "New record created successfully";
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
signup.php Example (PDO)- Get variable from form and insert in database
<?php
$fn=$_GET[‘firstname’];
$ln=$_GET[‘lastname’];
$em=$_GET[‘email’];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = “INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘$fn’, ‘$ln’, ‘$em’)”;
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
The following example selects the id, firstname and lastname columns from the MyGuests table
and displays it on the page:
Example (MySQLi Procedural)-fetching data from mysql to php and display it in html
form
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_num_rows($result) > 0)
{
// output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
}
else
{
echo "0 results";
}
mysqli_close($conn);
?>
Example (MySQLi Object-oriented) fetching data from mysql to php and display it in html
form
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
if ($result->num_rows > 0)
{
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc())
{
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]." ".$row["lastname"]."</td></tr>";
}
echo "</table>";
}
else
{
echo "0 results";
}
$conn->close();
?>
Select Data With PDO (+ Prepared Statements)- fetching data from mysql to php and
display it in html form
It selects the id, firstname and lastname columns from the MyGuests table and displays it in an
HTML table:
Example (PDO)- fetching data from mysql to php and display it in html form
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";
function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record
or records that should be deleted. If you omit the WHERE clause, all records will be deleted!
Example (MySQLi Procedural) –delete data from mysql using php file
<?php
$id=$_GET[‘id’];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql))
{
echo "Record deleted successfully";
}
else
{
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (MySQLi Object-oriented) –deleting data from mysql using php file
<?php
$id=$_GET[‘id’];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
After the record is deleted, the table will look like this:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which record
or records that should be updated. If you omit the WHERE clause, all records will be updated!
The following examples update the record with id=2 in the "MyGuests" table:
<?php
$id=$_GET[‘id’];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
mysqli_num_rows() Function
Syntax
mysqli_num_rows(result);
Parameter Description
Example
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rowcount);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
mysqli_affected_rows() Function
The mysqli_affected_rows() function returns the number of affected rows in the previous
SELECT, INSERT, UPDATE, REPLACE, or DELETE query.
Syntax
mysqli_affected_rows(connection)
Parameter Description
Return Value: The number of rows affected. -1 indicates that the query returned
an error
Example
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
mysqli_error() Function
The mysqli_error() function returns the last error description for the most recent function call, if
any.
Syntax
mysqli_error(connection);
Parameter Description
Return Value: Returns a string with the error description. "" if no error occurred
Example
Return the last error description for the most recent function call, if any:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
mysqli_errno() Function
The mysqli_errno() function returns the last error code for the most recent function call, if any.
Syntax
mysqli_errno(connection);
Parameter Description
Example
Return the last error code for the most recent function call, if any:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
mysqli_insert_id Function
The following examples are equal to the examples from the previous page (PHP Insert Data Into
MySQL), except that we have added one single line of code to retrieve the ID of the last inserted
record. We also echo the last inserted ID:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Before we go in detail, lets define important terms related to Object Oriented Programming.
Class − This is a programmer-defined data type, which includes local functions as well as local data. You
can think of a class as a template for making many instances of the same kind (or class) of object.
Object − An individual instance of the data structure defined by a class. You define a class once and then
make many objects that belong to it. Objects are also known as instance.
Member Variable − These are the variables defined inside a class. This data will be invisible to the
outside of the class and can be accessed via member functions. These variables are called attribute of the
object once an object is created.
Member function − These are the function defined inside a class and are used to access object data.
Inheritance − When a class is defined by inheriting existing function of a parent class then it is called
inheritance. Here child class will inherit all or few member functions and variables of a parent class.
Parent class − A class that is inherited from by another class. This is also called a base class or super
class.
Child Class − A class that inherits from another class. This is also called a subclass or derived class.
Polymorphism − This is an object oriented concept where same function can be used for different
purposes. For example function name will remain same but it take different number of arguments and can
do different task.
Overloading − a type of polymorphism in which some or all of operators have different implementations
depending on the types of their arguments. Similarly functions can also be overloaded with different
implementation.
Data Abstraction − Any representation of data in which the implementation details are hidden
(abstracted).
Encapsulation − refers to a concept where we encapsulate all the data and member functions together to
form an object.
Constructor − refers to a special type of function which will be called automatically whenever there is an
object formation from a class.
Destructor − refers to a special type of function which will be called automatically whenever an object is
deleted or goes out of scope
Magic Methods
The function
names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(),
__wakeup(), __toString(),__invoke(), __set_state(), __clone() and __debugInfo() are magical in PHP
classes. You cannot have functions with these names in any of your classes unless you want the magic
functionality associated with them.
<?php
class phpClass {
var $var1;
[..]
[..]
?>
The special form class, followed by the name of the class that you want to define.
A set of braces enclosing any number of variable declarations and function definitions.
Variable declarations start with the special form var, which is followed by a conventional $ variable
name; they may also have an initial assignment to a constant value.
Function definitions look much like standalone PHP functions but are local to the class and will be used
to set and access object data.
Example
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
function getPrice(){
function setTitle($par){
$this->title = $par;
function getTitle(){
?>
The variable $this is a special variable and it refers to the same object ie. itself.
Once you defined your class, then you can create as many objects as you like of that class type. Following
is an example of how to create object using new operator.
Here we have created three objects and these objects are independent of each other and they will have
their existence separately. Next we will see how to access member function and process member
variables.
After creating your objects, you will be able to call member functions related to that object. One member
function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books by calling member functions.
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
Now you call another member functions to get the values set by in above example −
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
Advanced Chemistry
Algebra
10
15
Constructor Functions
Constructor Functions are special type of functions which are called automatically whenever an object is
created. So we take full advantage of this behaviour, by initializing many things through constructor
functions.
PHP provides a special function called __construct() to define a constructor. You can pass as many as
arguments you like into the constructor function.
Following example will create one constructor for Books class and it will initialize price and title for the
book at the time of object creation.
$this->title = $par1;
$this->price = $par2;
Now we don't need to call set function separately to set price and title. We can initialize these two
member variables at the time of object creation only. Check following example below −
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
Advanced Chemistry
Algebra
10
15
Destructor
Like a constructor function you can define a destructor function using function __destruct(). You can
release all the resources with-in a destructor.
Inheritance
PHP class definitions can optionally inherit from a parent class definition by using the extends clause.
The syntax is as follows −
<definition body>
The effect of inheritance is that the child class (or subclass or derived class) has the following
characteristics −
Automatically has all the member variable declarations of the parent class.
Automatically has all the same member functions as the parent, which (by default) will work the same
way as those functions do in the parent.
Following example inherit Books class and adds more functionality based on the requirement.
var $publisher;
function setPublisher($par){
$this->publisher = $par;
function getPublisher(){
Now apart from inherited functions, class Novel keeps two additional member functions.
Function Overriding
Function definitions in child classes override definitions with the same name in parent classes. In a child
class, we can modify the definition of a function inherited from parent class.
In the following example getPrice and getTitle functions are overridden to return some values.
function getPrice() {
return $this->price;
function getTitle(){
return $this->title;
Public Members
Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be
accessed in three possible situations −
From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to limit the accessibility of the
members of a class then you define class members as private or protected.
Private members
By designating a member private, you limit its accessibility to the class in which it is declared. The
private member cannot be referred to from classes that inherit the class in which it is declared and cannot
be accessed from outside the class.
A class member can be made private by using private keyword infront of the member.
class MyClass {
$driver = "SRK";
function __construct($par) {
// is created.
function myPublicFunction() {
return("I'm visible!");
When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as
will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car,
because they are declared private.
Protected members
A protected property or method is accessible in the class in which it is declared, as well as in classes that
extend that class. Protected members are not available outside of those two kinds of classes. A class
member can be made protected by using protected keyword in front of the member.
class MyClass {
$driver = "SRK";
function __construct($par) {
// is created.
function myPublicFunction() {
return("I'm visible!");
Interfaces
Interfaces are defined to provide a common function names to the implementers. Different implementors
can implement those interfaces according to their requirements. You can say, interfaces are skeletons
which are implemented by developers.
interface Mail {
Constants
A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a
constant is immutable. Once you declare a constant, it does not change.
class MyClass {
function __construct($incomingValue) {
// is created.
In this class, requiredMargin is a constant. It is declared with the keyword const, and under no
circumstances can it be changed to anything other than 1.7. Note that the constant's name does not have a
leading $, as variable names do.
Abstract Classes
An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the
keyword abstract, like this −
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must
be defined by the child; additionally, these methods must be defined with the same visibility.
Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is
not legal to have abstract function definitions inside a non-abstract class.
Static Keyword
Declaring class members or methods as static makes them accessible without needing an instantiation of
the class. A member declared as static can not be accessed with an instantiated class object (though a
static method can).
<?php
class Foo {
return self::$my_static;
?>
Final Keyword
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing
the definition with final. If the class itself is being defined final then it cannot be extended.
Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()
<?php
class BaseClass {
?>
Instead of writing an entirely new constructor for the subclass, let's write it by calling the parent's
constructor explicitly and then doing whatever is necessary in addition for instantiation of the subclass.
Here's a simple example −
class Name {
var $_firstName;
var $_lastName;
$this->_firstName = $first_name;
$this->_lastName = $last_name;
function toString() {
var $_middleInitial;
Name::Name($first_name, $last_name);
$this->_middleInitial = $middle_initial;
function toString() {
In this example, we have a parent class (Name), which has a two-argument constructor, and a subclass
(NameSub1), which has a three-argument constructor. The constructor of NameSub1 functions by calling
its parent constructor explicitly using the :: syntax (passing two of its arguments along) and then setting
an additional field. Similarly, NameSub1 defines its non constructor toString() function in terms of the
parent function that it overrides.
A constructor can be defined with the same name as the name of a class. It is defined in above example
R eferences:
1. W3schools.com
2. Javapoint.com
3. Php.net
4. Tutorialspoint.com
5. Wordpress.org
Thankful to so many online resources