PHP - Introduction
PHP - Introduction
Rasmus Lerdorf inspired the first version of PHP and participated in the later
versions. It is an interpreted language and it does not require a compiler.
PHP code is executed in the server.
It can be integrated with many databases such as Oracle, Microsoft SQL
Server, MySQL, PostgreSQL, Sybase, and Informix.
It is powerful to hold a content management system like WordPress and can
be used to control user access.
It supports main protocols like HTTP Basic, HTTP Digest, IMAP, FTP, and
others.
Websites like www.facebook.com and www.yahoo.com are also built on
PHP.
One of the main reasons behind this is that PHP can be easily embedded in
HTML files and HTML codes can also be written in a PHP file.
The thing that differentiates PHP from the client-side language like HTML is,
that PHP codes are executed on the server whereas HTML codes are
directly rendered on the browser. PHP codes are first executed on the server
and then the result is returned to the browser.
The only information that the client or browser knows is the result returned
after executing the PHP script on the server and not the actual PHP codes
present in the PHP file. Also, PHP files can support other client-side scripting
languages like CSS and JavaScript.
characteristics of PHP :
<html>
<head>
<title>PHP Example</title>
</head>
<body>
</body>
</html>
Output:
Hello, World! This is PHP code
PHP Comments
PHP comments can be used to describe any line of code so that other developer can
understand the code easily. It can also be used to hide any code.
PHP supports single line and multi line comments. These comments are similar to C/C++
and Perl style (Unix shell style) comments.
1. <?php
2. // this is C++ style single line comment
3. # this is Unix Shell style single line comment
4. echo "Welcome to PHP single line comments";
5. ?>
Output:
1. <?php
2. /*
3. Anything placed
4. within comment
5. will not be displayed
6. on the browser;
7. */
8. echo "Welcome to PHP multi line comment";
9. ?>
Output:
Logical $x and
and True if both the operands are true else false
AND $y
Logical $x &&
&& True if both the operands are true else false
AND $y
Logical
! !$x True if $x is false
NOT
Comparison Operators: These operators are used to compare two elements and outputs
the result in boolean form. Here are the comparison operators along with their syntax and
operations in PHP.
Operator Name Syntax Operation
Less Than or
<= $x <= $y Returns True if $x is less than or equal to $y
Equal To
If the condition is true? then $x : or else $y. This means that if the
?: Ternary condition is true then the left result of the colon is accepted otherwise
the result is on right.
Assignment Operators: These operators are used to assign values to different variables,
with or without mid-operations. Here are the assignment operators along with their
syntax and operations, that PHP provides for the operations.
Operator Name Syntax Operation
$x +=
+= Add then Assign Simple Addition same as $x = $x + $y
$y
$x *=
*= Multiply then Assign Simple product same as $x = $x * $y
$y
Array Operators: These operators are used in the case of arrays. Here are the array
operators along with their syntax and operations, that PHP provides for the array operation.
Operator Name Syntax Operation
$x ==
== Equality Returns true if both has same key-value pair
$y
Non- $x !==
!== Returns True if both are not identical to each other
Identity $y
$x <>
<> Inequality Returns True if both are unequal
$y
Increment/Decrement Operators: These are called the unary operators as they work on
single operands. These are used to increment or decrement values.
Operator Name Syntax Operation
String Operators: This operator is used for the concatenation of 2 or more strings using
the concatenation operator (‘.’). We can also use the concatenating assignment operator
(‘.=’) to append the argument on the right side to the argument on the left side.
Operator Name Syntax Operation
Spaceship Operators:
PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship
operator or combined comparison operator is denoted by “<=>“. These operators are used
to compare values but instead of returning the boolean results, it returns integer values. If
both the operands are equal, it returns 0. If the right operand is greater, it returns -1. If the
left operand is greater, it returns 1. The following table shows how it works in detail:
$x <= $y $x <=> $y Identical to -1 (right is greater) or identical to 0 (if both are equal)
$x >= $y $x <=> $y Identical to 1 (if left is greater) or identical to 0 (if both are equal)
PHP Primitives
Data Types define the type of data a variable can store. PHP allows eight different types
of data types. All of them are discussed below. There are pre-defined, user-defined, and
special data types.
The predefined data types are:
Boolean
Integer
Double
String
The user-defined (compound) data types are:
Array
Objects
The special data types are:
NULL
resource
The first five are called simple data types and the last three are compound data types:
1. Integer: Integers hold only whole numbers including positive and negative numbers,
i.e., numbers without fractional part or decimal point. They can be decimal (base 10),
octal (base 8), or hexadecimal (base 16). The default base is decimal (base 10). The octal
integers can be declared with leading 0 and the hexadecimal can be declared with leading
0x. The range of integers must lie between -2^31 to 2^31.
2. Double: Can hold numbers containing fractional or decimal parts including positive
and negative numbers or a number in exponential form. By default, the variables add a
minimum number of decimal places. The Double data type is the same as a float as
floating-point numbers or real numbers.
3. String: Hold letters or any alphabets, even numbers are included. These are written
within double quotes during declaration. The strings can also be written within single
quotes, but they will be treated differently while printing variables. To clarify this look at
the example below.
4. Boolean: Boolean data types are used in conditional testing. Hold only two values,
either TRUE(1) or FALSE(0). Successful events will return true and unsuccessful events
return false. NULL type values are also treated as false in Boolean. Apart from NULL, 0
is also considered false in boolean. If a string is empty then it is also considered false in
boolean data type.
5. Array: Array is a compound data type that can store multiple values of the same data
type. Below is an example of an array of integers. It combines a series of data that are
related together.
6. Objects: Objects are defined as instances of user-defined classes that can hold both
values and functions and information for data processing specific to the class. This is an
advanced topic and will be discussed in detail in further articles. When the objects are
created, they inherit all the properties and behaviours from the class, having different
values for all the properties.
Objects are explicitly declared and created from the new keyword
7. NULL: These are special types of variables that can hold only one value i.e., NULL.
We follow the convention of writing it in capital form, but it’s case-sensitive. If a
variable is created without a value or no value, it is automatically assigned a value of
NULL. It is written in capital letters.
8. Resources: Resources in PHP are not an exact data type. These are basically used to
store references to some function call or to external PHP resources. For example,
consider a database call. This is an external resource. Resource variables hold special
handles for files and database connection.
PHP | Variables
Variables in a program are used to store some values or data that can be used later in a
program. The variables are also like containers that store character values, numeric
values, memory addresses, and strings. PHP has its own way of declaring and storing
variables.
There are a few rules, that need to be followed and facts that need to be kept in mind
while dealing with variables in PHP:
Any variables declared in PHP must begin with a dollar sign ($), followed by the
variable name.
A variable can have long descriptive names (like $factorial, $even_nos) or short
names (like $n or $f or $x)
A variable name can only contain alphanumeric characters and underscores (i.e., ‘a-
z’, ‘A-Z’, ‘0-9, and ‘_’) in their name. Even it cannot start with a number.
A constant is used as a variable for a simple value that cannot be changed. It is also
case-sensitive.
Assignment of variables is done with the assignment operator, “equal to (=)”. The
variable names are on the left of equal and the expression or values are to the right of
the assignment operator ‘=’.
One must keep in mind that variable names in PHP names must start with a letter or
underscore and no numbers.
PHP is a loosely typed language, and we do not require to declare the data types of
variables, rather PHP assumes it automatically by analyzing the values. The same
happens while conversion. No variables are declared before they are used. It
automatically converts types from one type to another whenever required.
PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.
Data types used by PHP to declare or construct variables:
Integers
Doubles
NULL
Strings
Booleans
Arrays
Objects
Resources
Variable Scopes
Scope of a variable is defined as its extent in a program within which it can be
accessed, i.e. the scope of a variable is the portion of the program within which
it is visible or can be accessed.
Depending on the scopes, PHP has three variable scopes:
Local variables: The variables declared within a function are called local
variables to that function and have their scope only in that particular function.
In simple words, it cannot be accessed outside that function. Any declaration
of a variable outside the function with the same name as that of the one
within the function is a completely different variable. We will learn about
functions in detail in later articles. For now, consider a function as a block of
statements.
Variable Variables:-
PHP allows us to use dynamic variable names, called variable variables.
Variable variables are simply variables whose names are dynamically
created by another variable’s value.
o if
o if-else
o if-else-if
o nested if
PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is true.
If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.
Syntax
Play Video
1. if(condition){
2. //code to be executed
3. }
Flowchart
Example
1. <?php
2. $num=12;
3. if($num<100){
4. echo "$num is less than 100";
5. }
6. ?>
Output:
Syntax
1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }
Flowchart
Example
1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>
Output:
12 is even number
Syntax
1. if (condition1){
2. //code to be executed if condition1 is true
3. } elseif (condition2){
4. //code to be executed if condition2 is true
5. } elseif (condition3){
6. //code to be executed if condition3 is true
7. ....
8. } else{
9. //code to be executed if all given conditions are false
10. }
Flowchart
Example
1. <?php
2. $marks=69;
3. if ($marks<33){
4. echo "fail";
5. }
6. else if ($marks>=34 && $marks<50) {
7. echo "D grade";
8. }
9. else if ($marks>=50 && $marks<65) {
10. echo "C grade";
11. }
12. else if ($marks>=65 && $marks<80) {
13. echo "B grade";
14. }
15. else if ($marks>=80 && $marks<90) {
16. echo "A grade";
17. }
18. else if ($marks>=90 && $marks<100) {
19. echo "A+ grade";
20. }
21. else {
22. echo "Invalid input";
23. }
24. ?>
Output:
B Grade
Syntax
1. if (condition) {
2. //code to be executed if condition is true
3. if (condition) {
4. //code to be executed if condition is true
5. }
6. }
Flowchart
PHP - Arrays
An array is a data structure that stores one or more similar type of values in a single value.
For example if you want to store 100 numbers then instead of defining 100 variables its
easy to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c
which is called array index.
Numeric array − An array with a numeric index. Values are stored and accessed
in linear fashion.
Associative array − An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are
accessed using multiple indices
NOTE − Built-in array functions is given in function reference PHP Array Functions
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented
by numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function
reference.
Live Demo
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they
are different in terms of their index. Associative array will have their index as string so
that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be
the best choice. Instead, we could use the employees names as the keys in our
associative array, and the value would be their respective salary.
NOTE − Don't keep associative array inside double quote while printing otherwise it would
not return any value.
Example
Live Demo
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
</body>
</html>
This will produce the following result −
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional
array are accessed using multiple index.
PHP - Functions
PHP functions are similar to other programming languages. A function is a piece of code
which takes one more input in the form of parameter and does some processing and
returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in
functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you −
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
}
</body>
</html>
This will display following result −
You are really a nice person, Have a nice time!
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result −
Sum of the two numbers is : 30
<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
This will display following result −
Original Value is 10
Original Value is 16
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
Form Processing
HTML forms are used to send the user information to the server and returns the
result back to the browser. For example, if you want to get the details of visitors
to your website, and send them good thoughts, you can collect the user
information by means of form processing. Then, the information can be
validated either at the client-side or on the server-side. The final result is sent to
the client through the respective web browser. To create a HTML
form, form tag should be used.
Attributes of Form Tag:
Attribute Description
name or It specifies the name of the form and is used to identify individual
id forms.
It specifies the location to which the form data has to be sent when
action
the form is submitted.
It specifies the encryption type for the form data when the form is
encType
submitted.
It implies the server not to verify the form data when the form is
novalidate
submitted.
<?php
if (isset($_POST['submit']))
if ((!isset($_POST['firstname'])) || (!isset($_POST['lastname']))
||
(!isset($_POST['address'])) || (!isset($_POST['emailaddress']))
||
(!isset($_POST['password'])) || (!isset($_POST['gender'])))
else
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$emailaddress = $_POST['emailaddress'];
$password = $_POST['password'];
$gender = $_POST['gender'];
?>
<html>
<head>
<body>
<fieldset>
<?php
if (isset($_POST['submit']))
if (isset($error))
. $error . "</p>";
?>
FirstName:
<span style="color:red;">*</span>
<br>
<br>
Last Name:
<span style="color:red;">*</span>
<br>
<br>
Address:
<span style="color:red;">*</span>
<br>
<br>
Email:
<span style="color:red;">*</span>
<br>
<br>
Password:
<span style="color:red;">*</span>
<br>
<br>
Gender:
<input type="radio"
value="Male"
name="gender"> Male
<input type="radio"
value="Female"
name="gender">Female
<br>
<br>
</form>
</fieldset>
<?php
if(isset($_POST['submit']))
if(!isset($error))
echo"<h1>INPUT RECEIVED</h1><br>";
echo "<table border='1'>";
echo "<thead>";
echo "<th>Parameter</th>";
echo "<th>Value</th>";
echo "</thead>";
echo "<tr>";
echo "<td>".$firstname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>".$lastname."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Address</td>";
echo "<td>".$address."</td>";
echo "</tr>";
echo "<tr>";
echo "<tr>";
echo "<td>Password</td>";
echo "<td>".$password."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Gender</td>";
echo "<td>".$gender."</td>";
echo "</tr>";
echo "</table>";
?>
</body>
</html>
Output:
Syntax
1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $c
ontext ]] )
Example
Play Video
1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>
Click me for more details...
PHP Close File - fclose()
The PHP fclose() function is used to close an open file pointer.
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. ?>
Cookies
A cookie in PHP is a small file with a maximum size of 4KB that the web server
stores on the client computer. They are typically used to keep track of information
such as a username that the site can retrieve to personalize the page when the
user visits the website next time. A cookie can only be read from the domain that
it has been issued from. Cookies are usually set in an HTTP header but
JavaScript can also set a cookie directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used.
The setcookie() function needs to be called prior to any output generated by the
script otherwise the cookie will not be set.
Syntax:
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general which
are:
Name: It is used to set the name of the cookie.
Value: It is used to set the value of the cookie.
Expire: It is used to set the expiry timestamp of the cookie after which the
cookie can’t be accessed.
Path: It is used to specify the path on the server for which the cookie will be
available.
Domain: It is used to specify the domain for which the cookie is available.
Security: It is used to indicate that the cookie should be sent only if a secure
HTTPS connection exists.
Below are some operations that can be performed on Cookies in PHP:
Creating Cookies: Creating a cookie named Auction_Item and assigning the
value Luxury Car to it. The cookie will expire after 2 days(2 days * 24 hours *
60 mins * 60 seconds).
Example: This example describes the creation of the cookie in PHP.
PHP
<!DOCTYPE html>
<?php
?>
<html>
<body>
<?php
?>
<p>
<strong>Note:</strong>
</p>
</body>
</html>
Note: Only the name argument in the setcookie() function is mandatory. To skip
an argument, the argument can be replaced by an empty string(“”).
Output:
<!DOCTYPE html>
<?php
?>
<html>
<body>
<?php
?>
<p>
<strong>Note:</strong>
</p>
</body>
</html>
Note: Only the name argument in the setcookie() function is mandatory. To skip
an argument, the argument can be replaced by an empty string(“”).
Output:
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.
Play Video
Syntax
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.
Example: Store information
1. $_SESSION["user"] = "Sachin";
1. echo $_SESSION["user"];
1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php
7. $_SESSION["user"] = "Sachin";
8. echo "Session information are set successfully.<br/>";
9. ?>
10. <a href="session2.php">Visit next page</a>
11. </body>
12. </html>
File: session2.php
1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php
7. echo "User is: ".$_SESSION["user"];
8. ?>
9. </body>
10. </html>
PHP Session Counter Example
File: sessioncounter.php
1. <?php
2. session_start();
3.
4. if (!isset($_SESSION['counter'])) {
5. $_SESSION['counter'] = 1;
6. } else {
7. $_SESSION['counter']++;
8. }
9. echo ("Page Views: ".$_SESSION['counter']);
10. ?>
File: session3.php
1. <?php
2. session_start();
3. session_destroy();
4. ?>
Database connection
The collection of related data is called a database. XAMPP stands for cross-platform,
Apache, MySQL, PHP, and Perl. It is among the simple light-weight local servers for
website development.
Requirements: XAMPP web server procedure:
Start XAMPP server by starting Apache and MySQL.
Write PHP script for connecting to XAMPP.
Run it in the local browser.
Database is successfully created which is based on the PHP code.
In PHP, we can connect to the database using XAMPP web server by using the following
path.
"localhost/phpmyadmin"
Steps in Detail:
Open XAMPP and start running Apache, MySQL and FileZilla
Now open your PHP file and write your PHP code to create database and a table in
your database.
PHP code to create a database:
PHP
<?php
$servername = "localhost";
// Password is empty
$password = "";
// Creating a connection
$username, $password);
// Check connection
if ($conn->connect_error) {
. $conn->connect_error);
} else {
echo "Error: " . $conn->error;
// Closing connection
$conn->close();
?>