0% found this document useful (0 votes)
40 views79 pages

Unit III Scripting Essentials Unit III Scripting Essentials

The document covers scripting essentials, focusing on the differences between client-side and server-side scripting, with an emphasis on PHP as a widely used server-side language. It explains the need for scripting languages, their working principles, and provides examples of PHP syntax, variables, and functions. Additionally, it discusses the installation of PHP and various features that make it a popular choice for web development.

Uploaded by

Deshma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views79 pages

Unit III Scripting Essentials Unit III Scripting Essentials

The document covers scripting essentials, focusing on the differences between client-side and server-side scripting, with an emphasis on PHP as a widely used server-side language. It explains the need for scripting languages, their working principles, and provides examples of PHP syntax, variables, and functions. Additionally, it discusses the installation of PHP and various features that make it a popular choice for web development.

Uploaded by

Deshma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

lOMoARcPSD|32195777

Unit III Scripting essentials

Web Essentials (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Deshma ([email protected])
lOMoARcPSD|32195777

UNIT III SCRIPTING ESSENTIALS 9


Need for Scripting languages - Types of scripting languages - Client side scripting - Server side
scripting - PHP - Working principle of PHP - PHP Variables - Constants - Operators – Flow Control
and Looping - Arrays - Strings - Functions - File Handling - PHP and MySQL - PHP and HTML -
Cookies - Simple PHP scripts.

Client-side scripting vs. server-side scripting:


a comparison
The internet has always been based on one simple principle: all kinds of content is provided by
web servers and can be received by clients via HTTP or FTP. Clients are browsers, of which the
best-known ones include Mozilla Firefox and Google Chrome. These can be installed and used
on the user’s system. Web servers such as Apache and NGINX, on the other hand, are
components of web projects; these are also installed and run in this environment and allow the
respective client access to the content.

While static content like typical HTML elements and images can easily be transferred and
displayed, dynamic content such as a Wiki, a drop-down menu, or a web application, will only
function with scripts. These must be executed and interpreted with the appropriate scripting
language, which can either occur server-side or client-side. For this reason, a distinction must be
made between server-side scripting and client-side scripting.

What is server-side scripting?


Server-side scripting examples

 ActiveVFP.
 ASP.
 C.
 DC.
 Java.
 JavaScript (using Server-side JavaScript (SSJS) e.g., node.js)
 Perl.
 PHP.

Server-side scripting is a technique that is used to develop websites and implement dynamic
elements and web applications. It’s based on the use of scripts that are carried out by the web
server using the appropriate scripting languages when a client requests the corresponding
content. The script’s task is often to retrieve the appropriate data from a database and integrate it
into the web project. The user accesses these via HTML pages, while the script source codes
remain completely hidden. The use of server-side scripts requires the client to send multiple
requests to the web server to provide the user with new information. This means, on the one
hand, high utilization of the server's capacity, which has an impact on the response time of the
web server, and on the other hand, that an existing connection to the server is indispensable for
making use of the web offer.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

In the early days of the World Wide Web, server-side scripting was almost exclusively
implemented by writing developer programs in C, as well as Perl and command line scripts.
These applications were carried out and interpreted by server operating systems, at which time
the result could be passed from the web server to the browser via the common gateway interface
(CGI). Many modern web servers can now also run scripts directly, i.e. using corresponding
modules. Launched in 1995 and based on C and Perl, PHP is the most widely used server-side
scripting language today. The following table shows a selection of the programming languages
used for server-side scripts:

What is client-side scripting?


Client-side | Languages Example

 JavaScript.
 VBScript.
 HTML (Structure)
 CSS (Designing)
 AJAX.
 jQuery etc.

Client-side scripting is another technique used by web developers to create projects with
dynamic content. Unlike the server-side variant, however, the client executes and processes the
programmed scripts, not the server. For this purpose, the scripts are either embedded into the
HTML or XHTML document, or written into a separate file linked to the document. If the user
now tries to access a webpage or application with such a client-side script, the web server sends
the HTML document and the script to the browser, which performs the same execution,
presenting the final result. Client-side scripts can also contain concrete instructions for the web
browser, determining how it should react to users’ actions, e.g. clicking on a button. Often, the
client doesn’t need to re-establish a connection to the web server.

As the scripts are executed in the user’s browser, the user has the option to view the source code
– unlike with server-side scripts. In turn, the interpretation of the scripts requires the
corresponding script language to be understood by the web browser. There are also various
browser extensions available, which can block scripts, as client-side scripting applications, such
as pop-ups and web-tracking tools, can have a negative impact on the loading times.

The most significant client-side script language is JavaScript. Developed by the Mozilla
predecessor, Netscape, and launched in 1995 with the previous version of the browser, Navigator
2.0 – then known as LiveScript. The script language caught on quickly, eventually becoming the
universal scripting language of all relevant web browsers. Shockwave Flash (SWF) is also
worth a mention, despite its considerable drawbacks. The object-oriented language is an
important component of Adobe’s Flash Player, which for a long time was the measure of all
things for videos on the internet. However, with all its security gaps and the introduction of new
technology, such as HTML5, the once popular Flash video has now faded into the background.
In the early days of the internet, Microsoft Silverlight and Java Applets also enjoyed a great deal
of popularity.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

In theory, it’s also possible to use other scripting languages for client-side scripting, but the
developers of the relevant browsers must choose to support them. There are, however, alternative
solutions that allow client-side scripts with other languages. For this purpose, the respective code
can be interpreted and executed as JavaScript using a transpiler like CoffeeScript or TypeScript.

What is PHP
PHP is a open source, interpreted and object-oriented scripting language i.e. executed at server
side. It is used to develop web applications (an application i.e. executed at server side and
generates dynamic page).

What is PHP

 PHP is a server side scripting language.


 PHP is an interpreted language, i.e. there is no need for compilation.
 PHP is an object-oriented language.
 PHP is an open-source scripting language.
 PHP is simple and easy to learn language.

Note: An interpreted language is a type of programming language for which most of its
implementations execute instructions directly and freely, without previously compiling a program into
machine-language instructions. The interpreter executes the program directly, translating each statement
into a sequence of one or more subroutines already compiled into machine code.

PHP Features

There are given many features of PHP.

 Performance: Script written in PHP executes much faster then those scripts written in other
languages such as JSP & ASP.
 Open Source Software: PHP source code is free available on the web, you can developed all the
version of PHP according to your requirement without paying any cost.
 Platform Independent: PHP are available for WINDOWS, MAC, LINUX & UNIX operating
system. A PHP application developed in one OS can be easily executed in other OS also.
 Compatibility: PHP is compatible with almost all local servers used today like Apache, IIS etc.
 Embedded: PHP code can be easily embedded within HTML tags and script.

Install PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It is
available for all operating systems. There are many AMP options available in the market that are
given below:

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

 WAMP for Windows


 LAMP for Linux
 MAMP for Mac
 SAMP for Solaris
 FAMP for FreeBSD
 XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some other
components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail etc.

If you are on Windows and don't want Perl and other features of XAMPP, you should go for
WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.

PHP Example
It is very easy to create a simple PHP example. To do so, create a file and write HTML tags +
PHP code and save this file with .php extension.

All PHP code goes between php tag. A syntax of PHP tag is given below:

1. <?php
2. //your code here
3. ?>

File: first.php

1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
5. echo "<h2>Hello First PHP</h2>";
6. ?>
7. </body>
8. </html>

Save in c:\htdocs\first.php

To run:Open browser and type http://localhost/first.php

PHP Echo
PHP echo is a language construct not a function, so you don't need to use parenthesis with it. But
if you want to use more than one parameters, it is required to use parenthesis.

The syntax of PHP echo is given below:

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

1. void echo ( string $arg1 [, string $... ] )

PHP echo statement can be used to print string, multi line strings, escaping characters, variable,
array etc.

PHP echo: printing string


File: echo1.php

1. <?php
2. echo "Hello by PHP echo";
3. ?>

Output:

Hello by PHP echo

PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with the
argument list. Unlike echo, it always returns 1.

The syntax of PHP print is given below:

1. int print(string $arg)

PHP print statement can be used to print string, multi line strings, escaping characters, variable,
array etc.

PHP print: printing string


File: print1.php

1. <?php
2. print "Hello by PHP print ";
3. print ("Hello by PHP print()");
4. ?>

Output:

Hello by PHP print Hello by PHP print()

Difference between echo and print:

They are:

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

 print only takes one parameter, while echo can have multiple parameters.
 print returns a value (1), so can be used as an expression.
 echo is slightly faster.

To add to the answers above, while print can only take one parameter, it will allow for concatenation of
multiple values, ie:

$count = 5;

print "This is " . $count . " values in " . $count/5 . " parameter";

This is 5 values in 1 parameter

PHP Variables
A variable in PHP is a name of memory location that holds data. A variable is a temporary
storage that is used to store data temporarily.

In PHP, a variable is declared using $ sign followed by variable name.

Syntax of declaring a variable in PHP is given below:

1. $variablename=value;

PHP Variable: Declaring string, integer and float

Let's see the example to store string, integer and float values in PHP variables.

File: variable1.php

1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>

Output:

string is: hello string


integer is: 200
float is: 44.6

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

PHP Variable: case sensitive

In PHP, variable names are case sensitive. So variable name "color" is different from Color,
COLOR, COLor etc.

File: variable3.php

1. <?php
2. $color="red";
3. echo "My car is " . $color . "<br>";
4. echo "My house is " . $COLOR . "<br>";
5. echo "My boat is " . $coLOR . "<br>";
6. ?>

Output:

My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is

PHP Variable: Rules

PHP variables must start with letter or underscore only.

PHP variable can't be start with numbers and special symbols.

File: variablevalid.php

1. <?php
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4.
5. echo "$a <br/> $_b";
6. ?>

Output:

hello
hello

PHP: Loosely typed language

PHP is a loosely typed language, it means PHP automatically converts the variable to its correct
data type.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

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.

PHP has three different variable scopes:

 local
 global
 static

Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:

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();

echo "<p>Variable x outside function is: $x</p>";


?>

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();

// using x outside the function will generate an error

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

echo "<p>Variable x outside function is: $x</p>";


?>

PHP The global Keyword

The global keyword is used to access a global variable from within a function.

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
?>

PHP The static Keyword

Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.

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();
?>

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.

Note: The variable is still local to the function.

Output:

PHP $ and $$ Variables


The $var (single dollar) is a normal variable with the name var that stores any value like string,
integer, float, etc.

The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.

To understand the difference better, let's see some examples.

Example 1

1. <?php
2. $x = "abc";
3. $$x = 200;
4. echo $x."<br/>";
5. echo $$x."<br/>";
6. echo $abc;
7. ?>

Output:

Abc

200

200

In the above example, we have assigned a value to the variable x as abc. Value of reference
variable $$x is assigned as 200.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Now we have printed the values $x, $$x and $abc.

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:

1. Using define() function


2. Using const keyword

PHP constants follow the same PHP variable rules. For example, it can be started with letter or
underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

PHP constant: define()

Let's see the syntax of define() function in PHP.

1. define(name, value, case-insensitive)

1. name: specifies the constant name


2. value: specifies the constant value
3. case-insensitive: Default value is false. It means it is case sensitive by default.

Let's see the example to define PHP constant using define().

File: constant1.php

1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP");
3. echo MESSAGE;
4. ?>

Output:

Hello JavaTpoint PHP

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

File: constant2.php

1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>

Output:

File: constant3.php

1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>

Output:

Hello JavaTpoint PHP


Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message

PHP constant: const keyword

The const keyword defines constants at compile time. It is a language construct not a function.

It is bit faster than define().

It is always case sensitive.

File: constant4.php

1. <?php
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE;
4. ?>

Output:

Hello const by JavaTpoint PHP

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

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
__LINE__ Represents current line number where it is used.
Represents full path and file name of the file. If it is used inside an include,
__FILE__
name of included file is returned.
Represents full directory path of the file. Equivalent to dirname(__file__). It
__DIR__ does not have a trailing slash unless it is a root directory. It also resolves
symbolic link.
Represents the function name where it is used. If it is used outside of any
__FUNCTION__
function, then it will return blank.
Represents the function name where it is used. If it is used outside of any
__CLASS__
function, then it will return blank.
Represents the trait name where it is used. If it is used outside of any
__TRAIT__
function, then it will return blank. It includes namespace it was declared in.
Represents the name of the class method where it is used. The method name
__METHOD__
is returned as it was declared.
__NAMESPACE__ Represents the name of the current namespace.

Example

Let's see an example for each of the above magical constants.

File Name: magic.php

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

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

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>";

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

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. ?>

PHP Data Types


PHP data types are used to hold different types of data or values. PHP supports 8 primitive data
types that can be categorized further in 3 types:

1. Scalar Types
2. Compound Types
3. Special Types

PHP Data Types: Scalar Types(as they can hold only a single data item they are
known as scalar data types)

There are 4 scalar data types in PHP.

1. boolean
2. integer
3. float
4. string

PHP Data Types: Compound Types(can hold more than one data item)

There are 2 compound data types in PHP.

1. array
2. object

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

PHP Data Types: Special Types

There are 2 special data types in PHP.

1. resource
2. NULL

PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. For example:

1. $num=10+20;//+ is the operator and 10,20 are operands

In the above example, + is the binary + operator, 10 and 20 are operands and $num is variable.

PHP Operators can be categorized in following forms:

 Arithmetic Operators
 Comparison Operators
 Bitwise Operators
 Logical Operators
 String Operators
 Incrementing/Decrementing Operators
 Array Operators
 Type Operators
 Execution Operators
 Error Control Operators
 Assignment Operators

We can also categorize operators on behalf of operands. They can be categorized in 3 forms:

 Unary Operators: works on single operands such as ++, -- etc.


 Binary Operators: works on two operands such as binary +, -, *, / etc.
 Ternary Operators: works on three operands such as "?:".

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

PHP Operators Precedence

Let's see the precedence of PHP operators with associativity.

Operators Additional Information Associativity

clone new clone and new non-associative

[ array() left

** arithmetic right

++ -- ~ (int) (float) (string) (array) (object) (bool) @ increment/decrement and types right

Instanceof types non-associative

! logical (negation) right

*/% arithmetic left

+-. arithmetic and string concatenation left

<< >> bitwise (shift) left

< <= > >= comparison non-associative

== != === !== <> comparison non-associative

& bitwise AND left

^ bitwise XOR left

| bitwise OR left

&& logical AND left

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

|| logical OR left

?: ternary left

= += -= *= **= /= .= %= &= |= ^= <<= >>= => assignment right

And logical left

Xor logical left

Or logical left

, many uses (comma) left

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.

PHP Single Line Comments

There are two ways to use single line comments in PHP.

 // (C++ style single line comment)


 # (Unix Shell style single line comment)

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:

Welcome to PHP single line comments

PHP Multi Line Comments

In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /* */.
Let's see a simple example of PHP multiple line comment.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

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. ?>

PHP Multi Line Comments

In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /* */.
Let's see a simple example of PHP multiple line comment.

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:

Welcome to PHP multi line comment

PHP CONTROL STATEMENTS

PHP If Else
PHP if else statement is used to test condition. There are various ways to use if statement in PHP.

 if
 if-else
 if-else-if
 nested if

PHP If Statement

PHP if statement is executed if condition is true, otherwise else will be executed.

Example

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

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

PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works like
PHP if-else-if statement.

Syntax

switch(expression){

case value1:

//code to be executed

break;

case value2:

//code to be executed

break;

......

default:

code to be executed if all cases are not matched;

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

PHP Switch Example

1. <?php
2. $num=20;
3. switch($num){
4. case 10:
5. echo("number is equals to 10");
6. break;
7. case 20:
8. echo("number is equal to 20");
9. break;
10. case 30:
11. echo("number is equal to 30");
12. break;
13. default:
14. echo("number is not equal to 10, 20 or 30");
15. }
16. ?>

Output:

number is equal to 20

PHP For Loop


PHP for loop can be used to traverse set of code for the specified number of times.

It should be used if number of iteration is known otherwise use while loop.

Syntax

1. for(initialization; condition; increment/decrement){


2. //code to be executed
3. }
4. <?php
5. for($n=1;$n<=10;$n++){
6. echo "$n<br/>";
7. }
8. ?>

Output:

1
2
3
4

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

5
6
7
8
9
10

PHP While Loop


PHP while loop can be used to traverse set of code like for loop.

It should be used if number of iteration is not known.

Syntax

1. while(condition){
2. //code to be executed
3. }

PHP While Loop Example

1. <?php
2. $n=1;
3. while($n<=10){
4. echo "$n<br/>";
5. $n++;
6. }
7. ?>

Output:

1
2
3
4
5
6
7
8
9
10

PHP do while loop


PHP do while loop can be used to traverse set of code like php while loop. The PHP do-while
loop is guaranteed to run at least once.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

It executes the code at least one time always because condition is checked after executing the
code.

Syntax

1. do{
2. //code to be executed
3. }while(condition);

Example

1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>

Output:

1
2
3
4
5
6
7
8
9
10

Break and Continue:


<?php

$i = 10;
while (--$i)
{
if ($i == 8)
{
continue;
}
if ($i == 5)
{
break;

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

}
echo $i . "\n";
}
?>

Sample Programs:
1) Sum of Digits

2) Even or odd number

3) Prime number

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.

Advantage of PHP Functions

Code Reusability: PHP functions are defined only once and can be invoked many times, like in
other programming languages.

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.

Easy to understand: PHP functions separate the programming logic. So it is easier to


understand the flow of the application because every logic is divided in the form of functions.

PHP User-defined Functions

We can declare and call user-defined functions easily. Let's see the syntax to declare user-
defined functions.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Syntax

1. function functionname(){
2. //code to be executed
3. }

PHP Functions Example


File: function1.php

1. <?php
2. function sayHello(){
3. echo "Hello PHP Function";
4. }
5. sayHello();//calling function
6. ?>

Output:

Hello PHP Function

PHP Function Arguments

We can pass the information in PHP function through arguments which is separated by comma.

PHP supports Call by Value (default), Call by Reference, Default argument values and
Variable-length argument list.

Let's see the example to pass single argument in PHP function.

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

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Let's see the example to pass two argument in PHP function.

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:

Hello Sonoo, you are 27 years old


Hello Vimal, you are 29 years old
Hello John, you are 23 years old

PHP Call By Reference

Value passed to the function doesn't modify the actual value by default (call by value). But we
can do so by passing value as a reference.

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.

Let's see a simple example of call by reference in PHP.

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:

Hello Call By Reference

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Passing an argument like so: myFunc(&$var); means that the variable is passed
by reference (and not by value). So any modifications made to the variable in
the function modify the variable where the call is made.

