Académique Documents
Professionnel Documents
Culture Documents
PHP is a server scripting language, and a powerful tool for making dynamic
and interactive Web pages.
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo "My first PHP script!";
?>
</body>
</html>
PHP 7 has improved Error Handling, supports stricter Type Declarations and
supports new operators, methods and properties.
PHP 5 Introduction
PHP scripts are executed on the server.
What You Should Already Know
Before you continue you should have a basic understanding of the following:
HTML
CSS
JavaScript
What is PHP?
PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source scripting language
PHP scripts are executed on the server
PHP is free to download and use
Why PHP?
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases
PHP is free. Download it from the official PHP resource: www.php.net
PHP is easy to learn and runs efficiently on the server side
PHP 5 Installation
What Do I Need?
To start using PHP, you can:
Just create some .php files, place them in your web directory, and the server
will automatically parse them for you.
PHP 5 Syntax
A PHP script is executed on the server, and the plain HTML result is sent
back to the browser.
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text "Hello World!" on a web page:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
In the example below, all three echo statements below are legal (and equal):
Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
In the example below, only the first statement will display the value of the
$color variable (this is because $color, $COLOR, and $coLOR are treated as
three different variables):
Example
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
PHP 5 Variables
Variables are "containers" for storing information.
After the execution of the statements above, the variable $txt will hold the
value Hello world!, the variable $x will hold the value 5, and the
variable $y will hold the value 10.5.
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring
a variable. It is created the moment you first assign a value to it.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different
variables)
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>
The following example will produce the same output as the example above:
Example
<?php
$txt = "W3Schools.com";
echo "I love " . $txt . "!";
?>
Example
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
Note: You will learn more about the echo statement and how to output data to
the screen in the next chapter.
PHP automatically converts the variable to the correct data type, depending on
its value.
In other languages such as C, C++, and Java, the programmer must declare
the name and type of the variable before using it.
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be
referenced/used.
local
global
static
Example
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function:
Example
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
You can have local variables with the same name in different functions, because
local variables are only recognized by the function in which they are declared.
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
Example
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the
information it contained from the last time the function was called.
In this tutorial we use echo (and print) in almost every example. So, this
chapter contains a little more info about those two output statements.
PHP echo and print Statements
echo and print are more or less the same. They are both used to output data
to the screen.
The differences are small: echo has no return value while print has a return
value of 1 so it can be used in expressions. echo can take multiple parameters
(although such usage is rare) while print can take one argument. echo is
marginally faster than print.
Display Text
The following example shows how to output text with the echo command
(notice that the text can contain HTML markup):
Example
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
Display Variables
The following example shows how to output text and variables with
the echo statement:
Example
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
echo "<h2>" . $txt1 . "</h2>";
echo "Study PHP at " . $txt2 . "<br>";
echo $x + $y;
?>
Display Text
The following example shows how to output text with the print command
(notice that the text can contain HTML markup):
Example
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
Display Variables
The following example shows how to output text and variables with
the print statement:
Example
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;
print "<h2>" . $txt1 . "</h2>";
print "Study PHP at " . $txt2 . "<br>";
print $x + $y;
?>
PHP 5 Data Types
Variables can store data of different types, and different data types can do
different things.
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.
Example
<?php
$x = 5985;
var_dump($x);
?>
PHP Float
A float (floating point number) is a number with a decimal point or a number in
exponential form.
In the following example $x is a float. The PHP var_dump() function returns the
data type and value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about
conditional testing in a later chapter of this tutorial.
PHP Array
An array stores multiple values in one single variable.
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
You will learn a lot more about arrays in later chapters of this tutorial.
PHP Object
An object is a data type which stores data and information on how to process
that data.
First we must declare a class of object. For this, we use the class keyword. A
class is a structure that can contain properties and methods:
Example
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
// create an object
$herbie = new Car();
A variable of data type NULL is a variable that has no value assigned to it.
Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
PHP Resource
The special resource type is not an actual data type. It is the storing of a
reference to functions and resources external to PHP.
We will not talk about the resource type here, since it is an advanced topic.
PHP 5 Strings
A string is a sequence of characters, like "Hello world!".
The example below returns the length of the string "Hello world!":
Example
<?php
echo strlen("Hello world!"); // outputs 12
?>
Example
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
Reverse a String
The PHP strrev() function reverses a string:
Example
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
The example below searches for the text "world" in the string "Hello world!":
Example
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
Example
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
The PHP string reference contains description and example of use, for each
function!
PHP 5 Constants
Constants are like variables except that once they are defined they cannot
be changed or undefined.
PHP Constants
A constant is an identifier (name) for a simple value. The value cannot be
changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
Note: Unlike variables, constants are automatically global across the entire
script.
Syntax
define(name, value, case-insensitive)
Parameters:
Example
<?php
define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;
?>
Example
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
PHP 5 Operators
PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
The basic assignment operator in PHP is "=". It means that the left operand
gets set to the value of the assignment expression on the right.
PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or
string):
The example below will output "Have a good day!" if the current time (HOUR) is
less than 20:
Example
<?php
$t = date("H");
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less
than 20, and "Have a good night!" otherwise:
Example
<?php
$t = date("H");
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is
less than 10, and "Have a good day!" if the current time is less than 20.
Otherwise it will output "Have a good night!":
Example
<?php
$t = date("H");
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
Example
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and
over again in a row. Instead of adding several almost equal code-lines in a
script, we can use loops to perform a task like this.
Syntax
while (condition is true) {
code to be executed;
}
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop
will continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will
increase by 1 each time the loop runs ($x++):
Example
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Syntax
do {
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while
loop will write some output, and then increment the variable $x with 1. Then
the condition is checked (is $x less than, or equal to 5?), and the loop will
continue to run as long as $x is less than, or equal to 5:
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Notice that in a do while loop the condition is tested AFTER executing the
statements within the loop. This means that the do while loop would execute
its statements at least once, even if the condition is false the first time.
The example below sets the $x variable to 6, then it runs the loop, and then
the condition is checked:
Example
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The for loop and the foreach loop will be explained in the next chapter.
Syntax
for (init counter; test counter; increment counter) {
code to be executed;
}
Parameters:
Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to
$value and the array pointer is moved by one, until it reaches the last array
element.
The following example demonstrates a loop that will output the values of the
given array ($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
Syntax
function functionName() {
code to be executed;
}
Note: A function name can start with a letter or underscore (not a number).
Tip: Give the function a name that reflects what the function does!
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 has a function with two arguments ($fname and $year):
Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
Example
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Example
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
PHP 5 Arrays
An array stores multiple values in one single variable:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?
An array can hold many values under a single name, and you can access the
values by referring to an index number.
The index can be assigned automatically (index always starts at 0), like this:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array named $cars, assigns three
elements to it, and then prints a text containing the array values:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Multidimensional Arrays
Multidimensional arrays will be explained in the PHP advanced section.
The reference contains a brief description, and examples of use, for each
function!
PHP 5 Sorting Arrays
The elements in an array can be sorted in alphabetical or numerical order,
descending or ascending.
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>
The following example sorts the elements of the $numbers array in ascending
numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
?>
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>
The following example sorts the elements of the $numbers array in descending
numerical order:
Example
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>
$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.
PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global
variables from anywhere in the PHP script (also from within functions or
methods).
The example below shows how to use the super global variable $GLOBALS:
Example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
In the example above, since z is a variable present within the $GLOBALS array,
it is also accessible from outside the function!
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations.
The example below shows how to use some of the elements in $_SERVER:
Example
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
The following table lists the most important elements that can go inside
$_SERVER:
Element/Code Description
PHP $_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form.
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>
PHP $_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>
<?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>
PHP $_GET
PHP $_GET can also be used to collect form data after submitting an HTML form
with method="get".
</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>
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>
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:
<html>
<body>
</body>
</html>
Welcome John
Your email address is john.doe@example.com
The same result could also be achieved using the HTTP GET method:
Example
<html>
<body>
<html>
<body>
</body>
</html>
The code above is quite simple. However, the most important thing is missing.
You need to validate form data to protect your script from malicious code.
This page does not contain any form validation, it just shows how you can send
and retrieve form data.
However, the next pages will show how to process PHP forms with security in
mind! Proper validation of form data is important to protect your form from
hackers and spammers!
Both GET and POST are treated as $_GET and $_POST. These are superglobals,
which means that they are always accessible, regardless of scope - and you can
access them from any function, class or file without having to do anything
special.
$_GET is an array of variables passed to the current script via the URL
parameters.
$_POST is an array of variables passed to the current script via the HTTP POST
method.
When to use GET?
Information sent from a form with the GET method is visible to everyone (all
variable names and values are displayed in the URL). GET also has limits on the
amount of information to send. The limitation is about 2000 characters.
However, because the variables are displayed in the URL, it is possible to
bookmark the page. This can be useful in some cases.
Note: GET should NEVER be used for sending passwords or other sensitive
information!
However, because the variables are not displayed in the URL, it is not possible
to bookmark the page.
Next, lets see how we can process PHP forms the secure way!
Form Validation
This and the next chapters show how to use PHP to validate form data.
The HTML form we will be working at in these chapters, contains various input
fields: required and optional text fields, radio buttons, and a submit button:
Text Fields
The name, email, and website fields are text input elements, and the comment
field is a textarea. The HTML code looks like this:
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
When the form is submitted, the form data is sent with method="post".
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page
itself, instead of jumping to a different page. This way, the user will get error
messages on the same page as the form.
What is the htmlspecialchars() function?
If PHP_SELF is used in your page then a user can enter a slash (/) and then
some Cross Site Scripting (XSS) commands to execute.
Now, if a user enters the normal URL in the address bar like
"http://www.example.com/test_form.php", the above code will be translated to:
So far, so good.
However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/scr
ipt%3E
This code adds a script tag and an alert command. And when the page loads,
the JavaScript code will be executed (the user will see an alert box). This is just
a simple and harmless example how the PHP_SELF variable can be exploited.
Be aware of that any JavaScript code can be added inside the <script>
tag! A hacker can redirect the user to a file on another server, and that file can
hold malicious code that can alter the global variables or submit the form to
another address to save the user data, for example.
When we use the htmlspecialchars() function; then if a user tries to submit the
following in a text field:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code,
like this:
<script>location.href('http://www.hacked.com')</script>
The code is now safe to be displayed on a page or inside an e-mail.
We will also do two more things when the user submits the form:
1. Strip unnecessary characters (extra space, tab, newline) from the user
input data (with the PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP
stripslashes() function)
The next step is to create a function that will do all the checking for us (which is
much more convenient than writing the same code over and over again).
Now, we can check each $_POST variable with the test_input() function, and
the script looks like this:
Example
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Notice that at the start of the script, we check whether the form has been
submitted using $_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is
POST, then the form has been submitted - and it should be validated. If it has
not been submitted, skip the validation and display a blank form.
However, in the example above, all input fields are optional. The script works
fine even if the user does not enter any data.
The next step is to make input fields required and create error messages if
needed.
In the following code we have added some new variables: $nameErr, $emailErr,
$genderErr, and $websiteErr. These error variables will hold error messages for
the required fields. We have also added an if else statement for each $_POST
variable. This checks if the $_POST variable is empty (with the
PHP empty() function). If it is empty, an error message is stored in the different
error variables, and if it is not empty, it sends the user input data through
the test_input() function:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
Example
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])
;?>">
</form>
The next step is to validate the input data, that is "Does the Name field contain
only letters and whitespace?", and "Does the E-mail field contain a valid e-mail
address syntax?", and if filled out, "Does the Website field contain a valid
URL?".
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
The preg_match() function searches a string for pattern, returning true if the
pattern exists, and false otherwise.
In the code below, if the e-mail address is not well-formed, then store an error
message:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
PHP - Validate URL
The code below shows a way to check if a URL address syntax is valid (this
regular expression also allows dashes in the URL). If the URL address syntax is
not valid, then store an error message:
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
Example
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also
allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
Then, we also need to show which radio button that was checked. For this, we
must manipulate the checked attribute (not the value attribute for radio
buttons):
Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="other") echo "checked";?>
value="other">Other
However, sometimes you want to store values with more than one key.
We can store the data from the table above in a two-dimensional array, like
this:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Now the two-dimensional $cars array contains four arrays, and it has two
indices: row and column.
To get access to the elements of the $cars array we must point to the two
indices (row and column):
Example
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
We can also put a for loop inside another for loop to get the elements of the
$cars array (we still have to point to the two indices):
Example
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
Syntax
date(format,timestamp)
Parameter Description
Here are some characters that are commonly used for dates:
Other characters, like"/", ".", or "-" can also be inserted between the characters
to add additional formatting.
Example
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
PHP Tip - Automatic Copyright Year
Use the date() function to automatically update the copyright year on your
website:
Example
© 2010-<?php echo date("Y");?>
The example below outputs the current time in the specified format:
Example
<?php
echo "The time is " . date("h:i:sa");
?>
Note that the PHP date() function will return the current date/time of the
server!
So, if you need the time to be correct according to a specific location, you can
set a timezone to use.
The example below sets the timezone to "America/New_York", then outputs the
current time in the specified format:
Example
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
The mktime() function returns the Unix timestamp for a date. The Unix
timestamp contains the number of seconds between the Unix Epoch (January 1
1970 00:00:00 GMT) and the time specified.
Syntax
mktime(hour,minute,second,month,day,year)
The example below creates a date and time from a number of parameters in
the mktime() function:
Example
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
The example below creates a date and time from the strtotime() function:
Example
<?php
$d=strtotime("10:30pm April 15 2014");
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
PHP is quite clever about converting a string to a date, so you can put in various
values:
Example
<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>
However, strtotime() is not perfect, so remember to check the strings you put
in there.
The example below outputs the number of days until 4th of July:
Example
<?php
$d1=strtotime("July 04");
$d2=ceil(($d1-time())/60/60/24);
echo "There are " . $d2 ." days until 4th of July.";
?>
The reference contains a brief description, and examples of use, for each
function!
Including files is very useful when you want to include the same PHP, HTML,
or text on multiple pages of a website.
PHP include and require Statements
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:
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';
<?php
echo "<p>Copyright © 1999-" . date("Y") . " W3Schools.com</p>";
?>
To include the footer file in a page, use the include statement:
Example
<html>
<body>
</body>
</html>
Example 2
Assume we have a standard menu file called "menu.php":
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
All pages in the Web site should use this menu file. Here is how it can be done
(we are using a <div> element so that the menu easily can be styled with CSS
later):
Example
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
Example 3
Assume we have a file called "vars.php", with some variables defined:
<?php
$color='red';
$car='BMW';
?>
Then, if we include the "vars.php" file, the variables can be used in the calling
file:
Example
<html>
<body>
</body>
</html>
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
therequire statement returned a fatal error:
Example
<html>
<body>
</body>
</html>
Use include when the file is not required and application should continue when
file is not found.
File handling is an important part of any web application. You often need to
open and process a file for different tasks.
Assume we have a text file called "webdictionary.txt", stored on the server, that
looks like this:
The PHP code to read the file and write it to the output buffer is as follows
(the readfile() function returns the number of bytes read on success):
Example
<?php
echo readfile("webdictionary.txt");
?>
The readfile() function is useful if all you want to do is open up a file and read
its contents.
The next chapters will teach you more about file handling.
The first parameter of fopen() contains the name of the file to be opened and
the second parameter specifies in which mode the file should be opened. The
following example also generates a message if the fopen() function is unable to
open the specified file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Tip: The fread() and the fclose() functions will be explained below.
Modes Description
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
It's a good programming practice to close all files after you have finished with
them. You don't want an open file running around on your server taking up
resources!
The fclose() requires the name of the file (or a variable that holds the
filename) we want to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
The example below outputs the first line of the "webdictionary.txt" file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
Note: After a call to the fgets() function, the file pointer has moved to the
next line.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-
file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
Note: After a call to the fgetc() function, the file pointer moves to the next
character.
If you use fopen() on a file that does not exist, it will create it, given that the
file is opened for writing (w) or appending (a).
The example below creates a new file called "testfile.txt". The file will be created
in the same directory where the PHP code resides:
Example
$myfile = fopen("testfile.txt", "w")
The first parameter of fwrite() contains the name of the file to write to and
the second parameter is the string to be written.
The example below writes a couple of names into a new file called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the
file we sent the string $txt that first contained "John Doe" and second contained
"Jane Doe". After we finished writing, we closed the file using
the fclose() function.
John Doe
Jane Doe
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we
open an existing file for writing. All the existing data will be ERASED and we
start with an empty file.
In the example below we open our existing file "newfile.txt", and write some
new data into it:
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, both John and Jane have vanished, and
only the data we just wrote is present:
Mickey Mouse
Minnie Mouse
However, with ease comes danger, so always be careful when allowing file
uploads!
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Without the requirements above, the file upload will not work.
The type="file" attribute of the <input> tag shows the input field as a
file-select control, with a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create
next.
<?php
$target_dir = "uploads/";
$target_file = $target_dir .
basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType
= strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
Note: You will need to create a new directory called "uploads" in the directory
where "upload.php" file resides. The uploaded files will be saved there.
First, we will check if the file already exists in the "uploads" folder. If it does, an
error message is displayed, and $uploadOk is set to 0:
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
Now, we want to check the size of the file. If the file is larger than 500KB, an
error message is displayed, and $uploadOk is set to 0:
PHP 5 Cookies
A cookie is often used to identify a user.
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
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
PHP Create/Retrieve a Cookie
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>
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the
cookie, and automatically decoded when received (to prevent URLencoding,
use setrawcookie() instead).
<?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
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Check if Cookies are Enabled
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>
PHP 5 Sessions
A session is a way to store information (in variables) to be used across
multiple pages.
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>
Note: The session_start() function must be the very first thing in your
document. Before any HTML tags.
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>
Most sessions set a user-key on the user's computer that looks something like
this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on
another page, it scans the computer for a user-key. If there is a match, it
accesses that session, if not, it starts a new session.
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>
PHP Filters
Validating data = Determine if the data is in proper form.
The PHP filter extension has many of the functions needed for checking user
input, and is designed to make data validation easier and quicker.
The filter_list() function can be used to list what the PHP filter extension
offers:
Example
<table>
<tr>
<td>Filter Name</td>
<td>Filter ID</td>
</tr>
<?php
foreach (filter_list() as $id =>$filter) {
echo '<tr><td>' . $filter . '</td><td>' . filter_id($filter)
. '</td></tr>';
}
?>
</table>
Example
<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?>
Validate an Integer
The following example uses the filter_var() function to check if the variable
$int is an integer. If $int is an integer, the output of the code below will be:
"Integer is valid". If $int is not an integer, the output will be: "Integer is not
valid":
Example
<?php
$int = 100;
Example
<?php
$int = 0;
if (filter_var($int, FILTER_VALIDATE_INT) === 0 || !filter_var($int,
FILTER_VALIDATE_INT) === false) {
echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>
Validate an IP Address
The following example uses the filter_var() function to check if the variable
$ip is a valid IP address:
Example
<?php
$ip = "127.0.0.1";
Example
<?php
$email = "john.doe@example.com";
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
Example
<?php
$url = "https://www.w3schools.com";
// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>
Example
<?php
$int = 122;
$min = 1;
$max = 200;
if (filter_var($int,
FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=
>$max))) === false) {
echo("Variable value is not within the legal range");
} else {
echo("Variable value is within the legal range");
}
?>
Example
<?php
$ip = "2001:0db8:85a3:08d3:1319:8a2e:0370:7334";
Example
<?php
$url = "https://www.w3schools.com";
Example
<?php
$str = "<h1>Hello WorldÆØÅ!</h1>";
This tutorial contains some of the most common error checking methods in PHP.
<?php
$file=fopen("welcome.txt","r");
?>
If the file does not exist you might get an error like this:
To prevent the user from getting an error message like the one above, we test
whether the file exist before we try to access it:
<?php
if(!file_exists("welcome.txt")) {
die("File not found");
} else {
$file=fopen("welcome.txt","r");
}
?>
Now if the file does not exist you get an error like this:
The code above is more efficient than the earlier code, because it uses a simple
error handling mechanism to stop the script after the error.
However, simply stopping the script is not always the right way to go. Let's take
a look at alternative PHP functions for handling errors.
This function must be able to handle a minimum of two parameters (error level
and error message) but can accept up to five parameters (optionally: file, line-
number, and the error context):
Syntax
error_function(error_level,error_message,
error_file,error_line,error_context)
Parameter Description
error_level Required. Specifies the error report level for the user-defined
error. Must be a value number. See table below for possible
error report levels
4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can
be caught by a user defined handle (see also
set_error_handler())
The code above is a simple error handling function. When it is triggered, it gets
the error level and an error message. It then outputs the error level and
message and terminates the script.
Now that we have created an error handling function we need to decide when it
should be triggered.
It is possible to change the error handler to apply for only some errors, that
way the script can handle different errors in different ways. However, in this
example we are going to use our custom error handler for all errors:
set_error_handler("customError");
Example
Testing the error handler by trying to output variable that does not exist:
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr";
}
//trigger error
echo($test);
?>
The output of the code above should be something like this:
Trigger an Error
In a script where users can input data it is useful to trigger errors when an
illegal input occurs. In PHP, this is done by the trigger_error()function.
Example
In this example an error occurs if the "test" variable is bigger than "1":
<?php
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below");
}
?>
Example
In this example an E_USER_WARNING occurs if the "test" variable is bigger
than "1". If an E_USER_WARNING occurs we will use our custom error handler
and end the script:
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
//trigger error
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
Now that we have learned to create our own errors and how to trigger them,
lets take a look at error logging.
Error Logging
By default, PHP sends an error log to the server's logging system or a file,
depending on how the error_log configuration is set in the php.ini file. By using
the error_log() function you can send error logs to a specified file or a remote
destination.
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"someone@example.com","From: webmaster@example.com");
}
//trigger error
$test=2;
if ($test>=1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
And the mail received from the code above looks like this:
This should not be used with all errors. Regular errors should be logged on the
server using the default PHP logging system.
What is an Exception
With PHP 5 came a new object oriented way of dealing with errors.
Exception handling is used to change the normal flow of the code execution if a
specified error (exceptional) condition occurs. This condition is called an
exception.
Note: Exceptions should only be used with error conditions, and should not be
used to jump to another place in the code at a specified point.
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception
checkNum(2);
?>
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
Example explained:
The code above throws an exception and catches it:
However, one way to get around the "every throw must have a catch" rule is to
set a top level exception handler to handle errors that slip through.
The custom exception class inherits the properties from PHP's exception class
and you can add custom functions to it.
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this-
>getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example...com";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
The new class is a copy of the old exception class with an addition of the
errorMessage() function. Since it is a copy of the old class, and it inherits the
properties and methods from the old class, we can use the exception class
methods like getLine() and getFile() and getMessage().
Example explained:
The code above throws an exception and catches it with a custom exception
class:
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this-
>getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}
$email = "someone@example.com";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
//check for "example" in mail address
if(strpos($email, "example") !== FALSE) {
throw new Exception("$email is an example e-mail");
}
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
Example explained:
The code above tests two conditions and throws an exception if any of the
conditions are not met:
If the exception thrown were of the class customException and there were no
customException catch, only the base exception catch, the exception would be
handled there.
Re-throwing Exceptions
Sometimes, when an exception is thrown, you may wish to handle it differently
than the standard way. It is possible to throw an exception a second time within
a "catch" block.
A script should hide system errors from users. System errors may be important
for the coder, but are of no interest to the user. To make things easier for the
user you can re-throw the exception with a user friendly message:
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = $this->getMessage().' is not a valid E-Mail address.';
return $errorMsg;
}
}
$email = "someone@example.com";
try {
try {
//check for "example" in mail address
if(strpos($email, "example") !== FALSE) {
//throw exception if email is not valid
throw new Exception($email);
}
}
catch(Exception $e) {
//re-throw exception
throw new customException($email);
}
}
Example explained:
The code above tests if the email-address contains the string "example" in it, if
it does, the exception is re-thrown:
If the exception is not caught in its current "try" block, it will search for a catch
block on "higher levels".
<?php
function myException($exception) {
echo "<b>Exception:</b> " . $exception->getMessage();
}
set_exception_handler('myException');
In the code above there was no "catch" block. Instead, the top level exception
handler triggered. This function should be used to catch uncaught exceptions.
What is MySQL?
MySQL is a database system used on the web
MySQL is a database system that runs on a server
MySQL is ideal for both small and large applications
MySQL is very fast, reliable, and easy to use
MySQL uses standard SQL
MySQL compiles on a number of platforms
MySQL is free to download and use
MySQL is developed, distributed, and supported by Oracle Corporation
MySQL is named after co-founder Monty Widenius's daughter: My
Databases are useful for storing information categorically. A company may have
a database with the following tables:
Employees
Products
Customers
Orders
The query above selects all the data in the "LastName" column from the
"Employees" table.
Another great thing about MySQL is that it can be scaled down to support
embedded database applications.
Earlier versions of PHP used the MySQL extension. However, this extension
was deprecated in 2012.
PDO will work on 12 different database systems, whereas MySQLi will only work
with MySQL databases.
So, if you have to switch your project to use another database, PDO makes the
process easy. You only have to change the connection string and a few queries.
With MySQLi, you will need to rewrite the entire code - queries included.
MySQLi (object-oriented)
MySQLi (procedural)
PDO
MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most
cases, when php5 mysql package is installed.
PDO Installation
For installation details, go to: http://php.net/manual/en/pdo.installation.php
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Note: In the PDO example above we have also specified a database
(myDB). PDO require a valid database to connect to. If no database is
specified, an exception is thrown.
Tip: A great benefit of PDO is that it has an exception class to handle any
problems that may occur in our database queries. If an exception is thrown
within the try{ } block, the script stops executing and flows directly to the first
catch(){ } block.
Example (PDO)
$conn = null;
// 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();
?>
Note: When you create a new database, you must only specify the first three
arguments to the mysqli object (servername, username and password).
Tip: If you have to use a specific port, add an empty string for the database-
name argument, like this: new mysqli("localhost", "username", "password", "",
port)
Example (MySQLi Procedural)
<?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);
?>
Example (PDO)
<?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;
?>
Tip: A great benefit of PDO is that it has exception class to handle any problems
that may occur in our database queries. If an exception is thrown within the
try{ } block, the script stops executing and flows directly to the first catch(){ }
block. In the catch block above we echo the SQL statement and the generated
error message.
We will create a table named "MyGuests", with five columns: "id", "firstname",
"lastname", "email" and "reg_date":
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.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
// 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);
?>
Example (PDO)
<?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;
?>
PHP Insert Data Into MySQL
Insert Data Into MySQL Using MySQLi and
PDO
After a database and a table have been created, we can start adding data in
them.
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.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
// 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);
?>
Example (PDO)
<?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);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// 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 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:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Example (MySQLi Procedural)
<?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);
?>
Example (PDO)
<?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);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
The following examples add three new records to the "MyGuests" table:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_close($conn);
?>
Example (PDO)
<?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;
?>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
$stmt->close();
$conn->close();
?>
This function binds the parameters to the SQL query and tells the database
what the parameters are. The "sss" argument lists the types of data that the
parameters are. The s character tells mysql that the parameter is a string.
i - integer
d - double
s - string
b - BLOB
By telling mysql what type of data to expect, we minimize the risk of SQL
injections.
Note: If we want to insert any data from external sources (like user input), it is
very important that the data is sanitized and validated.
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);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
// 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) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
First, we set up an SQL query that selects the id, firstname and lastname
columns from the MyGuests table. The next line of code runs the query and puts
the resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows
returned.
If there are more than zero rows returned, the function fetch_assoc() puts all
the results into an associative array that we can loop through. The while() loop
loops through the result set and outputs the data from the id, firstname and
lastname columns.
The following example shows the same as the example above, in the MySQLi
procedural way:
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);
?>
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
It selects the id, firstname and lastname columns from the MyGuests table and
displays it in an HTML table:
Example (PDO)
<?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();
The following examples delete the record with id=3 in the "MyGuests" table:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
$conn->close();
?>
// 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 (PDO)
<?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;
?>
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:
Example (MySQLi Object-oriented)
<?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();
?>
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
mysqli_close($conn);
?>
Example (PDO)
<?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);
// Prepare statement
$stmt = $conn->prepare($sql);
$conn = null;
?>
After the record is updated, the table will look like this:
The LIMIT clause makes it easy to code multi page results or pagination with
SQL, and is very useful on large tables. Returning a large number of records can
impact on performance.
Assume we wish to select all records from 1 - 30 (inclusive) from a table called
"Orders". The SQL query would then look like this:
When the SQL query above is run, it will return the first 30 records.
The SQL query below says "return only 10 records, start on record 16 (OFFSET
15)":
Notice that the numbers are reversed when you use a comma.
PHP XML Parsers
What is XML?
The XML language is a way to structure data for sharing across websites.
Several web technologies like RSS Feeds and Podcasts are written in XML.
XML is easy to create. It looks a lot like HTML, except that you make up your
own tags.
If you want to learn more about XML, please visit our XML tutorial.
Tree-Based Parsers
Event-Based Parsers
Tree-Based Parsers
Tree-based parsers holds the entire document in Memory and transforms the
XML document into a Tree structure. It analyzes the whole document, and
provides access to the Tree elements (DOM).
This type of parser is a better option for smaller XML documents, but not for
large XML document as it causes major performance issues.
SimpleXML
DOM
Event-Based Parsers
Event-based parsers do not hold the entire document in Memory, instead, they
read in one node at a time and allow you to interact with in real time. Once you
move onto the next node, the old one is thrown away.
This type of parser is well suited for large XML documents. It parses faster and
consumes less memory.
XMLReader
XML Expat Parser
SimpleXML turns an XML document into a data structure you can iterate
through like a collection of arrays and objects.
Compared to DOM or the Expat parser, SimpleXML takes a fewer lines of code
to read text data from an element.
Installation
As of PHP 5, the SimpleXML functions are part of the PHP core. No installation is
required to use these functions.
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";
Example
<?php
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";
Run example »
Error Handling Tip: Use the libxml functionality to retrieve all XML errors when
loading the document and then iterate over the errors. The following example
tries to load a broken XML string:
Example
<?php
libxml_use_internal_errors(true);
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<document>
<user>John Doe</wronguser>
<email>john@example.com</wrongemail>
</document>";
$xml = simplexml_load_string($myXMLData);
if ($xml === false) {
echo "Failed loading XML: ";
foreach(libxml_get_errors() as $error) {
echo "<br>", $error->message;
}
} else {
print_r($xml);
}
?>
Assume we have an XML file called "note.xml", that looks like this:
Example
<?php
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
print_r($xml);
?>
SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] => Reminder
[body] => Don't forget me this weekend! )
Tip: The next chapter shows how to get/retrieve node values from an XML file
with SimpleXML!
Tove
Jani
Reminder
Don't forget me this weekend!
Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
echo $xml->book[0]->title . "<br>";
echo $xml->book[1]->title;
?>
Everyday Italian
Harry Potter
Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) {
echo $books->title . ", ";
echo $books->author . ", ";
echo $books->year . ", ";
echo $books->price . "<br>";
}
?>
Example
<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
echo $xml->book[0]['category'] . "<br>";
echo $xml->book[1]->title['lang'];
?>
COOKING
en
en
en
en-us
en-us
<from>Jani</from>
The XML Expat Parser functions are part of the PHP core. There is no installation
needed to use these functions.
The XML File
The XML file "note.xml" will be used in the example below:
Example
<?php
// Initialize the XML parser
$parser=xml_parser_create();
// Read data
while ($data=fread($fp,4096)) {
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
Example explained:
Installation
The DOM parser functions are part of the PHP core. There is no installation
needed to use these functions.
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
print $xmlDoc->saveXML();
?>
If you select "View source" in the browser window, you will see the following
HTML:
The example above creates a DOMDocument-Object and loads the XML from
"note.xml" into it.
Then the saveXML() function puts the internal XML document into a string, so
we can output it.
$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item) {
print $item->nodeName . " = " . $item->nodeValue . "<br>";
}
?>
#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don't forget me this weekend!
#text =
In the example above you see that there are empty text nodes between each
element.
When XML generates, it often contains white-spaces between the nodes. The
XML DOM parser treats these as ordinary elements, and if you are not aware of
them, they sometimes cause problems.
AJAX Introduction
AJAX is about updating parts of a web page, without reloading the whole
page.
What is AJAX?
AJAX = Asynchronous JavaScript and XML.
Classic web pages, (which do not use AJAX) must reload the entire page if the
content should change.
Google Suggest
AJAX was made popular in 2005 by Google, with Google Suggest.
Google Suggest is using AJAX to create a very dynamic web interface: When
you start typing in Google's search box, a JavaScript sends the letters off to a
server and the server returns a list of suggestions.
First name:
Suggestions:
Example Explained
In the example above, when a user types a character in the input field, a
function called "showHint()" is executed.
Example
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
Code explanation:
First, check if the input field is empty (str.length == 0). If it is, clear the
content of the txtHint placeholder and exit the function.
$hint = "";
Example
Example
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
Code explanation:
First, check if person is selected. If no person is selected (str == ""), clear the
content of txtHint and exit the function. If a person is selected, do the following:
The source code in "getuser.php" runs a query against a MySQL database, and
returns the result in an HTML table:
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
Explanation: When the query is sent from the JavaScript to the PHP file, the
following happens:
Example
<html>
<head>
<script>
function showCD(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getcd.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="">Select a CD:</option>
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>
<div id="txtHint"><b>CD info will be listed here...</b></div>
</body>
</html>
Check if a CD is selected
Create an XMLHttpRequest object
Create the function to be executed when the server response is ready
Send the request off to a file on the server
Notice that a parameter (q) is added to the URL (with the content of the
dropdown list)
The PHP script loads an XML document, "cd_catalog.xml", runs a query against
the XML file, and returns the result as HTML:
<?php
$q=$_GET["q"];
$x=$xmlDoc->getElementsByTagName('ARTIST');
$cd=($y->childNodes);
for ($i=0;$i<$cd->length;$i++) {
//Process only element nodes
if ($cd->item($i)->nodeType==1) {
echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>
When the CD query is sent from the JavaScript to the PHP page, the following
happens:
The results in the example above are found in an XML file (links.xml). To make
this example small and simple, only six results are available.
<html>
<head>
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseTex
t;
document.getElementById("livesearch").style.border="1px solid
#A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>
</body>
</html>
If the input field is empty (str.length==0), the function clears the content of the
livesearch placeholder and exits the function.
If the input field is not empty, the showResult() function executes the following:
The source code in "livesearch.php" searches an XML file for titles matching the
search string and returns the result:
<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
If there is any text sent from the JavaScript (strlen($q) > 0), the following
happens:
<form>
<select onchange="showRSS(this.value)">
<option value="">Select an RSS-feed:</option>
<option value="Google">Google News</option>
<option value="ZDN">ZDNet News</option>
</select>
</form>
<br>
<div id="rssOutput">RSS-feed will be listed here...</div>
</body>
</html>
<?php
//get the q parameter from URL
$q=$_GET["q"];
When a request for an RSS feed is sent from the JavaScript, the following
happens:
<html>
<head>
<script>
function getVote(int) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("poll").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","poll_vote.php?vote="+int,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<form>
Yes:
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<br>No:
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>
</body>
</html>
if ($vote == 0) {
$yes = $yes + 1;
}
if ($vote == 1) {
$no = $no + 1;
}
<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>
The value is sent from the JavaScript, and the following happens:
0||0
The first number represents the "Yes" votes, the second number represents the
"No" votes.
Note: Remember to allow your web server to edit the text file. Do NOT give
everyone access, just the web server (PHP).
PHP 5 Array Functions
PHP Array Introduction
The array functions allow you to access and manipulate arrays.
Installation
The array functions are part of the PHP core. There is no installation needed to
use these functions.
Function Description
array_replace_recursive() Replaces the values of the first array with the values
from following arrays recursively
each() Returns the current key and value pair from an array
Calendar Functions
PHP Calendar Introduction
The calendar extension contains functions that simplifies converting between
different calendar formats.
It is based on the Julian Day Count, which is a count of days starting
from January 1st, 4713 B.C.
Note: To convert between calendar formats, you must first convert to Julian
Day Count, then to the calendar of your choice.
Note: The Julian Day Count is not the same as the Julian Calendar!
Installation
For these functions to work, you have to compile PHP with --enable-calendar.
The Windows version of PHP has built-in support for this extension.
Function Description
easter_days() Returns the number of days after March 21, that the
Easter Day is in a specified year
Note: These functions depend on the locale settings of your server. Remember
to take daylight saving time and leap years into consideration when working
with these functions.
Installation
The PHP date/time functions are part of the PHP core. No installation is required
to use these functions.
Runtime Configuration
The behavior of these functions is affected by settings in php.ini:
date.timezone The default timezone (used by all date/time "" PHP 5.1
functions)
date.default_latitude The default latitude (used by date_sunrise() and "31.7667" PHP 5.0
date_sunset())
Function Description
checkdate() Validates a Gregorian date
Constant Description
Installation
The PHP directory functions are part of the PHP core. No installation is required
to use these functions.
Function Description
The error functions allow us to define own error handling rules, and modify the
way the errors can be logged.
Installation
The PHP error functions are part of the PHP core. No installation is required to
use these functions.
Runtime Configuration
The behavior of the error functions is affected by settings in php.ini.
Function Description
2048 E_STRICT Enable to have PHP suggest changes to your code which
will ensure the best interoperability and forward
compatibility of your code (Since PHP 5 but not included
in E_ALL until PHP 5.4)
32767 E_ALL Enable all PHP errors and warnings (except E_STRICT in
versions < 5.4)
Filesystem Functions
PHP Filesystem Introduction
The filesystem functions allow you to access and manipulate the filesystem.
Installation
The filesystem functions are part of the PHP core. There is no installation
needed to use these functions.
On Windows platforms, both forward slash (/) and backslash (\) can be used.
Runtime Configuration
The behavior of the filesystem functions is affected by settings in php.ini.
user_agent NULL Defines the user agent for PHP to send PHP_INI_ALL
(available since PHP 4.3)
auto_detect_line_endings "0" When set to "1", PHP will examine the PHP_INI_ALL
data read by fgets() and file() to see if it
is using Unix, MS-Dos or Mac line-
ending characters (available since PHP
4.3)
PHP 5 Filesystem Functions
Function Description
fgetcsv() Parses a line from an open file, checking for CSV fields
fgetss() Returns a line, with HTML and PHP tags removed, from
an open file
fpassthru() Reads from an open file, until EOF, and writes the
result to the output buffer
Filter Functions
PHP Filter Introduction
This PHP filters is used to validate and filter data coming from insecure sources,
like user input.
Installation
As of PHP 5.2.0, the filter functions are enabled by default. There is no
installation needed to use these functions.
Runtime Configurations
The behavior of these functions is affected by settings in php.ini:
Name Description
filter.default Filter all $_GET, $_POST, $_COOKIE, $_REQUEST and $_SERVER data by this filter. A
the filter you like to use by default. See the filter list for the list of the filter names
filter.default_flags Default flags to apply when the default filter is set. This is set to FILTER_FLAG_NO_ENC
default for backwards compatibility reasons
Function Description
filter_input_array() Gets external variables (e.g. from form input) and optionally
filters them
Constant ID Description
FILTER_SANITIZE_FULL_SPECIAL_CHARS
FTP Functions
PHP FTP Introduction
The FTP functions give client access to file servers through the File Transfer
Protocol (FTP).
The FTP functions are used to open, login and close connections, as well as
upload, download, rename, delete, and get information on files from file
servers. Not all of the FTP functions will work with every server or return the
same results. The FTP functions became available with PHP 3.
If you only wish to read from or write to a file on an FTP server, consider using
the ftp:// wrapper with the Filesystem functions which provide a simpler and
more intuitive interface.
Installation
For these functions to work, you have to compile PHP with --enable-ftp.
The Windows version of PHP has built-in support for this extension.
PHP 5 FTP Functions
Function Description
HTTP Functions
PHP HTTP Introduction
The HTTP functions let you manipulate information sent to the browser by the
Web server, before any other output has been sent.
Installation
The HTTP functions are part of the PHP core. There is no installation needed to
use these functions.
setcookie() Defines a cookie to be sent along with the rest of the HTTP
headers
libxml Functions
PHP libxml Introduction
The libxml functions and constants are used together with SimpleXML, XSLT and
DOM functions.
Installation
These functions require the libxml package. Download at xmlsoft.org
PHP libxml Functions
PHP: indicates the earliest version of PHP that supports the function.
Function Description
Function Description
Mail Functions
PHP Mail Introduction
The mail() function allows you to send emails directly from a script.
Requirements
For the mail functions to be available, PHP requires an installed and working
email system. The program to be used is defined by the configuration settings
in the php.ini file.
Installation
The mail functions are part of the PHP core. There is no installation needed to
use these functions.
Runtime Configuration
The behavior of the mail functions is affected by settings in php.ini:
Function Description
Installation
The PHP math functions are part of the PHP core. No installation is required to
use these functions.
Function Description
Misc. Functions
PHP Miscellaneous Introduction
The misc. functions were only placed here because none of the other categories
seemed to fit.
Installation
The misc. functions are part of the PHP core. No installation is required to use
these functions.
Runtime Configuration
The behavior of the misc. functions is affected by settings in the php.ini file.
Function Description
CONNECTION_ABORTED
CONNECTION_NORMAL
CONNECTION_TIMEOUT
__COMPILER_HALT_OFFSET__ 5
MySQLi Functions
PHP MySQLi Introduction
PHP MySQLi = PHP MySQL Improved!
Note: The MySQLi extension is designed to work with MySQL version 4.1.13 or
newer.
Installation / Runtime Configuration
For the MySQLi functions to be available, you must compile PHP with support for
the MySQLi extension.
The MySQLi extension was introduced with PHP version 5.0.0. The MySQL
Native Driver was included in PHP version 5.3.0.
Function Description
mysqli_character_set_name() Returns the default character set for the database connection
mysqli_close() Closes a previously opened database connection
mysqli_connect_errno() Returns the error code from the last connection error
mysqli_connect_error() Returns the error description from the last connection error
mysqli_errno() Returns the last error code for the most recent function call
mysqli_error_list() Returns a list of errors for the most recent function call
mysqli_error() Returns the last error description for the most recent function call
mysqli_fetch_all() Fetches all result rows as an associative array, a numeric array, or
both
mysqli_fetch_field_direct() Returns meta-data for a single field in the result set, as an object
mysqli_fetch_fields() Returns an array of objects that represent the fields in a result set
mysqli_fetch_lengths() Returns the lengths of the columns of the current row in the result
set
mysqli_field_count() Returns the number of columns for the most recent query
mysqli_field_seek() Sets the field cursor to the given field offset
mysqli_get_host_info() Returns the MySQL server hostname and the connection type
mysqli_set_local_infile_default() Unsets user defined handler for load local infile command
mysqli_set_local_infile_handler() Set callback function for LOAD DATA LOCAL INFILE command
mysqli_sqlstate() Returns the SQLSTATE error code for the last MySQL operation
mysqli_use_result() Initiates the retrieval of a result set from the last query executed
using the mysqli_real_query()
mysqli_warning_count() Returns the number of warnings from the last query in the
connection
SimpleXML Functions
PHP SimpleXML Introduction
SimpleXML is an extension that allows us to easily manipulate and get XML
data.
SimpleXML turns an XML document into a data structure you can iterate
through like a collection of arrays and objects.
Installation
As of PHP 5, the SimpleXML functions are part of the PHP core. No installation is
required to use these functions.
getName() Returns the name of the XML tag referenced by the SimpleXML
element
getNamespaces() Returns the namespaces USED in document
Function Description
String Functions
PHP 5 String Functions
The PHP string functions are part of the PHP core. No installation is required to
use these functions.
Function Description
hebrevc() Converts Hebrew text to visual text and new lines (\n) into <br>
strchr() Finds the first occurrence of a string inside another string (alias of
strstr())
strcspn() Returns the number of characters found in a string before any part
of some specified characters are found
stristr() Finds the first occurrence of a string inside another string (case-
insensitive)
strripos() Finds the position of the last occurrence of a string inside another
string (case-insensitive)
strrpos() Finds the position of the last occurrence of a string inside another
string (case-sensitive)
substr_compare() Compares two strings from a specified start position (binary safe
and optionally case-sensitive)
Because it is an event-based, non validating parser, Expat is fast and well suited
for web applications.
The XML parser functions lets you create XML parsers and define handlers for
XML events.
Installation
The XML functions are part of the PHP core. There is no installation needed to
use these functions.
Constant
XML_ERROR_NONE (integer)
XML_ERROR_NO_MEMORY (integer)
XML_ERROR_SYNTAX (integer)
XML_ERROR_NO_ELEMENTS (integer)
XML_ERROR_INVALID_TOKEN (integer)
XML_ERROR_UNCLOSED_TOKEN (integer)
XML_ERROR_PARTIAL_CHAR (integer)
XML_ERROR_TAG_MISMATCH (integer)
XML_ERROR_DUPLICATE_ATTRIBUTE (integer)
XML_ERROR_JUNK_AFTER_DOC_ELEMENT (integer)
XML_ERROR_PARAM_ENTITY_REF (integer)
XML_ERROR_UNDEFINED_ENTITY (integer)
XML_ERROR_RECURSIVE_ENTITY_REF (integer)
XML_ERROR_ASYNC_ENTITY (integer)
XML_ERROR_BAD_CHAR_REF (integer)
XML_ERROR_BINARY_ENTITY_REF (integer)
XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (integer)
XML_ERROR_MISPLACED_XML_PI (integer)
XML_ERROR_UNKNOWN_ENCODING (integer)
XML_ERROR_INCORRECT_ENCODING (integer)
XML_ERROR_UNCLOSED_CDATA_SECTION (integer)
XML_ERROR_EXTERNAL_ENTITY_HANDLING (integer)
XML_OPTION_CASE_FOLDING (integer)
XML_OPTION_TARGET_ENCODING (integer)
XML_OPTION_SKIP_TAGSTART (integer)
XML_OPTION_SKIP_WHITE (integer)
Installation
For the Zip file functions to work on your server, these libraries must be
installed:
PHP 5+: Zip functions and the Zip library is not enabled by default and must be
downloaded from the links above. Use the --with-zip=DIRconfigure option to
include Zip support.
PHP 5+: Zip functions is not enabled by default, so the php_zip.dll and the
ZZIPlib library must be downloaded from the link above. php_zip.dll must be
enabled inside of php.ini.
To enable any PHP extension, the PHP extension_dir setting (in the php.ini file)
should be set to the directory where the PHP extensions are located. An
example extension_dir value is c:\php\ext.
PHP 5 Timezones
PHP Supported Timezones
Below is a complete list of the timezones supported by PHP, which are useful
with several PHP date functions.
Africa
America
Antarctica
Arctic
Asia
Atlantic
Australia
Europe
Indian
Pacific
Africa
America
America/Yakutat America/Yellowknife
Antarctica
Antarctica/Vosto
k
Arctic
Arctic/Longyearbyen
Asia
Asia/Yerevan
Atlantic
Atlantic/St_Hele Atlantic/Stanley
na
Australia
Europe
Indian
Indian/Reunion
Pacific
Pacific/Wallis Pacific/Yap
Javatpoint :
The $$var (double dollar) is a reference variable that stores the value of the $variable
inside it.
Example 1
1. <?php
2. $x = "abc";
3. $$x = 200;
4. echo $x."<br/>";
5. echo $$x."<br/>";
6. echo $abc;
7. ?>
Output:
In the above example, we have assigned a value to the variable x as abc. Value of
reference variable $$x is assigned as 200.
Example2
1. <?php
2. $x="U.P";
3. $$x="Lucknow";
4. echo $x. "<br>";
5. echo $$x. "<br>";
6. echo "Capital of $x is " . $$x;
7. ?>
Output:
In the above example, we have assigned a value to the variable x as U.P. Value of
reference variable $$x is assigned as Lucknow.
Output:
In the above example, we have assigned a value to the variable name Cat. Value of
reference variable ${$name} is assigned as Dog and ${${$name}} as Monkey.
Now we have printed the values as $name, ${$name}, $Cat, ${${$name}} and $Dog.
PHP Constants
PHP constants are name or identifier that can't be changed during the execution of the
script. PHP constants can be defined by 2 ways:
PHP constants follow the same PHP variable rules. For example, it can be started with letter
or underscore only.
File: constant1.php
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP");
3. echo MESSAGE;
4. ?>
Output:
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>
Output:
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>
Output:
File: constant4.php
1. <?php
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE;
4. ?>
Output:
Magic Constants
Magic constants are the predefined constants in PHP which get changed on the basis of their
use. They start with double underscore (__) and ends with double underscore.
They are similar to other predefined constants but as they change their values with the
context, they are called magic constants.
There are eight magical constants defined in the below table. They are case-insensitive.
Name Description
__FILE__ Represents full path and file name of the file. If it is used inside an
include, name of included file is returned.
__TRAIT__ Represents the trait name where it is used. If it is used outside of any
function, then it will return blank. It includes namespace it was
declared in.
__METHOD__ Represents the name of the class method where it is used. The method
name is returned as it was declared.
Example
Let's see an example for each of the above magical constants.
1. <?php
2. echo "<h3>Example for __LINE__</h3>";
3. echo "You are at line number " . __LINE__ . "<br><br>";// print Your current line number
i.e;3
4. echo "<h3>Example for __FILE__</h3>";
5. echo __FILE__ . "<br><br>";//print full path of file with .php extension
6. echo "<h3>Example for __DIR__</h3>";
7. echo __DIR__ . "<br><br>";//print full path of directory where script will be placed
8. echo dirname(__FILE__) . "<br><br>"; //its output is equivalent to above one.
9. echo "<h3>Example for __FUNCTION__</h3>";
10. //Using magic constant inside function.
11. function cash(){
12. echo 'the function name is '. __FUNCTION__ . "<br><br>";//the function name is cash.
13. }
14. cash();
15. //Using magic constant outside function gives the blank output.
16. function test_function(){
17. echo 'HYIIII';
18. }
19. test_function();
20. echo __FUNCTION__ . "<br><br>";//gives the blank output.
21.
22. echo "<h3>Example for __CLASS__</h3>";
23. class abc
24. {
25. public function __construct() {
26. ;
27. }
28. function abc_method(){
29. echo __CLASS__ . "<br><br>";//print name of the class abc.
30. }
31. }
32. $t = new abc;
33. $t->abc_method();
34. class first{
35. function test_first(){
36. echo __CLASS__;//will always print parent class which is first here.
37. }
38. }
39. class second extends first
40. {
41. public function __construct() {
42. ;
43. }
44. }
45. $t = new second;
46. $t->test_first();
47. echo "<h3>Example for __TRAIT__</h3>";
48. trait created_trait{
49. function abc(){
50. echo __TRAIT__;//will print name of the trait created_trait
51. }
52. }
53. class anew{
54. use created_trait;
55. }
56. $a = new anew;
57. $a->abc();
58. echo "<h3>Example for __METHOD__</h3>";
59. class meth{
60. public function __construct() {
61. echo __METHOD__ . "<br><br>";//print meth::__construct
62. }
63. public function meth_fun(){
64. echo __METHOD__;//print meth::meth_fun
65. }
66. }
67. $a = new meth;
68. $a->meth_fun();
69.
70. echo "<h3>Example for __NAMESPACE__</h3>";
71. class name{
72. public function __construct() {
73. echo 'This line will be printed on calling namespace';
74. }
75. }
76. $clas_name= __NAMESPACE__ .'\name';
77. $a = new $clas_name;
78. ?>
Output:
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as
argument list and return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive
function also.
Less Code: It saves a lot of code because you don't need to write the logic many times. By
the use of function, you can write the logic only once and reuse it.
Syntax
1. function functionname(){
2. //code to be executed
3. }
Note: Function name must be start with letter and underscore only like other labels in PHP. It can't
be start with numbers or special symbols.
File: functionarg.php
1. <?php
2. function sayHello($name){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Sonoo");
6. sayHello("Vimal");
7. sayHello("John");
8. ?>
Output:
Hello Sonoo
Hello Vimal
Hello John
File: functionarg2.php
1. <?php
2. function sayHello($name,$age){
3. echo "Hello $name, you are $age years old<br/>";
4. }
5. sayHello("Sonoo",27);
6. sayHello("Vimal",29);
7. sayHello("John",23);
8. ?>
Output:
By default, value passed to the function is call by value. To pass value as a reference, you
need to use ampersand (&) symbol before the argument name.
File: functionref.php
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>
Output:
File: functiondefaultarg.php
1. <?php
2. function sayHello($name="Sonoo"){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Rajesh");
6. sayHello();//passing no value
7. sayHello("John");
8. ?>
Output:
Hello Rajesh
Hello Sonoo
Hello John
File: functiondefaultarg.php
1. <?php
2. function cube($n){
3. return $n*$n*$n;
4. }
5. echo "Cube of 3 is: ".cube(3);
6. ?>
Output:
Cube of 3 is: 27
They are specified inside the parentheses, after the function name.
The output depends upon the dynamic values passed as the parameters into the function.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Parameter Addition and Subtraction Example</title>
5. </head>
6. <body>
7. <?php
8. //Adding two numbers
9. function add($x, $y) {
10. $sum = $x + $y;
11. echo "Sum of two numbers is = $sum <br><br>";
12. }
13. add(467, 943);
14.
15. //Subtracting two numbers
16. function sub($x, $y) {
17. $diff = $x - $y;
18. echo "Difference between two numbers is = $diff";
19. }
20. sub(943, 467);
21. ?>
22. </body>
23. </html>
Output:
1. <?php
2. //add() function with two parameter
3. function add($x,$y)
4. {
5. $sum=$x+$y;
6. echo "Sum = $sum <br><br>";
7. }
8. //sub() function with two parameter
9. function sub($x,$y)
10. {
11. $sub=$x-$y;
12. echo "Diff = $sub <br><br>";
13. }
14. //call function, get two argument through input box and click on add or sub button
15. if(isset($_POST['add']))
16. {
17. //call add() function
18. add($_POST['first'],$_POST['second']);
19. }
20. if(isset($_POST['sub']))
21. {
22. //call add() function
23. sub($_POST['first'],$_POST['second']);
24. }
25. ?>
26. <form method="post">
27. Enter first number: <input type="number" name="first"/><br><br>
28. Enter second number: <input type="number" name="second"/><br><br>
29. <input type="submit" name="add" value="ADDITION"/>
30. <input type="submit" name="sub" value="SUBTRACTION"/>
31. </form>
Output:
Example 1
In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Value' string. But, printing $str variable results 'Hello' only. It is because changes
are done in the local variable $str2 only. It doesn't reflect to $str variable.
1. <?php
2. function adder($str2)
3. {
4. $str2 .= 'Call By Value';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>
Output:
Hello
Example 2
Let's understand PHP call by value concept through another example.
1. <?php
2. function increment($i)
3. {
4. $i++;
5. }
6. $i = 10;
7. increment($i);
8. echo $i;
9. ?>
Output:
10
Example 1
In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Reference' string. Here, printing $str variable results 'This is Call By Reference'. It is
because changes are done in the actual variable $str.
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'This is ';
7. adder($str);
8. echo $str;
9. ?>
Output:
Example 2
Let's understand PHP call by reference concept through another example.
1. <?php
2. function increment(&$i)
3. {
4. $i++;
5. }
6. $i = 10;
7. increment($i);
8. echo $i;
9. ?>
Output:
11
Let' see the simple example of using PHP default arguments in function.
Example 1
1. <?php
2. function sayHello($name="Ram"){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Sonoo");
6. sayHello();//passing no value
7. sayHello("Vimal");
8. ?>
Output:
Hello Sonoo
Hello Ram
Hello Vimal
Since PHP 5, you can use the concept of default argument value with call by reference also.
Example 2
1. <?php
2. function greeting($first="Sonoo",$last="Jaiswal"){
3. echo "Greeting: $first $last<br/>";
4. }
5. greeting();
6. greeting("Rahul");
7. greeting("Michael","Clark");
8. ?>
Output:
Example 3
1. <?php
2. function add($n1=10,$n2=10){
3. $n3=$n1+$n2;
4. echo "Addition is: $n3<br/>";
5. }
6. add();
7. add(20);
8. add(40,40);
9. ?>
Output:
Addition is: 20
Addition is: 30
Addition is: 80
The 3 dot concept is implemented for variable length argument since PHP 5.6.
1. <?php
2. function add(...$numbers) {
3. $sum = 0;
4. foreach ($numbers as $n) {
5. $sum += $n;
6. }
7. return $sum;
8. }
9.
10. echo add(1, 2, 3, 4);
11. ?>
Output:
10
It is recommended to avoid recursive function call over 200 recursion level because it may
smash the stack and may cause the termination of script.
Output:
1
2
3
4
5
Output:
120
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
File: array2.php
1. <?php
2. $season[0]="summer";
3. $season[1]="winter";
4. $season[2]="spring";
5. $season[3]="autumn";
6. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
7. ?>
Output:
1st way:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>
Output:
Output:
PHP indexed array can store numbers, strings or any object. PHP indexed array is also
known as numeric array.
Definition
There are two ways to define indexed array:
1st way:
1. $size=array("Big","Medium","Short");
2nd way:
1. $size[0]="Big";
2. $size[1]="Medium";
3. $size[2]="Short";
Output:
File: array3.php
1. <?php
2. $size=array("Big","Medium","Short");
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>
Output:
1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>
Output:
Definition
There are two ways to define associative array:
1st way:
1. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
2nd way:
1. $salary["Sonoo"]="550000";
2. $salary["Vimal"]="250000";
3. $salary["Ratan"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
5. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
6. ?>
Output:
1. <?php
2. $salary["Sonoo"]="550000";
3. $salary["Vimal"]="250000";
4. $salary["Ratan"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
7. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
8. ?>
Output:
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. foreach($salary as $k => $v) {
4. echo "Key: ".$k." Value: ".$v."<br/>";
5. }
6. ?>
Output:
Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
PHP Multidimensional Array Example
Let's see a simple example of PHP multidimensional array to display following tabular data.
In this example, we are displaying 3 rows and 3 columns.
Id Name Salary
1 sonoo 400000
2 john 500000
3 rahul 300000
File: multiarray.php
1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
13. echo "<br/>";
14. }
15. ?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
PHP Array Functions
PHP provides various array functions to access and manipulate the elements of array. The
important PHP array functions are given below.
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>
Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>
Output:
Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )
Syntax
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>
Output:
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)
Syntax
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>
Output:
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
summer
winter
Syntax
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
winter
summer
Syntax
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>
Output:
Syntax
1. array array_intersect ( array $array1 , array $array2 [, array $... ] )
Example
1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>
Output:
sonoo
smith
PHP String
A PHP string is a sequence of characters i.e. used to store and manipulate text. There are 4
ways to specify string in PHP.
o single quoted
o double quoted
o heredoc syntax
o newdoc syntax (since PHP 5.3)
1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>
Output:
1. <?php
2. $str1='Hello text
3. multiple line
4. text within single quoted string';
5. $str2='Using double "quote" directly inside single quoted string';
6. $str3='Using escape sequences \n in single quoted string';
7. echo "$str1 <br/> $str2 <br/> $str3";
8. ?>
Output:
Note: In single quoted PHP strings, most escape sequences and variables will not be interpreted.
But, we can use single quote through \' and backslash through \\ inside single quoted PHP strings.
1. <?php
2. $num1=10;
3. $str1='trying variable $num1';
4. $str2='trying backslash n and backslash t inside single quoted string \n \t';
5. $str3='Using single quote \'my quote\' and \\backslash';
6. echo "$str1 <br/> $str2 <br/> $str3";
7. ?>
Output:
1. <?php
2. $str="Hello text within double quote";
3. echo $str;
4. ?>
Output:
Now, you can't use double quote directly inside double quoted string.
1. <?php
2. $str1="Using double "quote" directly inside double quoted string";
3. echo $str1;
4. ?>
Output:
We can store multiple line text, special characters and escape sequences in a double
quoted PHP string.
1. <?php
2. $str1="Hello text
3. multiple line
4. text within double quoted string";
5. $str2="Using double \"quote\" with backslash inside double quoted string";
6. $str3="Using escape sequences \n in double quoted string";
7. echo "$str1 <br/> $str2 <br/> $str3";
8. ?>
Output:
1. <?php
2. $num1=10;
3. echo "Number is: $num1";
4. ?>
Output:
Number is: 10
hebrevc() It is used to convert Hebrew text to visual text and new lines (\n)
into <br>.
hebrevc() It is used to convert Hebrew text to visual text and new lines (\n)
into <br>.
Syntax
Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtolower($str);
4. echo $str;
5. ?>
Output:
my name is khan
Syntax
Example
1. <?php
2. $str="My name is KHAN";
3. $str=strtoupper($str);
4. echo $str;
5. ?>
Output:
MY NAME IS KHAN
Syntax
Example
1. <?php
2. $str="my name is KHAN";
3. $str=ucfirst($str);
4. echo $str;
5. ?>
Output:
My name is KHAN
Syntax
Example
1. <?php
2. $str="MY name IS KHAN";
3. $str=lcfirst($str);
4. echo $str;
5. ?>
Output:
mY name IS KHAN
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=ucwords($str);
4. echo $str;
5. ?>
Output:
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strrev($str);
4. echo $str;
5. ?>
Output:
Syntax
Example
1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strlen($str);
4. echo $str;
5. ?>
Output:
24
PHP Math
PHP provides many predefined math constants and functions that can be used to perform
mathematical operations.
Syntax
1. <?php
2. echo (abs(-7)."<br/>"); // 7 (integer)
3. echo (abs(7)."<br/>"); //7 (integer)
4. echo (abs(-7.2)."<br/>"); //7.2 (float/double)
5. ?>
Output:
7
7
7.2
Syntax
1. <?php
2. echo (ceil(3.3)."<br/>");// 4
3. echo (ceil(7.333)."<br/>");// 8
4. echo (ceil(-4.8)."<br/>");// -4
5. ?>
Output:
4
8
-4
Syntax
1. <?php
2. echo (floor(3.3)."<br/>");// 3
3. echo (floor(7.333)."<br/>");// 7
4. echo (floor(-4.8)."<br/>");// -5
5. ?>
Output:
3
7
-5
PHP Math: sqrt() function
The sqrt() function returns square root of given argument.
Syntax
1. <?php
2. echo (sqrt(16)."<br/>");// 4
3. echo (sqrt(25)."<br/>");// 5
4. echo (sqrt(7)."<br/>");// 2.6457513110646
5. ?>
Output:
4
5
2.6457513110646
Syntax
1. <?php
2. echo (decbin(2)."<br/>");// 10
3. echo (decbin(10)."<br/>");// 1010
4. echo (decbin(22)."<br/>");// 10110
5. ?>
Output:
10
1010
10110
Syntax
1. <?php
2. echo (dechex(2)."<br/>");// 2
3. echo (dechex(10)."<br/>");// a
4. echo (dechex(22)."<br/>");// 16
5. ?>
Output:
2
a
16
Syntax
1. <?php
2. echo (decoct(2)."<br/>");// 2
3. echo (decoct(10)."<br/>");// 12
4. echo (decoct(22)."<br/>");// 26
5. ?>
Output:
2
12
26
1. <?php
2. $n1=10;
3. echo (base_convert($n1,10,2)."<br/>");// 1010
4. ?>
Output:
1010
Syntax
1. <?php
2. echo (bindec(10)."<br/>");// 2
3. echo (bindec(1010)."<br/>");// 10
4. echo (bindec(1011)."<br/>");// 11
5. ?>
Output:
2
10
11
Function Description
max() It is used to return the highest value in an array, or the highest value
of several specified values.
min() It returns the lowest value in an array, or the lowest value of several
specified values.
fmod() It is used to return the floating point remainder of the division of the
argument.
The form request may be get or post. To retrieve data from get request, we need to use
$_GET, for post request $_POST.
Let's see a simple example to receive data from get request in PHP.
File: form1.html
1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variable
3. echo "Welcome, $name";
4. ?>
Let's see a simple example to receive data from post request in PHP.
File: form1.html
1. <form action="login.php" method="post">
2. <table>
3. <tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
4. <tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
5. <tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
6. </table>
7. </form>
File: login.php
1. <?php
2. $name=$_POST["name"];//receiving name field value in $name variable
3. $password=$_POST["password"];//receiving password field value in $password variable
4.
5. echo "Welcome: $name, your password is: $password";
6. ?>
Output:
Advantage
Code Reusability: By the help of include and require construct, we can reuse HTML code or
PHP script in many PHP scripts.
File: menu.html
1. <a href="http://www.javatpoint.com">Home</a> |
2. <a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
3. <a href="http://www.javatpoint.com/java-tutorial">Java</a> |
4. <a href="http://www.javatpoint.com/html-tutorial">HTML</a>
File: include1.php
Output:
File: menu.html
1. <a href="http://www.javatpoint.com">Home</a> |
2. <a href="http://www.javatpoint.com/php-tutorial">PHP</a> |
3. <a href="http://www.javatpoint.com/java-tutorial">Java</a> |
4. <a href="http://www.javatpoint.com/html-tutorial">HTML</a>
File: require1.php
1. <?php require("menu.html"); ?>
2. <h1>This is Main Page</h1>
Output:
PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends
request to the server, cookie is embedded with request. Such way, cookie can be received
at the server side.
Syntax
1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Example
PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.
Example
Output:
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
File: cookie1.php
1. <?php
2. setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago
3. ?>
PHP Session
PHP session is used to store and pass information from one page to another temporarily
(until user close the website).
PHP session technique is widely used in shopping websites where we need to store and pass
cart information e.g. username, product code, product name, product price etc from one
page to another.
PHP session creates unique user id for each browser to recognize the user and avoid conflict
between multiple browsers.
Syntax
1. bool session_start ( void )
Example
1. session_start();
PHP $_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to set
and get session variable values.
1. $_SESSION["user"] = "Sachin";
1. echo $_SESSION["user"];
File: session3.php
1. <?php
2. session_start();
3. session_destroy();
4. ?>
Syntax
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resour
ce $context ]] )
Example
1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>
Syntax
Example
1. <?php
2. fclose($handle);
3. ?>
Syntax
Example
1. <?php
2. $filename = "c:\\myfile.txt";
3. $handle = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($handle, filesize($filename));//read file
6.
7. echo $contents;//printing data of file
8. fclose($handle);//close file
9. ?>
Output
Syntax
Example
1. <?php
2. $fp = fopen('data.txt', 'w');//open file in write mode
3. fwrite($fp, 'hello ');
4. fwrite($fp, 'php file');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>
Output
Syntax
Example
1. <?php
2. unlink('data.txt');
3.
4. echo "File deleted successfully";
5. ?>
Syntax
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resour
ce $context ]] )
Mode Description
r Opens file in read-only mode. It places the file pointer at the beginning of the file.
r+ Opens file in read-write mode. It places the file pointer at the beginning of the file.
w Opens file in write-only mode. It places the file pointer to the beginning of the file
and truncates the file to zero length. If file is not found, it creates a new file.
w+ Opens file in read-write mode. It places the file pointer to the beginning of the file
and truncates the file to zero length. If file is not found, it creates a new file.
a Opens file in write-only mode. It places the file pointer to the end of the file. If file
is not found, it creates a new file.
a+ Opens file in read-write mode. It places the file pointer to the end of the file. If file
is not found, it creates a new file.
x Creates and opens file in write-only mode. It places the file pointer at the
beginning of the file. If file is found, fopen() function returns FALSE.
x+ It is same as x but it creates and opens file in read-write mode.
c Opens file in write-only mode. If the file does not exist, it is created. If it exists, it
is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the
case with 'x'). The file pointer is positioned on the beginning of the file
o fread()
o fgets()
o fgetc()
Syntax
1. string fread (resource $handle , int $length )
Example
1. <?php
2. $filename = "c:\\file1.txt";
3. $fp = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($fp, filesize($filename));//read file
6.
7. echo "<pre>$contents</pre>";//printing data of file
8. fclose($fp);//close file
9. ?>
Output
Syntax
1. string fgets ( resource $handle [, int $length ] )
Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. echo fgets($fp);
4. fclose($fp);
5. ?>
Output
Syntax
1. string fgetc ( resource $handle )
Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. while(!feof($fp)) {
4. echo fgetc($fp);
5. }
6. fclose($fp);
7. ?>
Output
Syntax
Example
1. <?php
2. $fp = fopen('data.txt', 'w');//opens file in write-only mode
3. fwrite($fp, 'welcome ');
4. fwrite($fp, 'to php file write');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>
Output: data.txt
1. <?php
2. $fp = fopen('data.txt', 'w');//opens file in write-only mode
3. fwrite($fp, 'hello');
4. fclose($fp);
5.
6. echo "File written successfully";
7. ?>
Output: data.txt
hello
data.txt
Example
1. <?php
2. $fp = fopen('data.txt', 'a');//opens file in append mode
3. fwrite($fp, ' this is additional text ');
4. fwrite($fp, 'appending data');
5. fclose($fp);
6.
7. echo "File appended successfully";
8. ?>
Output: data.txt
PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is
deleted successfully otherwise FALSE.
Syntax
Output
PHP file upload features allows you to upload binary and text files both. Moreover, you can
have the full control over the file to be uploaded through PHP authentication and file
operation functions.
PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of $_FILES global,
we can get file name, file type, file size, temp file name and errors associated with file.
$_FILES['filename']['name']
returns file name.
$_FILES['filename']['type']
returns MIME type of the file.
$_FILES['filename']['size']
returns size of the file (in bytes).
$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the server.
$_FILES['filename']['error']
returns error code associated with this file.
move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough the POST
request. It moves the file if it is uploaded through the POST request.
Syntax
PHP Mail
PHP mail() function is used to send email in PHP. You can send text message, html message
and attachment with message using PHP mail() function.
1. bool mail ( string $to , string $subject , string $message [, string $additional_headers [, stri
ng $additional_parameters ]] )
$to: specifies receiver or receivers of the mail. The receiver must be specified one of the
following forms.
o user@example.com
o user@example.com, anotheruser@example.com
o User <user@example.com>
o User <user@example.com>, Another User <anotheruser@example.com>
$additional_headers (optional): specifies the additional headers such as From, CC, BCC
etc. Extra additional headers should also be separated with CRLF ( \r\n ).
If you run this code on the live server, it will send an email to the specified receiver.
1. <?php
2. $to = "abc@example.com";//change receiver address
3. $subject = "This is subject";
4. $message = "<h1>This is HTML heading</h1>";
5.
6. $header = "From:xyz@example.com \r\n";
7. $header .= "MIME-Version: 1.0 \r\n";
8. $header .= "Content-type: text/html;charset=UTF-8 \r\n";
9.
10. $result = mail ($to,$subject,$message,$header);
11.
12. if( $result == true ){
13. echo "Message sent successfully...";
14. }else{
15. echo "Sorry, unable to send mail...";
16. }
17. ?>
1. <?php
2. $to = "abc@example.com";
3. $subject = "This is subject";
4. $message = "This is a text message.";
5. # Open a file
6. $file = fopen("/tmp/test.txt", "r" );//change your file location
7. if( $file == false )
8. {
9. echo "Error in opening file";
10. exit();
11. }
12. # Read the file into a variable
13. $size = filesize("/tmp/test.txt");
14. $content = fread( $file, $size);
15.
16. # encode the data for safe transit
17. # and insert \r\n after every 76 chars.
18. $encoded_content = chunk_split( base64_encode($content));
19.
20. # Get a random 32 bit number using time() as seed.
21. $num = md5( time() );
22.
23. # Define the main headers.
24. $header = "From:xyz@example.com\r\n";
25. $header .= "MIME-Version: 1.0\r\n";
26. $header .= "Content-Type: multipart/mixed; ";
27. $header .= "boundary=$num\r\n";
28. $header .= "--$num\r\n";
29.
30. # Define the message section
31. $header .= "Content-Type: text/plain\r\n";
32. $header .= "Content-Transfer-Encoding:8bit\r\n\n";
33. $header .= "$message\r\n";
34. $header .= "--$num\r\n";
35.
36. # Define the attachment section
37. $header .= "Content-Type: multipart/mixed; ";
38. $header .= "name=\"test.txt\"\r\n";
39. $header .= "Content-Transfer-Encoding:base64\r\n";
40. $header .= "Content-Disposition:attachment; ";
41. $header .= "filename=\"test.txt\"\r\n\n";
42. $header .= "$encoded_content\r\n";
43. $header .= "--$num--";
44.
45. # Send email now
46. $result = mail ( $to, $subject, "", $header );
47. if( $result == true ){
48. echo "Message sent successfully...";
49. }else{
50. echo "Sorry, unable to send mail...";
51. }
52. ?>
o mysqli_connect()
o PDO::__construct()
PHP mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL database. It
returns resource if connection is established or null.
Syntax
PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if
connection is closed or false.
Syntax
Output:
Connected successfully
o mysqli_query()
o PDO::__query()
PHP MySQLi Create Database Example
Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {
8. die('Could not connect: ' . mysqli_connect_error());
9. }
10. echo 'Connected successfully<br/>';
11.
12. $sql = 'CREATE Database mydb';
13. if(mysqli_query( $conn,$sql)){
14. echo "Database mydb created successfully.";
15. }else{
16. echo "Sorry, database creation failed ".mysqli_error($conn);
17. }
18. mysqli_close($conn);
19. ?>
Output:
Connected successfully
Database mydb created successfully.
o mysqli_query()
o PDO::__query()
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $sql = "create table emp5(id INT AUTO_INCREMENT,name VARCHAR(20) NOT NULL,
14. emp_salary INT NOT NULL,primary key (id))";
15. if(mysqli_query($conn, $sql)){
16. echo "Table emp5 created successfully";
17. }else{
18. echo "Could not create table: ". mysqli_error($conn);
19. }
20.
21. mysqli_close($conn);
22. ?>
Output:
Connected successfully
Table emp5 created successfully
o mysqli_query()
o PDO::__query()
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $sql = 'INSERT INTO emp4(name,salary) VALUES ("sonoo", 9000)';
14. if(mysqli_query($conn, $sql)){
15. echo "Record inserted successfully";
16. }else{
17. echo "Could not insert record: ". mysqli_error($conn);
18. }
19.
20. mysqli_close($conn);
21. ?>
Output:
Connected successfully
Record inserted successfully
o mysqli_query()
o PDO::__query()
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $id=2;
14. $name="Rahul";
15. $salary=80000;
16. $sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";
17. if(mysqli_query($conn, $sql)){
18. echo "Record updated successfully";
19. }else{
20. echo "Could not update record: ". mysqli_error($conn);
21. }
22.
23. mysqli_close($conn);
24. ?>
Output:
Connected successfully
Record updated successfully
o mysqli_query()
o PDO::__query()
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $id=2;
14. $sql = "delete from emp4 where id=$id";
15. if(mysqli_query($conn, $sql)){
16. echo "Record deleted successfully";
17. }else{
18. echo "Could not deleted record: ". mysqli_error($conn);
19. }
20.
21. mysqli_close($conn);
22. ?>
Output:
Connected successfully
Record deleted successfully
o mysqli_query()
o PDO::__query()
Output:
Connected successfully
EMP ID :1
EMP NAME : ratan
EMP SALARY : 9000
--------------------------------
EMP ID :2
EMP NAME : karan
EMP SALARY : 40000
--------------------------------
EMP ID :3
EMP NAME : jai
EMP SALARY : 90000
--------------------------------
The order by clause is used to fetch data in ascending order or descending order on the
basis of column.
Let's see the query to select data from emp4 table in ascending order on the basis of name
column.
Let's see the query to select data from emp4 table in descending order on the basis of name
column.
Output:
Connected successfully
EMP ID :3
EMP NAME : jai
EMP SALARY : 90000
--------------------------------
EMP ID :2
EMP NAME : karan
EMP SALARY : 40000
--------------------------------
EMP ID :1
EMP NAME : ratan
EMP SALARY : 9000
--------------------------------
PHP Programs
Sum of Digits
To find sum of digits of a number just add all the digits.
For example,
1. 14597 = 1 + 4 + 5 + 9 + 7
2. 14597 = 26
Logic:
Example:
1. <?php
2. $num = 14597;
3. $sum=0; $rem=0;
4. for ($i =0; $i<=strlen($num);$i++)
5. {
6. $rem=$num%10;
7. $sum = $sum + $rem;
8. $num=$num/10;
9. }
10. echo "Sum of digits 14597 is $sum";
11. ?>
Output:
Odd numbers are those which are not divisible by 2. Numbers Like 1, 3, 5, 7, 9, 11, etc are
odd.
Logic:
o Take a number.
o Divide it by 2.
o If the remainder is 0, print number is even.
Example:
1. <?php
2. $number=1233456;
3. if($number%2==0)
4. {
5. echo "$number is Even Number";
6. }
7. else
8. {
9. echo "$number is Odd Number";
10. }
11. ?>
Output:
Example:
1. <html>
2. <body>
3. <form method="post">
4. Enter a number:
5. <input type="number" name="number">
6. <input type="submit" value="Submit">
7. </form>
8. </body>
9. </html>
10. <?php
11. if($_POST){
12. $number = $_POST['number'];
13. //divide entered number by 2
14. //if the reminder is 0 then the number is even otherwise the number is odd
15. if(($number % 2) == 0){
16. echo "$number is an Even number";
17. }else{
18. echo "$number is Odd number";
19. }
20. }
21. ?>
Output:
Prime Number
A number which is only divisible by 1 and itself is called prime number. Numbers 2, 3, 5, 7,
11, 13, 17, etc. are prime numbers.
1. <?php
2. $count = 0;
3. $num = 2;
4. while ($count < 15 )
5. {
6. $div_count=0;
7. for ( $i=1; $i<=$num; $i++)
8. {
9. if (($num%$i)==0)
10. {
11. $div_count++;
12. }
13. }
14. if ($div_count<3)
15. {
16. echo $num." , ";
17. $count=$count+1;
18. }
19. $num=$num+1;
20. }
21. ?>
Output:
We'll show a form, which will check whether a number is prime or not.
1. <form method="post">
2. Enter a Number: <input type="text" name="input"><br><br>
3. <input type="submit" name="submit" value="Submit">
4. </form>
5. <?php
6. if($_POST)
7. {
8. $input=$_POST['input'];
9. for ($i = 2; $i <= $input-1; $i++) {
10. if ($input % $i == 0) {
11. $value= True;
12. }
13. }
14. if (isset($value) && $value) {
15. echo 'The Number '. $input . ' is not prime';
16. } else {
17. echo 'The Number '. $input . ' is prime';
18. }
19. }
20. ?>
Output:
On entering number 12, we get the following output. It states that 12 is not a prime
number.
On entering number 97, we get the following output. It states that 97 is a prime number.
Table of Number
A table of a number can be printed using a loop in program.
Logic:
Example:
1. <?php
2. define('a', 7);
3. for($i=1; $i<=10; $i++)
4. {
5. echo $i*a;
6. echo '<br>';
7. }
8. ?>
Output:
Factorial Program
The factorial of a number n is defined by the product of all the digits from 1 to n (including
1 and n).
For example,
1. 4! = 4*3*2*1 = 24
2. 6! = 6*5*4*3*2*1 = 720
Note:
o Using loop
o Using recursive method
Logic:
o Take a number.
o Take the descending positive integers.
o Multiply them.
Factorial in PHP
Factorial of 4 using for loop is shown below.
Example:
1. <?php
2. $num = 4;
3. $factorial = 1;
4. for ($x=$num; $x>=1; $x--)
5. {
6. $factorial = $factorial * $x;
7. }
8. echo "Factorial of $num is $factorial";
9. ?>
Output:
Example:
1. <html>
2. <head>
3. <title>Factorial Program using loop in PHP</title>
4. </head>
5. <body>
6. <form method="post">
7. Enter the Number:<br>
8. <input type="number" name="number" id="number">
9. <input type="submit" name="submit" value="Submit" />
10. </form>
11. <?php
12. if($_POST){
13. $fact = 1;
14. //getting value from input text box 'number'
15. $number = $_POST['number'];
16. echo "Factorial of $number:<br><br>";
17. //start loop
18. for ($i = 1; $i <= $number; $i++){
19. $fact = $fact * $i;
20. }
21. echo $fact . "<br>";
22. }
23. ?>
24. </body>
25. </html>
Output:
Example:
1. <?php
2. function fact ($n)
3. {
4. if($n <= 1)
5. {
6. return 1;
7. }
8. else
9. {
10. return $n * fact($n - 1);
11. }
12. }
13.
14. echo "Factorial of 6 is " .fact(6);
15. ?>
Output:
Armstrong Number
An Armstrong number is the one whose value is equal to the sum of the cubes of its digits.
For example,
Logic:
Example:
1. <?php
2. $num=407;
3. $total=0;
4. $x=$num;
5. while($x!=0)
6. {
7. $rem=$x%10;
8. $total=$total+$rem*$rem*$rem;
9. $x=$x/10;
10. }
11. if($num==$total)
12. {
13. echo "Yes it is an Armstrong number";
14. }
15. else
16. {
17. echo "No it is not an armstrong number";
18. }
19. ?>
Output:
Look at the above snapshot, the output displays that 407 is an Armstrong number.
1. <html>
2. <body>
3. <form method="post">
4. Enter the Number:
5. <input type="number" name="number">
6. <input type="submit" value="Submit">
7. </form>
8. </body>
9. </html>
10. <?php
11. if($_POST)
12. {
13. //get the number entered
14. $number = $_POST['number'];
15. //store entered number in a variable
16. $a = $number;
17. $sum = 0;
18. //run loop till the quotient is 0
19. while( $a != 0 )
20. {
21. $rem = $a % 10; //find reminder
22. $sum = $sum + ( $rem * $rem * $rem ); //cube the reminder and add it to the sum var
iable till the loop ends
23. $a = $a / 10; //find quotient. if 0 then loop again
24. }
25. //if the entered number and $sum value matches then it is an armstrong number
26. if( $number == $sum )
27. {
28. echo "Yes $number an Armstrong Number";
29. }else
30. {
31. echo "$number is not an Armstrong Number";
32. }
33. }
34. ?>
Output:
Palindrome Number
A palindrome number is a number which remains same when its digits are reversed.
For example, number 24142 is a palindrome number. On reversing it we?ll get the same
number.
Logic:
o Take a number.
o Reverse the input number.
o Compare the two numbers.
o If equal, it means number is palindrome
1. <?php
2. function palindrome($n){
3. $number = $n;
4. $sum = 0;
5. while(floor($number)) {
6. $rem = $number % 10;
7. $sum = $sum * 10 + $rem;
8. $number = $number/10;
9. }
10. return $sum;
11. }
12. $input = 1235321;
13. $num = palindrome($input);
14. if($input==$num){
15. echo "$input is a Palindrome number";
16. } else {
17. echo "$input is not a Palindrome";
18. }
19. ?>
Output:
1. <form method="post">
2. Enter a Number: <input type="text" name="num"/><br>
3. <button type="submit">Check</button>
4. </form>
5. <?php
6. if($_POST)
7. {
8. //get the value from form
9. $num = $_POST['num'];
10. //reversing the number
11. $reverse = strrev($num);
12.
13. //checking if the number and reverse is equal
14. if($num == $reverse){
15. echo "The number $num is Palindrome";
16. }else{
17. echo "The number $num is not a Palindrome";
18. }
19. }
20. ?>
Output:
Fibonacci Series
Fibonacci series is the one in which you will get your next term by adding previous two
numbers.
For example,
1. 0 1 1 2 3 5 8 13 21 34
2. Here, 0 + 1 = 1
3. 1+1=2
4. 3+2=5
and so on.
Logic:
o Initializing first and second number as 0 and 1.
o Print first and second number.
o From next number, start your loop. So third number will be the sum of the first two
numbers.
Example:
1. <?php
2. $num = 0;
3. $n1 = 0;
4. $n2 = 1;
5. echo "<h3>Fibonacci series for first 12 numbers: </h3>";
6. echo "\n";
7. echo $n1.' '.$n2.' ';
8. while ($num < 10 )
9. {
10. $n3 = $n2 + $n1;
11. echo $n3.' ';
12. $n1 = $n2;
13. $n2 = $n3;
14. $num = $num + 1;
15. ?>
Output:
1. <?php
2. /* Print fiboancci series upto 12 elements. */
3. $num = 12;
4. echo "<h3>Fibonacci series using recursive function:</h3>";
5. echo "\n";
6. /* Recursive function for fibonacci series. */
7. function series($num){
8. if($num == 0){
9. return 0;
10. }else if( $num == 1){
11. return 1;
12. } else {
13. return (series($num-1) + series($num-2));
14. }
15. }
16. /* Call Function. */
17. for ($i = 0; $i < $num; $i++){
18. echo series($i);
19. echo "\n";
20. }
Reverse number
A number can be written in reverse order.
For example
12345 = 54321
Logic:
1. <?php
2. $num = 23456;
3. $revnum = 0;
4. while ($num > 1)
5. {
6. $rem = $num % 10;
7. $revnum = ($revnum * 10) + $rem;
8. $num = ($num / 10);
9. }
10. echo "Reverse number of 23456 is: $revnum";
11. ?>
Output:
1. <?php
2. function reverse($number)
3. {
4. /* writes number into string. */
5. $num = (string) $number;
6. /* Reverse the string. */
7. $revstr = strrev($num);
8. /* writes string into int. */
9. $reverse = (int) $revstr;
10. return $reverse;
11. }
12. echo reverse(23456);
13. ?>
Output:/strong>
Reverse String
A string can be reversed either using strrev() function or simple PHP code.
Logic:
Example:
1. <?php
2. $string = "JAVATPOINT";
3. echo "Reverse string of $string is " .strrev ( $string );
4. ?>
Output:
Reverse String Without using strrev() function
A reverse string program without using strrev() function is shown.
Example:
1. <?php
2. $string = "JAVATPOINT";
3. $length = strlen($string);
4. for ($i=($length-1) ; $i >= 0 ; $i--)
5. {
6. echo $string[$i];
7. }
8. ?>
Output:
For example
1. a = 20, b = 30
2. After swapping,
3. a = 30, b = 20
1. <?php
2. $a = 45;
3. $b = 78;
4. // Swapping Logic
5. $third = $a;
6. $a = $b;
7. $b = $third;
8. echo "After swapping:<br><br>";
9. echo "a =".$a." b=".$b;
10. ?>
Output:
1. <?php
2. $a=234;
3. $b=345;
4. //using arithmetic operation
5. $a=$a+$b;
6. $b=$a-$b;
7. $a=$a-$b;
8. echo "Value of a: $a</br>";
9. echo "Value of b: $b</br>";
10. ?>
Output:
1. <?php
2. $a=234;
3. $b=345;
4. // using arithmetic operation
5. $a=$a*$b;
6. $b=$a/$b;
7. $a=$a/$b;
8. echo "Value of a: $a</br>";
9. echo "Value of b: $b</br>";
10. ?>
Output:
Example:
1. <?php
2. $x=15;
3. $y=30;
4. $z=$x+$y;
5. echo "Sum: ",$z;
6. ?>
Output:
Adding in Form
Two numbers can be added by passing input value in the form.
Example:
1. <html>
2. <body>
3. <form method="post">
4. Enter First Number:
5. <input type="number" name="number1" /><br><br>
6. Enter Second Number:
7. <input type="number" name="number2" /><br><br>
8. <input type="submit" name="submit" value="Add">
9. </form>
10. <?php
11. if(isset($_POST['submit']))
12. {
13. $number1 = $_POST['number1'];
14. $number2 = $_POST['number2'];
15. $sum = $number1+$number2;
16. echo "The sum of $number1 and $number2 is: ".$sum;
17. }
18. ?>
19. </body>
20. </html>
Output:
1. <body>
2. <form>
3. Enter First Number:
4. <input type="number" name="number1" /><br><br>
5. Enter Second Number:
6. <input type="number" name="number2" /><br><br>
7. <input type="submit" name="submit" value="Add">
8. </form>
9. </body>
10. <?php
11. @$number1=$_GET['number1'];
12. @$number2=$_GET['number2'];
13. for ($i=1; $i<=$number2; $i++)
14. {
15. $number1++;
16. }
17. echo "Sum of $number1 and $number2 is=".$number2;
18. ?>
Output:
Subtracting Two Numbers
There are three methods to subtract two numbers:
Example:
1. <?php
2. $x=30;
3. $y=15;
4. $z=$x-$y;
5. echo "Difference: ",$z;
6. ?>
Output:
Subtraction in Form
By inserting values in the form two numbers can be subtracted.
Example:
1. <html>
2. <body>
3. <form method="post">
4. Enter First Number:
5. <input type="number" name="number1" /><br><br>
6. Enter Second Number:
7. <input type="number" name="number2" /><br><br>
8. <input type="submit" name="submit" value="Subtract">
9. </form>
10. <?php
11. if(isset($_POST['submit']))
12. {
13. $number1 = $_POST['number1'];
14. $number2 = $_POST['number2'];
15. $sum = $number1-$number2;
16. echo "The difference of $number1 and $number2 is: ".$sum;
17. }
18. ?>
19. </body>
20. </html>
Output:
Example:
1. <body>
2. <form>
3. Enter First Number:
4. <input type="number" name="number1" /><br><br>
5. Enter Second Number:
6. <input type="number" name="number2" /><br><br>
7. <input type="submit" name="submit" value="Subtract">
8. </form>
9. </body>
10. <?php
11.
12. @$number1=$_GET['number1'];
13. @$number2=$_GET['number2'];
14. for ($i=1; $i<=$number2; $i++)
15. {
16. $number1--;
17. }
18. echo "Difference=".$number1;
19. ?>
Output:
Area of Triangle
Area of a triangle is calculated by the following Mathematical formula,
Example:
1. <?php
2. $base = 10;
3. $height = 15;
4. echo "area with base $base and height $height= " . ($base * $height) / 2;
5. ?>
Output:
Example:
1. <html>
2. <body>
3. <form method = "post">
4. Base: <input type="number" name="base">
5. <br><br>
6. Height: <input type="number" name="height"><br>
7. <input type = "submit" name = "submit" value="Calculate">
8. </form>
9. </body>
10. </html>
11. <?php
12. if(isset($_POST['submit']))
13. {
14. $base = $_POST['base'];
15. $height = $_POST['height'];
16. $area = ($base*$height) / 2;
17. echo "The area of a triangle with base as $base and height as $height is $area";
18. }
19. ?>
Output:
Area of a Rectangle
Area of a rectangle is calculated by the mathematical formula,
Logic:
Example:
1. <?php
2. $length = 14;
3. $width = 12;
4. echo "area of rectangle is $length * $width= " . ($length * $width) . "<br />";
5. ?>
Output:
Example:
1. <html>
2. <body>
3. <form method = "post">
4. Width: <input type="number" name="width">
5. <br><br>
6. Length: <input type="number" name="length"> <br>
7. <input type = "submit" name = "submit" value="Calculate">
8. </form>
9. </body>
10. </html>
11. <?php
12. if(isset($_POST['submit']))
13. {
14. $width = $_POST['width'];
15. $length = $_POST['length'];
16. $area = $width*$length;
17. echo "The area of a rectangle with $width x $length is $area";
18. }
19. ?>
Output:
Example:
1. <?php
2. function isLeap($year)
3. {
4. return (date('L', mktime(0, 0, 0, 1, 1, $year))==1);
5. }
6. //For testing
7. for($year=1991; $year<2016; $year++)
8. {
9. If (isLeap($year))
10. {
11. echo "$year : LEAP YEAR<br />\n";
12. }
13. else
14. {
15. echo "$year : Not leap year<br />\n";
16. }
17. }
18. ?>
Output:
Leap Year Program in Form
This program states whether a year is leap year or not by inserting a year in the form.
Example:
1. <html>
2. <body>
3. <form method="post">
4. Enter the Year: <input type="text" name="year">
5. <input type="submit" name="submit" value="Submit">
6. </form>
7. </body>
8. </html>
9. <?php
10. if($_POST)
11. {
12. //get the year
13. $year = $_POST['year'];
14. //check if entered value is a number
15. if(!is_numeric($year))
16. {
17. echo "Strings not allowed, Input should be a number";
18. return;
19. }
20. //multiple conditions to check the leap year
21. if( (0 == $year % 4) and (0 != $year % 100) or (0 == $year % 400) )
22. {
23. echo "$year is a Leap Year";
24. }
25. else
26. {
27. echo "$year is not a Leap Year";
28. }
29. }
30. ?>
Output:
Logic:
o Two for loops are used.
o First for loop set conditions to print 1 to 5 rows.
o Second for loop set conditions in decreasing order.
Example:
1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=5; $j>$i; $j--){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>
Output:
Example:
1. <?php
2. for( $i=65; $i<=69; $i++){
3. for($j=5; $j>=$i-64; $j--){
4. echo chr($i);
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Example:
1. <?php
2. $k=1;
3. foreach(range('A','Z') as $char){
4. for($i=5; $i>=$k; $i--){
5. echo $char;
6. }
7. echo "<br>";
8. $k=$k+1;
Output:
1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=5; $j>$i; $j--){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>
Output:
Pattern 2
1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=0; $j<=$i; $j++){
5. echo $alpha[$i];
6. }
7. echo "<br>";
8. }
9. ?>
Output:
Pattern 3
1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=0; $j<=$i; $j++){
5. echo $alpha[$j];
6. }
7. echo "<br>";
8. }
9. ?>
Output:
Pattern 4
1. <?php
2. $alpha = range('A', 'Z');
3. for($i=0; $i<5; $i++){
4. for($j=4; $j>=$i; $j--){
5. echo $alpha[$j];
6. }
7. echo "<br>";
8. }
9. ?>
Output:
Pattern 5
1. <?php
2. $alpha = range('A', 'Z');
3. for ($i=5; $i>=1; $i--) {
4. for($j=0; $j<=$i; $j++) {
5. echo ' ';
6. }
7. $j--;
8. for ($k=0; $k<=(5-$j); $k++) {
9. echo $alpha[$k];
10. }
11. echo "<br>\n";
12. }
13. ?>
Output:
Number Triangle
Number triangle in PHP can be printed using for and foreach loop. There are a lot of
patterns in number triangle. Some of them are show here.
Pattern1
1. <?php
2. $k=1;
3. for($i=0;$i<4;$i++){
4. for($j=0;$j<=$i;$j++){
5. echo $k." ";
6. $k++;
7. }
8. echo "<br>";
9. }
10. ?>
Output:
Pattern 2
1. <?php
2. $k=1;
3. for($i=0;$i<5;$i++){
4. for($j=0;$j<=$i;$j++){
5. if($j%2==0)
6. {
7. $k=0;
8. }
9. else
10. {
11. $k=1;
12. }
13. echo $k." ";
14. }
15. echo "<br>";
16. }
17. ?>
Output:
Pattern 3
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo $j;
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Pattern 4
1. <?php
2. for($i=0;$i>=5;$i++){
3. for($j=1;$j>=$i;$j++){
4. echo $i;
5. }
6. echo "<br>";
7. }
8. ?<
Output:
Pattern 5
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo "1";
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Pattern 6
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo "1";
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Pattern 7
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo $j;
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Pattern 8
1. <?php
2. for($i=5;$i>=1;$i--){
3. for($j=$i;$j>=1;$j--){
4. echo $i." ";
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Star Triangle
The star triangle in PHP is made using for and foreach loop. There are a lot of star patterns.
We'll show some of them here.
Pattern 1
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=5-$i;$j>=1;$j--){
4. echo "* ";
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Pattern 2
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($j=1;$j<=$i;$j++){
4. echo "* ";
5. }
6. echo "<br>";
7. }
8. ?>
Output:
Pattern 3
1. <?php
2. for($i=0;$i<=5;$i++){
3. for($k=5;$k>=$i;$k--){
4. echo " ";
5. }
6. for($j=1;$j<=$i;$j++){
7. echo "* ";
8. }
9. echo "<br>";
10. }
11. for($i=4;$i>=1;$i--){
12. for($k=5;$k>=$i;$k--){
13. echo " ";
14. }
15. for($j=1;$j<=$i;$j++){
16. echo "* ";
17. }
18. echo "<br>";
19. }
20. ?>
Output:
Pattern 4
1. <?php
2. for($i=1; $i<=5; $i++){
3. for($j=1; $j<=$i; $j++){
4. echo ' * ';
5. }
6. echo '<br>';
7. }
8. for($i=5; $i>=1; $i--){
9. for($j=1; $j<=$i; $j++){
10. echo ' * ';
11. }
12. echo '<br>';
13. }
14. ?>
Output:
Pattern 5
1. <?php
2. for ($i=1; $i<=5; $i++)
3. {
4. for ($j=1; $j<=5; $j++)
5. {
6. echo '* ';
7. }
8. echo "</br>";
9. }
10. ?>
Output:
Pattern 6
1. <?php
2. for($i=5; $i>=1; $i--)
3. {
4. if($i%2 != 0)
5. {
6. for($j=5; $j>=$i; $j--)
7. {
8. echo "* ";
9. }
10. echo "<br>";
11. }
12. }
13. for($i=2; $i<=5; $i++)
14. {
15. if($i%2 != 0)
16. {
17. for($j=5; $j>=$i; $j--)
18. {
19. echo "* ";
20. }
21. echo "<br>";
22. }
23. }
24. ?>
Output: