PHP Notes
PHP Notes
PHP Notes
PHP is one of the most widely used server side scripting language for web development. Popular
websites like Facebook, Yahoo, Wikipedia etc, and even our college website are developed using
PHP.
What is PHP?
PHP stands for Hypertext Pre-Processor. PHP is a scripting language used to develop static and
dynamic webpages and web applications. Here are a few important things you must know about PHP:
1. PHP is an Interpreted language, hence it doesn't need a compiler.
2. To run and execute PHP code, we need a Web server on which PHP must be installed.
3. PHP is a server side scripting language, which means that PHP is executed on the server and the
result is sent to the browser in plain HTML.
4. PHP is open source and free.
Uses of PHP
To further fortify your trust in PHP, here are a few applications of this amazing scripting language:
1. It can be used to create Web applications like Social Networks(Facebook, Digg),
Blogs(Wordpress, Joomla), eCommerce websites(OpenCart, Magento etc.) etc.
2. Comman Line Scripting. You can write PHP scripts to perform different operations on any
machine, all you need is a PHP parser for this.
3. Create Facebook applications and easily integrate Facebook plugins in your website, using
Facebook's PHP SDK. Check this link for more information.
4. Sending Emails or building email applications because PHP provides with a robust email sending
function.
5. Wordpress is one of the most used blogging(CMS) platform in the World, and if you know PHP,
you can try a hand in Wordpress plugin development.
You can easily download and install XAMPP from this link. The installation process is simple and
once installed you will see a small window like this, showing the status of various services which
are running.
You can easily control, stop and restart, various services using the XAMPP Control Panel.
Upon successful installation, a folder with name xampp will be created in the C drive(by default).
In the folder xampp there are many sub-folders like apache, cgi-bin, FileZillaFTP etc, but the
most important sub-folders are:
1. htdocs: This is the folder in which we will keep all our PHP files.
2. mysql: This folder contains all the files for the MySQL database. By default the MySQL
databse runs on port number 3306.
3. php: This folder holds all the installation files for PHP. All the configurations for the current
PHP installation is saved in php.ini file which is stored in this folder.
If everything seems fine and the apache server is running(check in the XAMPP control panel),
open your Web browser and enter localhost in the address bar and hit enter. You will see the
default page of Apache web server.
Other Software Packages
XAMPP is not the only available package, although it is the most widely used one. Here are a
few other Operating System specific options that you can download and install:
WAMP: It's for Windows (Window, Apache, MySQL and PHP)
MAMP: It's for Mac OSX (Macintosh, Apache, MySQL and PHP)
LAMP: It's for Linux (Linux, Apache, MySQL and PHP)
Hello, World!
echo is a command used in PHP to display anything on screen.
If we want to include this php code in an HTML document, we can do so like this:
<!DOCTYPE>
<html>
<body>
<?php
echo "<h1>Hello, World!</h1>";
?>
</body>
</html>
Now copy the above code and paste it in you Code Editor or IDE and save the file with the
name hello_world.php
Now go to your C directory where XAMPP was installed, and open xampp → htdocs and create
a new folder with name Matrusri and put your php code file hello_world.php in the Matrusri
folder.
Now visit the following link in your browser: localhost/ Matrusri /hello_world.php and you
would see Hello, World! written on the screen. Notice that Hello, World! is written as a heading
because in the HTML code we specified that Hello, World! should be printed as a heading as put
it inside the heading tag <h1>
PHP Syntax Rules
Below we have a listed down the main syntax rules that you must follow while writing php code.
1. All the php code in a php script should be enclosed within <?php and ?>, else it will not be
considered as php code. Adding php code inside the PHP tags is known as Escaping to
php.
<?php ... ?>
Apart from the standard <?php and ?>, you can also use the Short-open tags:
<? ... ?>
Or use the HTML script tags, like we do for adding javascript code in HTML document:
<script language="PHP"> ... </script>
10. PHP is case sensitive, which means that a variable $tiger is not same as $Tiger. Both of
these, represent two different variables here.
But all the predefined keywords and functions like if, else, echo etc are case insensitive.
<?php
echo "Hello, World!";
ECHO "Hello, World!";
?>
Hello, World!
Hello, World!
Don't worry we will learn about if...else conditions in details, this is just to demonstrate the
use of curly braces.
Variables in PHP 5
When we want to store any information(data) on our computer/laptop, we store it in the
computer's memory space. Instead of remembering the complex address of that memory space
where we have stored our data, our operating system provides us with an option to create
folders, name them, so that it becomes easier for us to find it and access it.
Similarly, in any programming/scripting language, when we want to use some data value in our
program/script, we can store it in a memory space and name the memory space so that it
becomes easier to access it. The name given to the memory space is called a Variable.
In PHP, a variable is declared using a $ sign, followed by the variable name.
Syntax:
<?php
$variableName = value;
?>
Creating a Variable
In the example below we have create a different types of variables:
<?php
$str = "I am a string";
$int = 4;
$float = 3.14;
// You can name your variable anything
$wow = "Wow!";
?>
In PHP, you don't have to declare the variable first and then use it, like it's done in Java, C++ etc,
but in PHP the variable is created at the moment you assign it a value, like Python.
Also, in PHP we do not have to specify the type of data that we will be storing in a variable. You
can create a variable and save any type of data in it. Hence PHP is quite loosely typed
language.
8. A variable name can only contain alphabets, numbers and underscore symbol _.
9. Variable names in PHP are case-sensitive, which means $love is not same as $Love.
10. <?php
11. $car = "Jaguar E-Pace";
12. echo "My favorite car is $car";
13. // below statement will give error
14. echo "I love $Car";
?>
PHP Echo
echo() function is used to print or output one or more strings. We have specifically
mentioned string here because, the syntax of the echo function is:
echo(string)
Although you can use echo() function to output anything, as PHP parser will automaticallly
convert it into string type.
echo doesn't need parenthesis, although you can use parenthesis if you want.
<?php
echo "I am open";
echo ("I am enclosed in parenthesis");
?>
I am open
I am enclosed in parenthesis
I am a sentence
Printing multiple strings using comma ,
Here is how you can use multiple strings as parameters for echo.
<?php
echo 'This','is','a','broken','sentence';
?>
I am a string variable
Printing a string variable with some text
Below we have explained how using double quotes and single quotes leads to different output
when we use a string variable with some plain text in echo.
<?php
$weird = "Stupid";
echo "I am $weird";
echo 'I am $weird';
?>
I am Stupid
I am $weird
As you can see, when we use double quotes the value of the string variable gets printed, while
if we use single quotes, the variable is printed as it is.
Escaping special characters
As seen in previous examples, a double quote is required by echo to confirm what has to be
printed. But what if you want to print the double quotes too? In such cases, we use an escape
sequence to escape special characters from their special meanings. In PHP, a backslash \ is
used to escape special characters.
Below we have a simple example:
<?php
echo "Hello, this is a \"beautiful\" picture";
?>
PHP Print
The PHP print is exactly the same as echo, with same syntax and same usage. Just
replace echowith print in all the above examples, and they will work just fine.
PHP Boolean
A boolean data type can have two possible values, either True or False.
$a = true;
$b = false;
PHP Integer
An Integer data type is used to store any non-decimal numeric value within the range -2,147,483,648
to 2,147,483,647.
An integer value can be negative or positive, but it cannot have a decimal.
$x = -2671;
$y = 7007;
PHP Float
Float data type is used to store any decimal numeric value.
A float(floating point) value can also be either negative or positive.
$a = -2671.01;
$b = 7007.70;
PHP String
String data type in PHP and in general, is a sequence of characters(or anything, it can be numbers and
special characters too) enclosed within quotes. You can use single or double quotes.
$str1 = "Hello";
$str2 = "What is your Roll No?";
$str3 = "4";
echo $str1;
echo "<br/>";
echo $str2;
echo "<br/>";
echo "Me: My Roll number is $str3";
Hello
What is your Roll No?
Me: My Roll number is 4
PHP NULL
NULL data type is a special data type which means nothing. It can only have one value, and that
is NULL.
If you create any variable and do not assign any value to it, it will automatically have NULL stored in it.
Also, we can use NULL value to empty any variable.
// holds a null value
$a;
$b = 7007.70;
// we can also assign null value
$b = null;
PHP 5 Constants
Constants are variables whose value cannot be changed. In other words, once you set a value
for a constant, you cannot change it.
In PHP, there are two ways to define a constant:
1. Using the define() method.
2. Using the const keyword.
Another very important point to remember is that while naming a constant, we don't have to
use $symbol with the constant's name.
Using define()
Below is the syntax for using the define() function to create a constant.
define(name, value, case-insensitive)
Parameters:
1. name: Name of the constant
2. value: Value of the constant
3. case-insensitive: Specifies whether the constant name is case sensitive or not. It's default
value is false, which means, by default, the constant name is case sensitive.
Time for an Example
Below we have a simple example where we have not mentioned the parameter case-
insensitive, hence it will automatically take the default value for that.
<?php
define(OMG, "Oh! my God.");
echo OMG;
?>
Oh! my God.
For the above constant definition, if we try to use the following statement we will get an error,
because the constant OMG is case sensitive.
<?php
define(OMG, "Oh! my God.");
echo omg;
?>
omg
echo will consider it as a string and will print it as it is, with a subtle NOTICE saying that the string
variable is not defined.
Now let's see another example where we will specify the case-insensitive parameter.
<?php
define(OMG, "Oh! my God.", true);
echo omg;
?>
Oh! my God.
Oh! my God.
When we define a constant using the const keyword, the constant name is always case sensitive.
PHP Operators
Operators are used to perform operations on PHP variables and simple values.
In PHP there are total 7 types of operators, they are:
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Increment/Decrement Operators
5. Logical Operators
6. String Operators
7. Array Operators
There are a few additional operators as well like, Type operator, Bitwise operator, Execution
operators etc.
Based on how these operators are used, they are categorised into 3 categories:
1. Unary Operators: Works on a single operand(variable or value).
2. Binary Operators: Works on two operands(variables or values).
3. Ternary Operators: Works on three operands.
+- $a += $b is same as $a + $b
-= $a -= $b is same as $a - $b
*= $a *= $b is same as $a * $b
/= $a /= $b is same as $a / $b
%= $a %= $b is same as $a % $b
Identical === It returns true if left operand is equal to the right $a === $b
operand and they are of the same type.
Not Equal != It returns true if left operand is not equal to the right $a != $b
operand.
Not Identical !== It returns true if left operand is not equal to the right $a !== $b
operand, and they are of different type as well.
Greater than > It returns true if left operand is greater than the right $a > $b
operand.
Less than < It returns true if left operand is less than the right $a < $b
operand.
Greater than or >= It returns true if left operand is greater than or equal $a >= $b
equal to to the right operand.
Less than or <= It returns true if left operand is less than or equal to $a <= $b
equal to the right operand.
++$a Pre Increment, It will first increment the operand by 1(add one to it) and then use it
or return it.
$a++ Post Increment, It will first return the operand and then increment the operand by 1.
--$b Pre Decrement, It will first decrement the operand by 1(subtract one from it) and
then use it or return it.
$b-- Post Decrement, It will first return the operand and then decrement the operand
by 1.
These operators are very useful and handy when use loops or when we have simply increment
any value by one in our program/script.
And and or && It returns true if both the operands(or expressions) returns true. $a && $b
Xor xor It returns true if any one out of the two operands(or $a xor $b
expressions) returns true, but not when both return true.
// appending $b to $a
$a .= $b
echo $a;
?>
matrusri
matrusri
Identical === It returns true if both the arrays have same key/value $a === $b
pairs, in same order and of same type.
Not Equal != It returns true if both the arrays are not same. $a != $b
Not !== It returns true if both the arrays are not identical, based $a !== $b
Identical on type of value etc.
The if statement
When we want to execute some code when a condition is true, then we use if statement.
Syntax:
if(condition)
{
// code to be executed if 'condition' is true
}
Here is a simple example,
<?php
$age = 20;
$age = 26;
Its dangerous
In the example above, we have also used logical operator &&. Logical operators are very useful
while writing multiple conditions together.
You can specify as many options as you want using a single switch code block.
X can be a variable or an expression.
In a switch statement, we provide the deciding factor which can be a variable or an expression to
our switch statement, and then we specify the different cases, each with a value, a piece of code
and a break statement.
break statement is specified to break the execution of the switch statement once the action
related to a specified value has been performed.
If we do not specify a break statement, then all the switch cases, after the matched case, will get
executed, until the next break statement.
The default statement is executed if no matching case is there.
<?php
$car = "Jaguar";
switch($car)
{
case "Audi":
echo "Audi is amazing";
break;
case "Mercedes":
echo "Mercedes is mindblowing";
break;
case "Jaguar":
echo "Jaguar is the best";
break;
default:
echo "$car is Ok";
}
?>
For example, let's take the problem mentioned in the beginning of this tutorial. Let's print
numbers from 1 to 10.
<?php
$a = 1;
$a = 1;
do {
echo "$a | ";
$a++; // incrementing value of a by 1
} while($a <= 10)
?>
Let's take another example where even if the condition is false, still the loop will be executed
once.
<?php
$a = 11;
do {
echo $a;
$a++; // incrementing value of a by 1
} while($a <= 10)
?>
11
As we can see clearly, that the condition in the above do...while loop will return false because
value of variable $a is 11 and as per the condition the loop should be executed only if the value
of $a is less than or equal to 10.
1
2
3
4
5
6
7
8
9
10
?>
0 0
1 0
2 0
0 1
1 1
2 1
0 2
1 2
2 2
foreach($array as $var)
{
echo "$var <br/>";
}
?>
Jaguar
Audi
Mercedes
BMW
$a = 1;
switch($a)
{
case 1:
echo "This is case 1";
break;
case 2:
echo "This is case 2";
break;
default:
echo "This is default case";
}
?>
This is case 1
But what if we forget to add the break statement at the end of each case block in the switchstatement?
In that case, the execution will still start from the matching case, but will not exit out of
the switch statement and will keep on executing every code statement below it until the
next breakstatement.
<?php
$a = 2;
switch($a)
{
case 1:
echo "This is case 1";
case 2:
echo "This is case 2";
default:
echo "This is default case";
}
?>
This is case 2
This is default case
$x = 13;
?>
function function_name()
{
// function code statements
}
?>
?>
Hey Martha
Merry Christmas and a Very Happy New Year
Hey Jon
Merry Christmas and a Very Happy New Year
?>
Let's take a simple example:
<?php
// defining the function with argument
function greetings($festival)
{
echo "Wish you a very Happy $festival";
}
// next line
echo "<br/>";
?>
Hey Jai
Wish you a very Happy Diwali
Hey Jon
Wish you a very Happy New Year
As you can see in the example above, how we changed our greetings() function to start taking
arguments, and now it can be used for sending greetings for different festivals.
// next line
echo "<br/>";
?>
Hey Jai
Wish you a very Happy Diwali
Hey Jon
Wish you a very Happy Life
So when you forget to provide an argument while calling the function, to cover up, you can set
default values to the arguments to your functions.
?>
5 + 10 = 15
5 + 10 = 15
5 + 10 + 15 = 30
Unfortunately, PHP does not support Function Overloading.
This was just to give you an idea about what function overloading is. In PHP, function signatures
are only based on their names and do not include the argument lists, hence we cannot have two
functions with same name.
PHP 5 Arrays
An array is used to store multiple values, generally of same type, in a single variable.
For example if you have a list of festivals that you want to store together, or may be a list of
stationary items, or list of colors, then you can either keep them in separate variables, but then
you will have to create a lot of variables and they won't be related to each other.
In such case, PHP arrays are used. Arrays can store multiple values together in a single variable
and we can traverse all the values stored in the array using the foreach loop.
Creating an Array
We can create an array in PHP using the array() function.
Syntax:
<?php
/*
this function takes multiple values
separated by comma as input to create
an aray
*/
array();
?>
To access the data stored in an array, we can either use the index numbers or we can use
a foreachloop to traverse the array elements.
Index number for array elements starts from 0, i.e the first element is at the position 0, the second
element at position 1 and so on...
<?php
/*
a simple array with Lamborghini car names
*/
$lamborghinis = array("Urus", "Huracan", "Aventador");
// print the first car name
echo $lamborghinis[0];
echo "Urus is the latest Super SUV by Lamborghini";
?>
Urus
Urus is the latest Super SUV by Lamborghini
Advantages of Array
Here are a few advantages of using array in our program/script:
1. It's very easy to define simple list of related data, rather than creating multiple variables.
2. It's super easy to use and traverse using the foreach loop.
3. PHP provides built-in functions for sorting array, hence it can be used for sorting information
as well.
// array traversal
// find size of the array
$size = count($lamborghinis);
?>
name : Urus
type : SUV
brand : Lamborghini
name : Cayenne
type : SUV
brand : Prosche
name : Bentayga
type : SUV
brand : Bentley
In the above multidimensional array, we have the main array as indexed array and the arrays
stored as elements are associative.
Bu the main array can also be associative, let's take an example for it.
Also, as the index in associative array is not numeric and not sequentially, hence to find the index
values or keys(as data saved in associative array is in the form of key-value), we can use the
function array_keys() to get an array of the keys used in the associative array.
<?php
/*
multidimensional array initialization
*/
$cars = array(
"Urus" => array(
"type"=>"SUV",
"brand"=>"Lamborghini"
),
"Cayenne" => array(
"type"=>"SUV",
"brand"=>"Porsche"
),
"Bentayga" => array(
"type"=>"SUV",
"brand"=>"Bentley"
),
);
/*
array traversal
*/
// find size of the array
$size = count($lamborghinis);
// array keys
$keys = arra_keys($cars);
?>
Urus
type : SUV
brand : Lamborghini
Cayenne
type : SUV
brand : Prosche
Bentayga
type : SUV
brand : Bentley
sizeof($arr)
This function returns the size of the array or the number of data elements stored in the array.
It is just like count($arr) method, that we used in previous tutorials while traversing the array.
<?php
?>
is_array($arr)
To check whether the provided data is in form of an array, we can use the is_array() function. It
returns True if the variable is an array and returns False otherwise.
<?php
$mycar = "Urus";
?>
Array
not an Array
in_array($var, $arr)
When using an array, we may often want to check whether a certain value is present in the array
or not. For example, if get a list of certain cars, like we do in almost all our examples, to check if a
certain car is added into the array, we can use the in_array function.
Let's take an example and see,
<?php
Not yet!
As we can see unlike the other functions above, this one takes two arguments, one is the value
to be searched in the array, and the second one is the array itself.print_r($arr)
Although this is not an array function, but it deserves a special mention here, as we can use this
function to print the array in the most descriptive way possible. This function prints the complete
representation of the array, along with all the keys and values.
<?php
?>
Array (
[0] => "Urus"
[1] => "Huracan"
[2] => "Aventador"
)
array_merge($arr1, $arr2)
If you want to combine two different arrays into a single array, you can do so using this function.
It doesn't matter whether the arrays to be combined are of same type(indexed, associative etc) or
different types, using this function we can combine them into one single array.
Let's take an example where we will merge an indexed array and an associative array.
<?php
$hatchbacks = array(
"Suzuki" => "Baleno",
"Skoda" => "Fabia",
"Hyundai" => "i20",
"Tata" => "Tigor"
);
print_r($merged);
?>
Array (
[Suzuki] => Baleno
[Skoda] => Fabia
[Hyundai] => i20
[Tata] => Tigor
[0] => Vinod
[1] => Javed
[2] => Navjot
[3] => Samuel
)
array_values($arr)
In an array, data is stored in form of key-value pairs, where key can be numerical(in case of
indexed array) or user-defined strings(in case of associative array) and values.
If we want to take all the values from our array, without the keys, and store them in a separate
array, then we can use array_values() function.
Let's take the array $merged formed in the example above,
<?php
$hatchbacks = array(
"Suzuki" => "Baleno",
"Skoda" => "Fabia",
"Hyundai" => "i20",
"Tata" => "Tigor"
);
print_r($merged);
?>
Array (
[0] => Baleno
[1] => Fabia
[2] => i20
[3] => Tigor
[4] => Vinod
[5] => Javed
[6] => Navjot
[7] => Samuel
)
array_keys($arr)
Just like values, we can also extract just the keys from an array. Let's use this function to extract
the keys from the array $merged.
<?php
print_r($keys);
?>
Array (
[0] => Suzuki
[1] => Skoda
[2] => Hyundai
[3] => Tata
[4] => 0
[5] => 1
[6] => 2
[7] => 3
)
array_pop($arr)
This function removes the last element of the array. Hence it can be used to remove one element
from the end.
<?php
print_r($lamborghinis);
?>
Array (
[0] => Urus
[1] => Huracan
)
array_push($arr, $val)
This function is the opposite of the array_pop() function. This can be used to add a new element
at the end of the array.
<?php
print_r($lamborghinis);
?>
Array (
[0] => Urus
[1] => Huracan
[2] => Aventador
[3] => Estoque
)
array_shift($arr)
This function can be used to remove/shift the first element out of the array. So, it is just
like array_pop() function but different in terms of the position of the element removed.
<?php
$lamborghinis = array("Urus", "Huracan", "Aventador");
print_r($lamborghinis);
?>
Array (
[0] => Huracan
[1] => Aventador
)
Similar to this, we have another function array_unshift($arr, $val) to add a new value($val) at
the start of the array(as the first element).
sort($arr)
This function sorts the array elements in ascending order. In case of a string value array, values
are sorted in ascending alphabetical order.
Some other sorting functions are: asort(), arsort(), ksort(), krsort() and rsort().
<?php
print_r($lamborghinis);
?>
Array (
[0] => Aventador
[1] => Estoque
[2] => Huracan
[3] => Urus
)
array_map('function_name', $arr)
If you want to perform certain operation on all the values stored in an array, you can do it by
iterating over the array using a for loop or foreach and performing the required operation on all
the values of the array.
Or, you can use the function array_map(). All we have to do is define a separate function to which
we will provide the values stored in the array one by one(one at a time) and it will perform the
operation on the values. Let's have an example,
<?php
function addOne($val) {
// adding 1 to input value
return ($val + 1);
}
$numbers = array(10, 20, 30, 40, 50);
print_r($numbers)
?>
Array (
[0] => 11
[1] => 21
[2] => 31
[3] => 41
[4] => 51
)
The function array_walk($arr, 'function_name') works just like the array_map() function.
array_flip($arr)
This function interchange the keys and the values of a PHP associative array.
<?php
$hatchbacks = array(
"Suzuki" => "Baleno",
"Skoda" => "Fabia",
"Hyundai" => "i20",
"Tata" => "Tigor"
);
?>
Array (
[Baleno] => Suzuki
[Fabia] => Skoda
[i20] => Hyundai
[Tigor] => Tata
)
array_reverse($arr)
This function is used to reverse the order of elements, making the first element last and last
element first, and similarly rearranging other array elements.
<?php
?>
Array (
[0] => 50
[1] => 40
[2] => 30
[3] => 20
[4] => 10
)
array_rand($arr)
If you want to pick random data element from an array, you can use the array_rand() function.
This function randomly selects one element from the given array and returns it.
In case of indexed array, it will return the index of the element, in case of associative array, it will
return the key of the selected random element.
<?php
?>
print_r(array_slice($colors, 2, 3));
?>
Array (
[0] => blue
[1] => green
[2] => white
)
PHP 5 Strings
Just like any other programming language, Strings in Php are also a collection of alphanumeric
characters, enclosed in single quotes for simple string data and double quotes for complex string data.
?>
We can define a string using double quotes as well as single quotes.
But, what if the string has a single or double quote in it, then what?
<?php
?>
Both the above string definitions will result in error, as we cannot include a double quote in the string,
if the string is defined inside double quotes.
But it will work, if the string contains double quotes, but it is defined using single quotes and vice
versa, for example,
<?php
?>
There is one more simple technique to deal with the quotes problem, it is known as Escaping Special
Character, which can be done using a backslash.
Let's take an example,
<?php
echo $str1;
echo "\n"; // new line
echo $str2;
?>
// string with $
$srt1 = "pas$word";
echo $str1;
?>
echo $str1;
?>
pas$word
echo $str;
?>
Take a right from the T point, and the go straight to fins the "Shop"
Here EOT is just a synonymn for end of text, which means nothing. These 3 characters are just to
mark the start and end of the multiline string.
You can use EOF or maybe SQL if you use this to define your multiline SQL query, like,
<?php
$tablename = "products";
echo $str;
?>
$hername = "Selena";
echo $str;
?>
$hername = "Selena";
echo "\n";
?>
Selena
$hername, hello!
Selena, hello!
See the difference, single quotes does not parse the text inside it, hence the variable is not translated
into its value, while in case of double quotes, it is.
strlen($str)
This function returns the length of the string or the number of characters in the string including
whitespaces.
<?php
?>
str_word_count($str)
This function returns the number of words in the string. This function comes in handly in form
field validation for some simple validations.
<?php
?>
strrev($str)
This function is used to reverse a string.
Let's take an example and see,
<?php
?>
strpos($str, $text)
This function is used to find the position of any text/word in a given string. Just like an array,
string also assign index value to the characters stored in it, starting from zero.
<?php
?>
echo $str;
?>
Welcome to Matrusri.com
ucwords($str)
This function is used for formatting the string. This function converts first letter/character of every
word in the string to uppercase.
Let's take an example and see,
<?php
echo ucwords($str);
?>
Welcome To Matrusri
strtoupper($str)
To convert every letter/character of every word of the string to uppercase, one can
use strtoupper()method.
<?php
echo strtoupper($str);
?>
WELCOME TO MATRUSRI
strtolower($str)
This function is used to convert every letter/character of a string to lowercase.
<?php
echo strtolower($str);
?>
welcome to matrusri
str_repeat($str, $counter)
This function is used to repeat a string a given number of times. The first argument is the string
and the second argument is the number of times the string should be repeated.
<?php
$str = "Matrusri";
?>
MatrusriMatrusriMatrusriMatrusri
strcmp($str1, $str2)
This function is used to compare two strings. The comparison is done alphabetically. If the first
string is greater than second string, the result will be greater than 0, if the first string is equal to
the second string, the result will be equal to 0 and if the second string is greater than the first
string, then the result will be less than 0.
<?php
$str1 = "Matrusri";
$str2 = "Matrusri.com";
?>
-4
4
0
substr($str, $start, $length)
This function is used to take out a part of the string(substring), starting from a particular position,
of a particular length.
The first argument is the string itself, second argument is the starting index of the substring to be
exracted and the third argument is the length of the substring to be extracted.
<?php
?>
Matrusri
trim($str, charlist)
This function is used to remove extra whitespaces from beginning and the end of a string. The
second argument charlist is optional. We can provide a list of character, just like a string, as the
second argument, to trim/remove those characters from the main string.
<?php
echo trim($str2,"Heo");
?>
Hello World
llo Hell
As you can see in the output, additional spaces from the beginning and end are removed and in
the second case, the characters specified are removed from the beginning and the end of the
string.
implode(separator, $arr)
This function is used to form a string using the array elements from the array provided and join
them using the separator.
Let's take an example,
<?php
?>
nl2br($str)
This function is used to change line break or \n to the HTML tag for line break, which is <br>.
This function is very useful to format string data to display on HTML pages because when a
multiline form data is submitted, it has \n included in the strnig for line breaks, but when you
display it on your HTML page, the line breaks will not get rendered because HTML doesn't
understand \n.
<?php
?>
Its a
beautiful day
</body>
</html>
In the code above, we have used the <form> tag to create an HTML form, with input fields for
Name and Email along with submit button to submit the form-data.
In the <form> tag, we have two attributes, action and method, do you know what they are for?
1. action: Using this attribute, we can specify the name of the file which will collect and handle
the form-data. In the example above, we have provided name of a Php file.
2. method: This attribute specify the means of sending the form-data, whether it will be submitted
via POST method or GET method.
Below we have the same form with method as GET,
<html>
<body>
</body>
</html>
?>
Hi, Matrusri
Your email address: [email protected]
You will get the above output, if you provide name as "Matrusri" and email address as
"[email protected]".
?>
Hi, Matrusri
Your email address: [email protected]
Again, the output remains the same.
The first step to process the form-data is to fetch the data using POST or GET superglobals,
once you have the data, you can do anything with it, display it on your webpage, save the data
into database, perform validations etc.
</body>
</html>
We have two input fields in above form, one is name and the other one is age. When we click on
submit, we will be redicrected to the following URL, form-handler.php?name=Matrusri&age=5,
with the form-data appended to the URL.
Sending the form-data as URL parameters proves out useful at times as you can
easily bookmark links with form-data, but for appending parameters in a URL there is a limit
of 2000 characters, hence for forms with large number of fields, it is not suggested, as some
data might get lost or the form submission may lead to error.
The Php file form-handler.php will look like,
<?php
echo "Your name is ". $name . " and you are ". $age . " years old".
?>
</body>
</html>
The Php file form-handler.php will look like,
<?php
echo "Your name is ". $name . " and you are ". $age . " years old".
?>
About Me:<br/>
<textarea name="aboutme"></textarea> <br/>
Gender:
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="male"> Male
<br/>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
The PHP Code
In the above form we are asking the user for 4 different inputs, let's see how we can fetch the
submitted values for the fields in PHP.
<?php
?>
Easy, right? Yes, to access the form-data for different types of HTML form elements, all you need
is $_POST.
But an HTML form is a great entry point for hackers to play around by entering script or some
malicious code into the input fields to cause some error/issue in your PHP script.
To tackle with it, it's good to put some validations in the PHP code for validating the user inputs
submitted in the form-data.
?>
In the code above we are checking whether the user has entered name value in the form or not,
similarly you can put a check on all the mandatory form fields.
To validate email address, there is a special function available in PHP which we can use to
validate email addresses. The function is filter_var($email, FILTER_VALIDATE_EMAIL), let's see
how it works.
<?php
// getting the value of the email field
$email = $_POST["email"];
?>
The filter_var() function returns true for a valid email address and returns false for an invalid
email address.
Validating a form in PHP depends on your requirements too. For example, if you don't have any
mandatory fields in your form, then you don't have to worry about checking whether the
submitted values are empty or not.
If you have email address field, we suggest you validate it.
You can even add more validations like checking the input for malicious codes like <script> tags
using regular expressions.
What is $_SERVER["PHP_SELF"]?
Sometimes we can avoid having an extra PHP file to handle/process the form-data and can
include the PHP code in the file with the HTML form itself.
In such scenarios, we will have to submit the form to the same webpage again, and we can
use $_SERVER["PHP_SELF"] as the form action.
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
What this superglobal does is that it returns the filename of the current webpage, which then acts
as the action script.
But as this returns the existing filename from the URL, you must be a little careful because users
may inject some unwanted code from the URL, so to avoid it, we can use
the htmlspecialchars() function to convert any special character in the string(URL in this case)
into HTML entities.
So you should use,
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
Cookies in PHP 5
Cookie is a small piece of information stored as a file in the user's browser by the web server.
Once created, cookie is sent to the web server as header information with every HTTP request.
You can use cookie to save any data but it should not exceed 1K(1024 bytes) in size.
Before we move on to how to create, update and delete a cookies, let's learn a few realworld use
of cookies.
Types of Cookies
There are two types of cookies, they are:
1. Session Cookie: This type of cookies are temporary and are expire as soon as the session
ends or the browser is closed.
2. Persistent Cookie: To make a cookie persistent we must provide it with an expiration time.
Then the cookie will only expire after the given expiration time, until then it will be a valid
cookie.
name Used to specify the name of the cookie. It is a mandatory argument. Name of the
cookie must be a string.
value Used to store any value in the cookie. It is generally saved as a pair with name. For
example, name is userid and value is 7007, the userid for any user.
expire Used to set the expiration time for a cookie. if you do not provide any value, the
cookie will be treated as a session cookie and will expire when the browser is
closed.
path Used to set a web URL in the cookie. If set, the cookie will be accessible only from
that URL. To make a cookie accessible through a domain, set '/' as cookie path.
domain The domain of your web application. It can be used to limit access of cookie for
sub-domains. For example, if you set the domain value as wwww.matrusri.com,
then the cookie will be inaccessible from blog.matrusri.com
secure If you set this to 1, then the cookie will be available and sent only over HTTPS
connection.
So if we want to create a cookie to store the name of the user who visited your website, and set
an expiration time of a week, then we can do it like this,
<?php
?>
To access a stored cookie we use the $_COOKIE global variable, and can use the isset() methos
to check whether the cookie is set or not.
Let's have a complete example where we will set a cookie and then retrieve it to show its value in
the HTML page.
<?php
// set the cookie
setcookie("username", "iamabhishek", time()+60*60*24*7);
?>
<html>
<body>
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>
</body>
</html>
So by providing the name of the cookie inside the square brakets with the global
variable $_COOKIE[]we can access the cookie.
NOTE: setcookie() function should be placed before the starting HTML tag(<html>).
<?php
// check if the cookie exists
if(isset($_COOKIE["username"]))
{
echo "Cookie set with value: ".$_COOKIE["username"];
}
else
{
echo "cookie not set!";
}
?>
</body>
</html>
We just update the value of username cookie from iamabhishek to iamNOTabhishek.
<?php
echo "cookie username is deleted!";
?>
</body>
</html>
And with this, we now know how to create a cookie, how to update it and how to delete it when
we no longer need it. Next up, Sessions!
Sessions in PHP 5
To store information accessible accross web pages, we use sessions. Session is not stored on
the user browser like cookie, hence it is a more secure option.
As we know HTTP is a stateless protocol, if a user visits a webpage and perform some action,
there is no way to remember what he did when the user navigates to the next webpage.
Let's take a practical example, when you log into your facebook account, by providing your email
address and password, until and unless you logout, the web application remembers who you are
and display what your friends are posting and liking on your News Feed, you can update your
profile, send someone message, join a group etc, this is accomplished by Session.
When a user logs into their account on any web application, a session is created for them, and in
the session their username or userid or some other unique identifier is stored, which is then used
on the consecutive webpages to show information specific to that user. On logout, the session is
destroyed.
Session is not limited by any size limit, you can store any information in the session, irrespective
of its size.
Before we move on to how to start, update and end a session in PHP, let's learn a few realworld
use of session.
<html>
<body>
<?php
echo "Session variable is set.";
?>
</body>
</html>
NOTE: The function session_start() should be the first statement of the page, before any HTML
tag.
<html>
<body>
<?php
echo "Username is: ".$username."<br/>";
echo "User id is: ".$userid;
?>
</body>
</html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
Array (
[username] => iamabhishek,
[userid] => 1
)
<html>
<body>
<?php
echo "Username is: ".$username."<br/>";
echo "User id is: ".$userid;
?>
</body>
</html>
<html>
<body>
<?php
// clean the session variable
session_unset();
</body>
</html>
We use these functions on pages like logout or checkout in case of an eCommerce website to
clean the session variable off the user specific data and to eventually destroy the current session.
Write mode w If the file exists then it is opened to allow write operation in it and if
it doesn't exist, then a new file is created. In this mode all the
existing data in file gets erased.
Read mode r File is opened in read mode with the file pointer starting from the
beginning of the file.
Append a File is opened in write mode where existing content of the file is
mode note erased. The new content in added after the existing content.
Create x A new file is created with write-only access. If the file already exists
Write-only then error is returned.
file
Apart from the mode specified above, we can add + along with the string literals to allow both
read and write(default) operation for a given mode.
For example, r+ mode opens file for read and write both. w+, a+ allow read operation on the file
along with the default write and append operations respectively.
Technically, file is not opened, fopen() binds the resource(file) to a stream, which can then be
used to read from the file or write data to the file.
Also, the filename should be fully qualified name along with relative path if the file is a local file.
The filename can also be a URL to specify a remote fiel's path. In that case, once PHP realise
that the file path is not local, it will check for the value of allow_url_fopen property in
the php.ini(PHP's configuration file). If it is false, PHP will print a warning and fopen() call will
fail.
// closing a file
fclose($handle);
Below is the code we will keep in the read-file.php file to open file.txt text file to write data in it.
$myfile = 'include/file.txt';
//opens the file.txt file
$handle = fopen($myfile, 'w') or die('Cannot open file: '.$myfile);
// close a file
fclose($handle);
We can either provide complete path for the file to be read or we can provide relative path like in
the example above.
In the upcoming tutorials we will learn how to read, write, append data to a file.
2. and the second argument specifies the size in bytes for the content to be read.
Let's take an example, if we have a file matrusri.txt with following content:
Matrusri is for coding enthusiasts!
If we want to read entire content of the file, we will open the file in read mode and then use
the fread() function.
<?php
// Opening a file
$myfile = fopen("matrusri.txt", "r");
Matrusri
Regular Expressions
Regular expressions are nothing more than a sequence or pattern of characters
itself. They provide the foundation for pattern-matching functionality.
Using regular expression you can search a particular string inside a another
string, you can replace one string by another string and you can split a string
into many chunks.
PHP offers functions specific to two sets of regular expression functions, each
corresponding to a certain type of regular expression. You can use any of them
based on your comfort.
POSIX Regular Expressions
PERL Style Regular Expressions
1 [0-9]
It matches any decimal digit from 0 through 9.
2 [a-z]
It matches any character from lower-case a through lowercase z.
3 [A-Z]
It matches any character from uppercase A through uppercase Z.
4 [a-Z]
It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to
match any decimal digit ranging from 0 through 3, or the range [b-v] to match
any lowercase character ranging from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single
characters can be denoted by a special character. Each special character having
a specific connotation. The +, *, ?, {int. range}, and $ flags all follow a
character sequence.
Sr.No Expression & Description
1 p+
It matches any string containing at least one p.
2 p*
It matches any string containing zero or more p's.
3 p?
It matches any string containing zero or one p's.
4 p{N}
It matches any string containing a sequence of N p's
5 p{2,3}
It matches any string containing a sequence of two or three p's.
6 p{2, }
It matches any string containing a sequence of at least two p's.
7 p$
It matches any string with p at the end of it.
8 ^p
It matches any string with p at the beginning of it.
Examples
Following examples will clear your concepts about matching characters.
Sr.No Expression & Description
1 [^a-zA-Z]
It matches any string not containing any of the characters ranging from a
through z and A through Z.
2 p.p
It matches any string containing p, followed by any character, in turn
followed by another p.
3 ^.{2}$
It matches any string containing exactly two characters.
4 <b>(.*)</b>
It matches any string enclosed within <b> and </b>.
5 p(hp)*
It matches any string containing a p followed by zero or more instances
of the sequence php.
1 [[:alpha:]]
It matches any string containing alphabetic characters aA through zZ.
2 [[:digit:]]
It matches any string containing numerical digits 0 through 9.
3 [[:alnum:]]
It matches any string containing alphanumeric characters aA through zZ
and 0 through 9.
4 [[:space:]]
It matches any string containing a space.
1 ereg()
The ereg() function searches a string specified by string for a string
specified by pattern, returning true if the pattern is found, and false
otherwise.
2 ereg_replace()
The ereg_replace() function searches for string specified by pattern and
replaces pattern with replacement if found.
3 eregi()
The eregi() function searches throughout a string specified by pattern for
a string specified by string. The search is not case sensitive.
4 eregi_replace()
The eregi_replace() function operates exactly like ereg_replace(), except
that the search for pattern in string is not case sensitive.
5 split()
The split() function will divide a string into various elements, the
boundaries of each element based on the occurrence of pattern in string.
6 spliti()
The spliti() function operates exactly in the same manner as its sibling
split(), except that it is not case sensitive.
7 sql_regcase()
The sql_regcase() function can be thought of as a utility function,
converting each character in the input parameter string into a bracketed
expression containing two characters.