PHP Function: Default Argument Value

We can specify a default argument value in function. While calling PHP function if you don't
specify any argument, it will take the default argument. Let's see a simple example of using
default argument value in PHP function.

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

PHP Function: Returning Value

Let's see an example of PHP function that returns value.

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

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

PHP Parameterized Function


PHP Parameterized functions are the functions with parameters. You can pass any number of
parameters inside a function. These passed parameters act as variables inside your function.

They are specified inside the parentheses, after the function name.

The output depends upon the dynamic values passed as the parameters into the function.

PHP Parameterized Example 1

Addition and Subtraction

In this example, we have passed two parameters $x and $y inside two functions add() and sub().

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>
24. Factorial.php:

<?php

function fac($n)

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

$fact=1;

$i=1;

for($i=1;$i<=$n;$i++)

$fact=$fact*$i;

echo "result=$fact";

if(isset($_POST['factorial']))

fac($_POST['val1']);

} ?>

<form method="post">

enter a number:<input type="number" name="val1"><br>

<input type="submit" name="factorial" value="fact">

</form>

In the above code in process.php the $POST is a array which contains user information
submitted by the form. Form send user input values with its control names to process.php. where
val1 is key and whatever user type in input field will be the value in $POST array and we can
access that information like this $_POST['val1'].

Now come to isset. isset function check that the variable is set or not in other words the variable
has a value or not. In this case isset($POST['factorial']) checks that the $_POST['factorial'] is set
or not. it will be set if the user click on the login button. if the $_POST['fcatorial'] is set then the
code will echo computed factorial value else it will show that visit again message. For the
purpose we you isset is that suppose if user visit process.php without submitting the form then
the page will show an error that your $POST['val1'] is not set as we are trying to echo its value.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

But now we are checking the form submission and if the user visit the process.php page without
submitting the form. This time user will get the visit again message instead of error.

PHP Variable Length Argument Function


PHP supports variable length argument function. It means you can pass 0, 1 or n number of
arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name.

The 3 dot concept is implemented for variable length argument since PHP 5.6.

Let's see a simple example of PHP variable length argument function.

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

PHP Recursive Function


PHP also supports recursive function call like C/C++. In such case, we call current function
within function. It is also known as recursion.

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.

Example 1: Printing number

1. <?php
2. function display($number) {
3. if($number<=5){

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

4. echo "$number <br/>";


5. display($number+1);
6. }
7. }
8.
9. display(1);
10. ?>

Output:

1
2
3
4
5

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.

Advantage of PHP Array

Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Sorting: We can sort the elements of array.

PHP Array Types

There are 3 types of array in PHP.

1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array

PHP index is represented by number which starts from 0. We can store number, string and object
in the PHP array. All PHP array elements are assigned to an index number by default.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

There are two ways to define indexed 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:

Season are: summer, winter, spring and autumn

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:

Season are: summer, winter, spring and autumn

PHP Indexed Array Example


File: array1.php

1. <?php
2. $size=array("Big","Medium","Short");
3. echo "Size: $size[0], $size[1] and $size[2]";
4. ?>

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Output:

Size: Big, Medium and Short

File: array2.php

1. <?php
2. $size[0]="Big";
3. $size[1]="Medium";
4. $size[2]="Short";
5. echo "Size: $size[0], $size[1] and $size[2]";
6. ?>

Output:

Size: Big, Medium and Short

foreach

(PHP 4, PHP 5, PHP 7)

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays
and objects, and will issue an error when you try to use it on a variable with a different data type
or an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)


statement
foreach (array_expression as $key => $value)
statement

The first form loops over the array given by array_expression. On each iteration, the value of the
current element is assigned to $value and the internal array pointer is advanced by one (so on the
next iteration, you'll be looking at the next element).

The second form will additionally assign the current element's key to the $key variable on each
iteration.

Traversing PHP Indexed Array

We can easily traverse array in PHP using foreach loop. Let's see a simple example to traverse all
the elements of PHP array.

File: array3.php

1. <?php

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

2. $size=array("Big","Medium","Short");
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>

Output:

Size is: Big


Size is: Medium
Size is: Short

Count Length of PHP Indexed Array

PHP provides count() function which returns length of an array.

1. <?php
2. $size=array("Big","Medium","Short");
3. echo count($size);
4. ?>

Output:

PHP Associative Array

We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

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");

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";


4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000
File: arrayassociative2.php

1. <?php
2. $salary["Sonoo"]="350000";
3. $salary["John"]="450000";
4. $salary["Kartik"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "John salary: ".$salary["John"]."<br/>";
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
8. ?>

Output:

Sonoo salary: 350000


John salary: 450000
Kartik salary: 200000

Traversing PHP Associative Array

By the help of PHP for each loop, we can easily traverse the elements of PHP associative array.

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:

Key: Sonoo Value: 550000


Key: Vimal Value: 250000
Key: Ratan Value: 200000

Application: to Store Form Element Names and Values

<?php

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

function fac($n)

$fact=1;

$i=1;

for($i=1;$i<=$n;$i++)

$fact=$fact*$i;

echo "result=$fact";

if(isset($_POST['factorial']))

fac($_POST['val1']);

?>

<form method="post">

enter a number:<input type="number" name="val1"><br>

<input type="submit" name="factorial" value="fact">

</form>

PHP Multidimensional Array


PHP multidimensional array is also known as array of arrays. It allows you to store tabular data
in an array. PHP multidimensional array can be represented in the form of matrix which is
represented by row * column.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

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

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

PHP Array Functions


PHP provides various array functions to access and manipulate the elements of array. The
important PHP array functions are given below.

1) PHP array() function

PHP array() function creates and returns an array. It allows you to create indexed, associative
and multidimensional arrays.

Syntax

1. array array ([ mixed $... ] )

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:

Season are: summer, winter, spring and autumn

2) PHP array_change_key_case() function

PHP array_change_key_case() function changes the case of all key of an array.

Note: It changes case of key only.

Syntax

1. array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )

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 )

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

print_r() displays information about a variable in a way that's readable by humans.

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 )

3) PHP array_chunk() function

PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can
divide array into many parts.

Syntax

1. array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )

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 )
)

4) PHP count() function

PHP count() function counts all elements in an array.

Syntax

1. int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

Example

1. <?php

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>

Output:

5) PHP sort() function

PHP sort() function sorts all the elements in an array.

Syntax

1. bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

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

6) PHP array_reverse() function

PHP array_reverse() function returns an array containing elements in reversed order.

Syntax

1. array array_reverse ( array $array [, bool $preserve_keys = false ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>

Output:

autumn
spring
winter
summer

7) PHP array_search() function

PHP array_search() function searches the specified value in an array. It returns key if search is
successful.

Syntax

1. mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>

Output:

8) PHP array_intersect() function

PHP array_intersect() function returns the intersection of two array. In other words, it returns the
matching elements of two array.

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");

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>

Output:

sonoo
smith

PHP 5 Sorting Arrays


The elements in an array can be sorted in alphabetical or numerical order, descending or
ascending.

PHP - Sort Functions For Arrays

In this chapter, we will go through the following PHP array sort functions:

 sort() - sort arrays in ascending order


 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order - sort()

The following example sorts the elements of the $cars array in ascending alphabetical order:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
?>

Output:
BMW
Toyota
Volvo

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Sort Array in Descending Order - rsort()

The following example sorts the elements of the $cars array in descending alphabetical order:

Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
rsort($cars);
?>

Output:

Volvo
Toyota
BMW

Sort Array (Ascending Order), According to Value - asort()

The following example sorts an associative array in ascending order, according to the value:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age);
?>

Output:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43

Sort Array (Ascending Order), According to Key - ksort()

The following example sorts an associative array in ascending order, according to the key:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
ksort($age);
?>

Output:

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35

Sort Array (Descending Order), According to Value - arsort()

The following example sorts an associative array in descending order, according to the value:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
arsort($age);
?>

Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35

Sort Array (Descending Order), According to Key - krsort()

The following example sorts an associative array in descending order, according to the key:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
krsort($age);
?>

Output:

Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37

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.

 single quoted
 double quoted

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Single Quoted PHP String

We can create a string in PHP by enclosing text in a single quote. It is the easiest way to specify
string in PHP.

1. <?php
2. $str='Hello text within single quote';
3. echo $str;
4. ?>

Output:

Hello text within single quote

Double Quoted PHP String

In PHP, we can specify string through enclosing text within double quote also. But escape
sequences and variables will be interpreted using double quote PHP strings.

1. <?php
2. $str="Hello text within double quote";
3. echo $str;
4. ?>

Output:

Hello text within double quote

PHP String Functions


PHP provides various string functions to access and manipulate strings. A list of important PHP
string functions are given below.

1) PHP strtolower() function

The strtolower() function returns string in lowercase letter.

Syntax

1. string strtolower ( string $string )

Example

1. <?php
2. $str="My name is KHAN";

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

3. $str=strtolower($str);
4. echo $str;
5. ?>

Output:

my name is khan

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

2) PHP strtoupper() function

The strtoupper() function returns string in uppercase letter.

Syntax

1. string strtoupper ( string $string )

Example

1. <?php
2. $str="My name is KHAN";
3. $str=strtoupper($str);
4. echo $str;
5. ?>

Output:

MY NAME IS KHAN

3) PHP ucfirst() function

The ucfirst() function returns string converting first character into uppercase. It doesn't change
the case of other characters.

Syntax

1. string ucfirst ( string $str )

Example

1. <?php
2. $str="my name is KHAN";
3. $str=ucfirst($str);
4. echo $str;
5. ?>

Output:

My name is KHAN

4) PHP lcfirst() function

The lcfirst() function returns string converting first character into lowercase. It doesn't change the

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

case of other characters.

Syntax

1. string lcfirst ( string $str )

Example

1. <?php
2. $str="MY name IS KHAN";
3. $str=lcfirst($str);
4. echo $str;
5. ?>

Output:

mY name IS KHAN

5) PHP ucwords() function

The ucwords() function returns string converting first character of each word into uppercase.

Syntax

1. string ucwords ( string $str )

Example

1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=ucwords($str);
4. echo $str;
5. ?>

Output:

My Name Is Sonoo Jaiswal

6) PHP strrev() function

The strrev() function returns reversed string.

Syntax

1. string strrev ( string $string )

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Example

1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strrev($str);
4. echo $str;
5. ?>

Output:

lawsiaj oonoS si eman ym

7) PHP strlen() function

The strlen() function returns length of the string.

Syntax

1. int strlen ( string $string )

Example

1. <?php
2. $str="my name is Sonoo jaiswal";
3. $str=strlen($str);
4. echo $str;
5. ?>

Output:

24

in_array()

Definition and Usage

The in_array() function searches an array for a specific value.

Note: If the search parameter is a string and the type parameter is set to TRUE, the search is
case-sensitive.

Syntax
in_array(search,array,type)

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Parameter Description

Search Required. Specifies the what to search for

Array Required. Specifies the array to search

Optional. If this parameter is set to TRUE, the in_array() function searches for the
Type
search-string and specific type in the array.

<?php
$number_list = array('16.10', '22.0', '33.45', '45.45');
if (in_array(22.0, $number_list))
{
echo "'22.0' found in the array";
}
?>
Copy

Output:

'22.0' found in the array

PHP str_ireplace() Function


The str_ireplace() function replaces some characters with some other
characters in a string.

Syntax
str_ireplace(find,replace,string,count)

Parameter Description

find Required. Specifies the value to find

replace Required. Specifies the value to replace the value in find

string Required. Specifies the string to be searched

count Optional. A variable that counts the number of replacements

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

In this example we will demonstrate str_ireplace() with an array and a count variable:

<?php
$arr = array("blue","red","green","yellow");
print_r(str_ireplace("RED","pink",$arr,$i));
echo "Replacements: $i";
?>

The output of the code above will be:

Array
(
[0] => blue
[1] => pink
[2] => green
[3] => yellow
)
Replacements: 1

Definition and Usage

The str_pad() function pads a string to a new length.

Syntax
str_pad(string,length,pad_string,pad_type)

Parameter Description

string Required. Specifies the string to pad

length Required. Specifies the new string length. If this value is less than the original
length of the string, nothing will be done

pad_string Optional. Specifies the string to use for padding. Default is whitespace

pad_type Optional. Specifies what side to pad the string.

Possible values:

 STR_PAD_BOTH - Pad to both sides of the string. If not an even number,


the right side gets the extra padding
 STR_PAD_LEFT - Pad to the left side of the string

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

 STR_PAD_RIGHT - Pad to the right side of the string. This is default

Example 1
<?php
$str = "Hello World";
echo str_pad($str,20,".");
?>

The output of the code above will be:

Hello World.........

PHP str_repeat() Function


Definition and Usage

The str_repeat() function repeats a string a specified number of times.

Syntax
str_repeat(string,repeat)

Parameter Description

string Required. Specifies the string to repeat

repeat Required. Specifies the number of times the string will be repeated. Must be
greater or equal to 0

Example
<?php
echo str_repeat(".",13);
?>

The output of the code above will be:

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

.............

PHP str_replace() Function


Definition and Usage

The str_replace() function replaces some characters with some other characters in a string.

Syntax
str_replace(find,replace,string,count)

Parameter Description

find Required. Specifies the value to find

replace Required. Specifies the value to replace the value in find

string Required. Specifies the string to be searched

count Optional. A variable that counts the number of replacements

In this example we will demonstrate str_replace() with an array and a count variable:

<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>

The output of the code above will be:

Array
(
[0] => blue
[1] => pink
[2] => green
[3] => yellow
)
Replacements: 1

PHP str_rot13() Function

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Definition and Usage

The str_rot13() function performs the ROT13 encoding on a string.

The ROT13 encoding shifts every letter 13 places in the alphabet. Numeric and non-alphabetical
characters remains untouched.

Syntax
str_rot13(string)

Parameter Description

string Required. Specifies the string to encode

Example

In this example we will encode and decode a string using the str_rot13() function:

<?php
echo str_rot13("Hello World");
echo "<br />";
echo str_rot13("Uryyb Jbeyq");
?>

The output of the code above will be:

Uryyb Jbeyq
Hello World

PHP str_shuffle() Function


Definition and Usage

The str_shuffle() function randomly shuffles all the characters of a string.

Syntax
str_shuffle(string)

Example
<?php
echo str_shuffle("Hello World");
?>

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

The output of the code above could be:

H leooWlrld

PHP str_split() Function

Definition and Usage

The str_split() function splits a string into an array.

Syntax
str_split(string,length)

Parameter Description

string Required. Specifies the string to split

length Optional. Specifies the length of each array element. Default is 1

Example 1
<?php
print_r(str_split("Hello"));
?>

The output of the code above will be:

Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
)

Example 2
<?php
print_r(str_split("Hello",3));
?>

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

The output of the code above will be:

Array
(
[0] => Hel
[1] => lo
)

PHP str_word_count() Function


Definition and Usage

The str_word_count() function counts the number of words in a string.

Syntax
str_word_count(string,return,char)

Example 1
<?php
echo str_word_count("Hello world!");
?>

The output of the code above will be:

PHP strcasecmp() Function


Definition and Usage

The strcasecmp() function compares two strings.

This function returns:

 0 - if the two strings are equal


 <0 - if string1 is less than string2
 >0 - if string1 is greater than string2

Syntax
strcasecmp(string1,string2)

Tips and Notes

Tip: The strcasecmp() function is binary safe and case-insensitive.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Example
<?php
echo strcasecmp("Hello world!","HELLO WORLD!");
?>

The output of the code above will be:

Classwork programs:
1)Write a PHP program to count number of
vowels in a string.
PHP File Handling
PHP File System allows us to create file, read file line by line, read file character by character,
write file, append file, delete file and close file.

PHP Open File - fopen()

The PHP fopen() function is used to open a file.

Syntax

1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $c
ontext ]] )

Example

1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>

PHP Close File - fclose()

The PHP fclose() function is used to close an open file pointer.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Syntax

1. fclose ( resource $handle )

Example

1. <?php
2. fclose($handle);
3. ?>

PHP Read File - fread()

The PHP fread() function is used to read the content of the file. It accepts two arguments:
resource and file size.

Syntax

1. string fread ( resource $handle , int $length )

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

hello php file

PHP Write File - fwrite()

The PHP fwrite() function is used to write content of the string into file.

Syntax

1. int fwrite ( resource $handle , string $string [, int $length ] )

Example

1. <?php
2. $fp = fopen('data.txt', 'w');//open file in write mode

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

3. fwrite($fp, 'hello ');


4. fwrite($fp, 'php file');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>

Output

File written successfully

PHP Delete File - unlink()

The PHP unlink() function is used to delete file.

Syntax

1. bool unlink ( string $filename [, resource $context ] )

Example

1. <?php
2. unlink('data.txt');
3.
4. echo "File deleted successfully";
5. ?>

PHP Open File


PHP fopen() function is used to open file or URL and returns resource. The fopen() function
accepts two arguments: $filename and $mode. The $filename represents the file to be opended
and $mode represents the file mode for example read-only, read-write, write-only etc.

Syntax

1. resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $c
ontext ]] )

PHP Open File Mode


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.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Opens file in write-only mode. It places the file pointer to the beginning of the file and truncates
w
the file to zero length. If file is not found, it creates a new file.

Opens file in read-write mode. It places the file pointer to the beginning of the file and truncates
w+
the file to zero length. If file is not found, it creates a new file.

Opens file in write-only mode. It places the file pointer to the end of the file. If file is not found, it
a
creates a new file.

Opens file in read-write mode. It places the file pointer to the end of the file. If file is not found, it
a+
creates a new file.

Creates and opens file in write-only mode. It places the file pointer at the beginning of the file. If
x
file is found, fopen() function returns FALSE.

x+ It is same as x but it creates and opens file in read-write mode.

Opens file in write-only mode. If the file does not exist, it is created. If it exists, it is neither
c 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

c+ It is same as c but it opens file in read-write mode.

PHP Read File


PHP provides various functions to read data from file. There are different functions that allow
you to read all file data, read data line by line and read data character by character.

The available PHP file read functions are given below.

 fread()
 fgets()
 fgetc()

PHP Read File - fread()

The PHP fread() function is used to read data of the file. It requires two arguments: file resource
and file size.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Syntax

1. string fread (resource $handle , int $length )

$handle represents file pointer that is created by fopen() function.

$length represents length of byte to be read.

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

this is first line


this is another line
this is third line

PHP Read File - fgets()

The PHP fgets() function is used to read single line from the file.

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

this is first line

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

PHP Read File - fgetc()

The PHP fgetc() function is used to read single character from the file. To get all data using
fgetc() function, use !feof() function inside the while loop.

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

this is first line this is another line this is third line

PHP Append to File


You can append data into file by using a or a+ mode in fopen() function. Let's see a simple
example that appends data into data.txt file.

Let's see the data of file first.

data.txt

welcome to php file write

PHP Append to File - fwrite()

The PHP fwrite() function is used to write and append data into file.

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);

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

6.
7. echo "File appended successfully";
8. ?>

Output: data.txt

welcome to php file write this is additional text appending data

PHP Delete File


In PHP, we can delete any file using unlink() function. The unlink() function accepts one
argument only: file name. It is similar to UNIX C unlink() function.

PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is
deleted successfully otherwise FALSE.

Syntax

1. bool unlink ( string $filename [, resource $context ] )

$filename represents the name of the file to be deleted.

PHP Delete File Example

1. <?php
2. $status=unlink('data.txt');
3. if($status){
4. echo "File deleted successfully";
5. }else{
6. echo "Sorry!";
7. }
8. ?>

Output

File deleted successfully

PHP readfile() Function

The readfile() function reads a file and writes it to the output buffer.

<?php
echo readfile("webdictionary.txt");
?>

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

PHP random access to a file:

-rewind();
-fseek();
-ftell();

PHP rewind () Function


Definition and Usage

The rewind () function "rewinds" the position of the file pointer to the beginning of the file.

This function returns TRUE on success, or FALSE on failure.

Syntax
rewind(file)

Example #1 rewind() overwriting example

<?php
$handle = fopen('output.txt', 'w');

fwrite($handle, 'Really long sentence.');


rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);

echo fread($handle, filesize('output.txt'));

fclose($handle);
?>

The above example will output something similar to:

Foolly long sentence.

PHP fseek() Function


Definition and Usage

The fseek() function seeks in an open file.

This function moves the file pointer from its current position to a new position, forward or
backward, specified by the number of bytes.

This function returns 0 on success, or -1 on failure. Seeking past EOF will not generate an error.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Syntax
fseek(file,offset,whence) ;

First one is the FILE * it will seek

Second is the int Record size, the value, it is expected to hop in one jump. Notice, it can be a
negative value as well.

Third parameter is the offset value from where this hopping is to be done. There are three
possible values for it 0,1 and 2. 0 represents beginning of the file 1 represents current location
And, 2 represents the end of file.

The SEEK_END, SEEK_CUR or,the SEEK_SET are merely the Macro Expansions with values
of 2,1 and 0 respectively. So when a user uses these macro Expansions rather that using the real
values underneath, the pre-processors replaces every such usage with its respective value and
compilation goes on as usual.

Example
<?php
$file = fopen("test.txt","r");
// read first line
fgets($file);
// move back to beginning of file
fseek($file,0);
?>

PHP ftell() Function


Definition and Usage

The ftell() function returns the current position in an open file.

Syntax
ftell(file)

Example
<?php
$file = fopen("test.txt","r");

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

// print current position


echo ftell($file);

// change current position


fseek($file,"15");

// print current position again


echo "<br />" . ftell($file);

fclose($file);
?>

The output of the code above will be:

0
15

Classwork programs:
1)Write a PHP program to count number of
lines in a file.
2)Write a PHP program to copy from 20th
line of a file to another file.
PHP and MYSQL:

MySQL Database

MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is
developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is
becoming so popular because of many good reasons −

 MySQL is released under an open-source license. So you have nothing to pay to use it.
 MySQL is a very powerful program in its own right. It handles a large subset of the
functionality of the most expensive and powerful database packages.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

 MySQL uses a standard form of the well-known SQL data language.


 MySQL works on many operating systems and with many languages including PHP,
PERL, C, C++, JAVA, etc.
 MySQL works very quickly and works well even with large data sets.
 MySQL is very friendly to PHP, the most appreciated language for web development.
 MySQL supports large databases, up to 50 million rows or more in a table. The default
file size limit for a table is 4GB, but you can increase this (if your operating system can
handle it) to a theoretical limit of 8 million terabytes (TB).
 MySQL is customizable. The open-source GPL license allows programmers to modify
the MySQL software to fit their own specific environments.

PHP MySQL Introduction

The data in MySQL is stored in tables. A table is a collection of related data, and it consists of
columns and rows.

Databases are useful when storing information categorically. A company may have a database
with the following tables:

 Employees
 Products
 Customers
 Orders

PHP + MySQL

 PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix
platform)

Queries

A query is a question or a request.

We can query a database for specific information and have a recordset returned.

Look at the following query (using standard SQL):

SELECT LastName FROM Employees

The query above selects all the data in the "LastName" column from the "Employees" table.

PHP How Connect to the MySQL

pen a Connection to the MySQL Server :

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Before we can access data in a database, we must open a connection to the MySQL server.

In PHP, this is done with the mysqli_connect() function.

Syntax

mysqli_connect(host,username,password,dbname);

Note: Mysqli--here “i” stands for improved version of Mysql.Mysqli supports Object-oriented
interface , Support for Prepared Statements etc.

Parameter Description
Optional. Either a host name or an
host
IP address
username Optional. The MySQL user name
Optional. The password to log in
password
with
Optional. The default database to
dbname
be used when performing queries

Note: There are more available parameters, but the ones listed above are the most important.

In the following example we store the connection in a variable ($con) for later use in the script:

<?php
// Create connection
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Host-If this parameter takes localhost" refers to the local computer that a program is running on.
For example, if you are running a Web browser on your computer, your computer is considered
to be the "localhost."

How Close a Connection

The connection will be closed automatically when the script ends. To close the connection
before, use the mysqli_close() function:

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysqli_close($con);
?>

PHP mysqli_query() Function

Definition and Usage

The mysqli_query() function performs a query against the database.

Syntax
mysqli_query(connection,query,resultmode);

Parameter Description

connection Required. Specifies the MySQL connection to use

Query Required. Specifies the query string

Optional. A constant. Either:mysqli::store_result() will fetch the whole


resultset from the MySQL server while mysqli::use_result() will fetch
the rows one by one.
resultmode
 MYSQLI_USE_RESULT (Use this if we have to retrieve large amount of data)
 MYSQLI_STORE_RESULT (This is default)

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Perform queries
mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");

mysqli_close($con);
?>

PHP mysqli_num_rows() Function


Definition and Usage

The mysqli_num_rows() function returns the number of rows in a result set.

Syntax
mysqli_num_rows(result);

Parameter Description

Required. Specifies a result set identifier returned by mysqli_query(),


Result
mysqli_store_result() or mysqli_use_result()

Technical Details
Return Value: Returns the number of rows in the result set

PHP mysqli_fetch_assoc() Function

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Definition and Usage

The mysqli_fetch_assoc() function fetches a result row as an associative array.

Note: Fieldnames returned from this function are case-sensitive.

Syntax
mysqli_fetch_assoc(result);

Parameter Description

Required. Specifies a result set identifier returned by mysqli_query(),


Result
mysqli_store_result() or mysqli_use_result()

Technical Details
Returns an associative array of strings representing the fetched row. NULL if there
Return Value:
are no more rows in result-set

PHP mysqli_multi_query() Function


?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql = "SELECT Lastname FROM Persons ORDER BY LastName;";


$sql .= "SELECT Country FROM Customers";

// Execute multi query


if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
echo $row[0]);
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}

mysqli_close($con);
?>

Definition and Usage

The mysqli_multi_query() function performs one or more queries against the database. The
queries are separated with a semicolon.

Syntax
mysqli_multi_query(connection,query);

Parameter Description

connection Required. Specifies the MySQL connection to use

query Required. Specifies one or more queries, seperated with semicolon

//Update:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

//delete
?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);
}

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

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.

Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying
return users.

A cookie is a small file with the maximum size of 4KB that the web server stores on the client
computer.

Once a cookie has been set, all page requests that follow return the cookie name and value. A
cookie can only be read from the domain that it has been issued from. For example, a cookie set
using the domain www.guru99.com can not be read from the domain career.guru99.com.

Most of the websites on the internet display elements from other domains such as advertising.
The domains serving these elements can also set their own cookies. These are known as third
party cookies.

A cookie created by a user can only be visible to them. Other users cannot see its value.

Most web browsers have options for disabling cookies, third party cookies or both.

If this is the case then PHP responds by passing the cookie token in the URL. Why
and when to use Cookies?

 Http is a stateless protocol; cookies allow us to track the state of the application using
small files stored on the user’s computer.

The path were the cookies are stored depends on the browser.

Internet Explorer usually stores them in Temporal Internet Files folder.

 Personalizing the user experience – this is achieved by allowing users to select their
preferences.

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

The page requested that follow are personalized based on the set preferences in the
cookies.

 Tracking the pages visited by a user

A cookie is created with the setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.

<?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>
The setcookie() function must appear BEFORE the <html> tag. The value of the cookie is automatically
URLencoded when sending the cookie, and automatically decoded when received. setcookie() must be
called before any output is sent to the browser.

To delete a cookie, use the setcookie() function with an expiration date in the past:

<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>

To check whether the cookies are enabled

<?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>

What is a Session?
 A session is a global variable stored on the server.
 Each session is assigned a unique id which is used to retrieve stored values.
 Whenever a session is created, a cookie containing the unique session id is stored on the
user’s computer and returned with every request to the server. If the client browser does
not support cookies, the unique php session id is displayed in the URL
 Sessions have the capacity to store relatively large data compared to cookies.
 The session values are automatically deleted when the browser is closed. If you want to
store the values permanently, then you should store them in the database.
 Just like the $_COOKIE array variable, session variables are stored in the $_SESSION
array variable. Just like cookies, the session must be started before any HTML tags.
 You want to store important information such as the user id more securely on the server
where malicious users cannot temper with them.
 You want to pass values from one page to another.
 You want the alternative to cookies on browsers that do not support cookies.
 You want to store global variables in an efficient and more secure way compared to
passing them in the URL

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

 You are developing an application such as a shopping cart that has to temporary store
information with a capacity larger than 4KB.

Creating a Session
In order to create a session, you must first call the PHP session_start function and then store
your values in the $_SESSION array variable.

Let’s suppose we want to know the number of times that a page has been loaded, we can use a
session to do that.

The code below shows how to create and retrieve values from sessions

<?php

session_start(); //start the PHP_session function

if(isset($_SESSION['page_count']))
{
$_SESSION['page_count'] += 1;
}
else
{
$_SESSION['page_count'] = 1;
}
echo 'You are visitor number ' . $_SESSION['page_count'];

?>

Output:

You are visitor number 1

Destroying Session Variables


The session_destroy() function is used to destroy the whole Php session variables.If you want to
destroy only a session single item, you use the unset() function. The code below illustrates how
to use both methods.

<?php

session_destroy(); //destroy entire session

?>
<?php

unset($_SESSION['product']); //destroy product session item

?>

Downloaded by Deshma ([email protected])


lOMoARcPSD|32195777

Session_destroy removes all the session data including cookies associated with the session.

Unset only frees the individual session variables.

Other data remains intact.

Downloaded by Deshma ([email protected])

You might also like