You are on page 1of 210

2

PHP

Free Tamil Ebooks at : www.TechFahim.com

www.kaniyam.com
3

PHP ,
. ,
.

, .

"" , 2012
. PHP
.

, editor@kaniyam.com
.

http://kaniyam.com/learn-php-in-tamil-ebook
. .

, .

.
tshrinivasan@gmail.com

editor@kaniyam.com

www.kaniyam.com
4

PHP
2016

2016 .

- . - linuxkathirvel.info@gmail.com

: . - tshrinivasan@gmail.com

: .

- - socrates1857@gmail.com

. ,

, , www.kaniyam.com
. .
.

http://static.kaniyam.com/ebooks/learn-php-in-tamil/learn-php-in-tamil.odt

www.kaniyam.com
5

This work is licensed under a Creative Commons Attribution-ShareAlike


4.0 Unported License.

www.kaniyam.com
6



.
,
.
.
.
.
.
.

PHP Developer
HTML, CSS, JavaScript, Bootstrap, jQuery
. PHP
. ,
.
, PHP
. " , PHP
" . 11- 7-
.
Python Developer
.

.
, . PHP
, ,
, .


.
.
. PHP

www.kaniyam.com

Free Tamil Ebooks at : www.TechFahim.com


7


(), ., .
, , ,
, , , , ,
, ,
.

28.12.2015

: http://gnutamil.blogspot.in

: linuxkathirvel.info@gmail.com

www.kaniyam.com
8

.......................................................................................................................................... 6
1 PHP ....................................................................................................................... 16
1.1 PHP ................................................................................................................. 16

1.2 PHP .............................................................................................................. 16

1.3 PHP 3 ................................................................................................................ 18

1.4 PHP 4 - ................................................................................................................. 18

1.5 PHP 5 Object Orientation , Error Handling and XML...................................................18

1.6 PHP ?........................................................................................ 19

2 PHP ................................................................................................................................ 20
2.1 PHP ?............................................................................................................ 20

2.2 PHP - ?........................................................20

2.3 PHP?............................................................................................................................... 21

2.4 PHP ?......................................................................................... 21

2.5 PHP ?....................................................................25

3 LAMP Server - 12.04 - ........................................................................26


3.1 :................................................................................................................................ 26

3.2 Apache Server - :..............................................................28

3.3 PHP - :...........................................................................29

4 PHP Script ............................................................................................................. 31


4.1 PHP Script ....................................................................................................... 31

4.2 PHP :.................................................................................31

4.3 PHP (Code Delimiters):.......................................................................31

4.4 PHP ?..................................................................32

4.5 PHP :............................................................................................ 35

www.kaniyam.com
9

5 Comments - .......................................................................................................... 38
5.1 :........................................................................................................... 39

5.2 :.................................................................................................................. 40

6 (Variables).................................................................................................................... 41
6.1 :............................................................................................... 41

6.2 :.....................................................................................42

6.3 :.....................................................................................43

6.4 PHP :.........................................................................44

6.5 (Check Whether a variable is set):


............................................................................................................................................................ 45
7 PHP :..................................................................................................................... 47
7.1 (Integer Variable Type):...............................................................47

7.2 (Float Variable Type):..............................................................47

7.3 (Boolean Variable Type):................................................................48

7.4 (String Variable Type):..............................................................................49

8 (Constants)..................................................................................................................... 51
8.1 (Defining a Constant):............................................................51

8.2 (Predefined Constants):.......................................53

9 Operators ()............................................................................................................. 57
9.1 (Assignment Operators):.....................58

9.2 (Arithmetic Operators):...............................................................61

9.3 (Comparison Operators):.................................................................62

9.4 (Logical Operators):.....................................................................64

9.5 (Increment and Decrement


Operators):........................................................................................................................................ 64
9.6 (String Concatenation Operator):......................66

9.7

www.kaniyam.com
10

(Execution Operator Executing Server Side Commands)......................................................66


10 Flow Control and Looping....................................................................................................... 68
10.1 Conditional Statements..................................................................................................... 68

10.2 ( Looping Statements).......................................................................72

10.3 switch (switch statements)....................................................................................77

10.4 (Breaking a Loop):..................................................................................81

11 Functions.................................................................................................................................... 84
11.1 Function () ?...........................................................................84

11.2 (function) ?........................................................................84

11.3 (Returning a Value from a function)....86

11.4 (passing parameters to a function).....86

11.5 (calling functions)....................................................................87

11.6 Passing Parameters by Reference....................................................................................89

11.7 Functions and Variable Scope........................................................................................... 91

12 Arrays.......................................................................................................................................... 93
12.1 Numerical Array................................................................................................................... 93

12.2 Associative Array................................................................................................................. 94

12.3 Array (Creating a Array)............................................................................94

12.4 Empty Array (empty array creation)...........................................................94

12.5 Array - ................................................................................95

12.6 Associative Array (Creating an Associative Array)......................96

12.7 Associative Array (Accessing Elements of an


Associative Array)............................................................................................................................ 96
12.8 Array (Using Array Pointers)..............................................97

12.9 Array , (Changing, Adding and


Removing Array Elements)............................................................................................................ 98

www.kaniyam.com
11

12.10 Looping array (Looping through array


Elements)........................................................................................................................................ 103
12.11 Replacing Sections of an Array....................................................................................105

12.12 Array - ......................................................................................105

12.13 Associative Array - ................................................................109

12.14 Array array

(functions).............................................................................................................. 110

13 Working with Strings and Text in PHP................................................................................ 111


13.1 (Changing the Case of a PHP String)................................111

13.2 ASCII ASCII ......................113

13.3 (Printing Formatted Strings)....................................117

13.4 (Finding the Length of a String).........................118

13.5 Array (Converting a String into a Array)............................119

13.6 whitespace (Removing


Leading and Trailing Whitespace from a String)......................................................................120
13.7 (Comparing Strings)..................................................................121

13.8 (Accessing and Modifying Characters in


String).............................................................................................................................................. 122
13.9 , (Searching for Characters
and Substrings in a String)........................................................................................................... 123
13.10 Extracting and Replacing Substrings..........................................................................124

13.11 Replacing All Instances of a Word in a String............................................................126

14 , / (File systems and File I/O)


............................................................................................................................................................... 128
14.1 (Opening and Creating Files)..................128

14.2 (Closing Files)..............................................................................129

14.3 (Writing to a File)..........................................................................130

www.kaniyam.com
12

14.4 (Reading From a File)..................................132

14.5 (Checking Whether a File Exists)..................132

14.6 , (Moving, Copying and


Deleting Files)................................................................................................................................ 133
14.7 (Accessing File Attributes)..............................134

14.8 (Output Buffering)..................................................................136

15 (Working with Directories)...........................................139


15.1 (Creating Directories).....................................139

15.2 (Deleting Directory)......................................................................141

15.3 Finding and Changing the Current Working Directory..............................................142

15.4 (Listing Files in a Directory)


.......................................................................................................................................................... 143
16 HTML Forms ...................................................................................................... 144
16.1 HTML (Creating HTML Forms)..........................................144

16.2 HTML Text Object ( )...............................................................................145

16.3 HTML TextArea Object ( )............................................................147

16.4 The HTML Button Object ( ).........................................................148

16.5 HTML check Boxes............................................................................................................ 150

16.6 HTML Radio Button.......................................................................................................... 151

16.7 HTML Drop-down / Select Object..................................................................................152

16.8 HTML Password Object.................................................................................................... 155

17 PHP and HTML Forms............................................................................................................ 156


17.1 (Creating the Form)...................................................................156

17.2 PHP Process (Processing Form Data


Using PHP)...................................................................................................................................... 158
17.3 Processing Multiple Selections with PHP( ).......160

18 PHP and Cookies Creating, Reading and Writing ( ,

www.kaniyam.com
13

)................................................................................................................................. 163
18.1 ................................................................................................................................. 163

18.2 The Difference Between Cookies and Sessions (Cookies and Sessions

)......................................................................................................... 164

18.3 (The Structure of Cookie)..................................................164

18.4 (Cookie Expiration Setting).............165

18.5 (Cookie path Setting).........................................................165

18.6 domain (Cookie domain Setting)..........................................................165

18.7 (Cookie Security Setting)............................................166

18.8 (Creating a Cookie in PHP).............................................................166

18.9 (Reading a Cookie in PHP).........................................................167

18.10 (Deleting a Cookie).........................................................................168

19 (Understanding PHP Sessions)................................................................................170


19.1 Session ?.................................................................................................. 170

19.2 PHP Session (Creation a PHP Session).................................................170

19.3 Session (Creating and Reading Session


Variables)........................................................................................................................................ 171
19.4 Session (Writing Session Data to a File)..............173

19.5 session (Reading Saved Session) 175

20 (Object Oriented Programming).......................................176


20.1 Object ?................................................................................................... 176

20.2 Class ?...................................................................................................... 176

20.3 Class Object ?.........................................................176

20.4 sub-classing ?......................................................................................... 177

20.5 PHP class ...................................................................................177

20.6 PHP class (class constructors and destructors). 178

www.kaniyam.com
14

20.7 PHP class (members) ..............................................180

20.8 Methods (Defining and Calling Methods)


.......................................................................................................................................................... 182
20.9 Subclassing in PHP............................................................................................................ 184

20.10 ChildClass ParentClass method .......185

20.11 PHP Object Serialization............................................................................................... 186

20.12 PHP Object ...............................................................187

21 PHP (Using PHP with MySQL)...............................................................190


21.1 PHP MySQL (Connect with PHP to a MySQL Server).........190

21.2 MySQL PHP (Record)


(Selecting Records from a MySQL Database Using PHP):......................................................192
21.3 Adding Records to MySQL Database using PHP
.......................................................................................................................................................... 193
21.4 Using PHP to get Information about a MySQL Database..........................................194

22 PHP SQLite (PHP and SQLite)................................................................................. 197


22.1 PHP SQLite Database (Creating an SQLite Database with
PHP)................................................................................................................................................. 197
22.2 PDO (PHP Data Objects) SQLite DB .................................197

22.3 PHP SQLite Table (Using PHP to Create Table to an


SQLite Database)........................................................................................................................... 198
22.4 Using PHP to Add Records to an SQLite Database.....................................................199

22.5 PHP Records (Using PHP to Select Records from an


SQLite Database)........................................................................................................................... 200
23 .................................................................................................................................... 203
24 .......................................................................................................................... 205
25 .......................................................................................................................... 207
.................................................................................................................................. 207

................................................................................................................................... 207

www.kaniyam.com
15

........................................................................................................................ 208

.................................................................................................................. 209

26 ............................................................................................................................... 210

www.kaniyam.com
16

1 PHP

1.1 PHP
.
, .
,
,
.

()

.

1.2 PHP
PHP 1995 Ramus Lerdof .
Rasmus Yahoo .
HTML
.
,
.

www.kaniyam.com
17

Perl
. Personal
Home Page / Form Interpreter. Rasmus Lerdof
,
.

Personal Home Page / Form Interpreter PHP/FI


. PHP: Hypertext Preprocessor
. GNUs Not Unix GNU
, PHP: Hypertext Preprocessor PHP
.

PHP/FI (Version 1.0) Rasmus


.
. PHP/FI 2.0 .

PHP 3 1997
PHP
.

www.kaniyam.com
18

1.3 PHP 3
1997 .
Apache Web Server
. PHP Andy Gutmans
Zeev Suraski PHP 3 .
Apache Web Server PHP PHP
.

PHP + Apache Web Server .


10% PHP
.

1.4 PHP 4 -
Andi Gutmans and Zeev Suraski PHP 3 .
PHP3- PHP4 .
PHP4 .
Zend Engine .

:
( Microsofts Internet Information Server IIS )
.

, mission critical

1.5 PHP 5 Object Orientation , Error Handling and XML


OOP . Java, Python
try/catch error and exception handling
. XML SQLite

.

www.kaniyam.com
19

1.6 PHP ?
PHP Server Side Scripting (Language)
. PHP
, .
Apache+PHP .
PHP .
2013 , 240 (1 =10
, 240 =240000000) PHP
. 2.1 PHP .

Perl, Python , PHP


. Syntax,
PHP ,
Web Developement PHP
.

www.kaniyam.com
20

2 PHP
2.1 PHP ?
PHP Server Side Scripting language.
.
. PHP
.
(Client Side) Process ,
(Server Side) Process
. Server
Server Side Scripting Language . PHP Server Side
Process . PHP server side scripting language .

Ruby, Python, Perl Server Side Scripting Language


. PHP , PHP
.
Extension .

Database , Database
, Dynamic ,
Content PHP
.
PHP .

2.2 PHP - ?
Dynamic Page Content .
Web Server , , , ,
.
(Form Data) .
Cookies .
(Database) , ,
.
(Users) .

www.kaniyam.com
21

Encrypt .
HTML , Images, PDF Files, Flash Movies XML, XHTML
.

2.3 PHP?
PHP . (. Windows, Linux,
Unix, Mac OS X, etc)
Server (Apache, IIS, etc )
.
MySQL, SQLite, Postgres, Oracle, MS SQL
PHP .
PHP . PHP
(www.php.net)
.
, Server Side
PHP .

2.4 PHP ?
,
,
.


.
.

.
.
.

HTML, CSS, JavaScript, jQuery


.
. PHP

www.kaniyam.com

Free Tamil Ebooks at : www.TechFahim.com


22

PHP , PHP
PHP pre-processing module
.
PHP pre-processing module Web Server .
Web Server PHP PHP pre-
processing module Substitutes .
.

php
process . php pre-processing module
process
.

. <?php ?>
. php
.

<?php php , ?> php


.

<!test1.php >
<!DOCTYPE html>
<html>
<head>
<title>PHP Learning</title>
</head>
<body>
<h1>Hello PHP!</h1>
<?php
echo Hello World!;
echo <br />;
echo Hello PHP!;
?>
</body>
</html>

www.kaniyam.com
23

test1.php

<?php HTML .
php . web server
web browser .
.

Test1.php

page source

<!DOCTYPE html>
<html>
<head>
<title>PHP Learning</title>
</head>
<body>
<h1>Hello PHP!</h1>
Hello World!<br />Hello PHP! </body>
</html>

www.kaniyam.com
24

php .

HTML php
? .
.

, ,
.
HTML
. view page source
.
. 2-
2-
.

HTML static
content .


php
. php

, . PHP
. ,
PHP .

www.kaniyam.com
25

PHP ? ?

2.5 PHP ?
HTML Static Page
.
. JavaScript - Dynamic Page -
. Dynamic Page
JavaScript Client Side
.
JavaScript - Web Server . Web
Browser .
JavaScript Database
Web Page .
Database PHP .
PHP Server Side Scripting Language ,
. PHP .
MySQL PHP . MySQL
PHP - .

www.kaniyam.com
26

3 LAMP Server - 12.04 -

Linux Apache MySQL PHP - LAMP . LAMP


/ .

Linux (
), Apache (Web Server), MySQL RDBMS
, PHP (Dynamic
Web Page)Scripting Language.

LAMP - Apache, MySQL, PHP .


.
,

!

LAMP Server 12.04 LTS


- . .


.
LINUX For You Magazine -
.
,
.
. GPRS
. .

3.1 :
, .

www.kaniyam.com
27

sudo apt-get update


sudo apt-get install lamp-server^

: ^ Keyboard - Number key - 6 -


.
. MySQL Database root
(password) , .

www.kaniyam.com
28

3.2 Apache Server - :

sudo service apache2 restart .


, Apache Server .

www.kaniyam.com
29

,
http://localhost/ ,
.

3.3 PHP - :

/var www
.

cd /var
sudo mkdir www

www .

, ,

echo "<?php phpinfo(); ?>" | sudo tee /var/www/testing.php

www.kaniyam.com
30

sudo service apache2 restart

Apache Server -
.

,
,

http://localhost/testing.php

PHP -
.

LAMP Server - .

www.kaniyam.com
31

4 PHP Script
4.1 PHP Script
PHP .
PHP Script . PHP
PHP .

4.2 PHP :
1. Web Server
2. PHP
3. Browser
4. Text Editor
5. Database

Web Server, PHP, Database


(gnutamil.blogspot.in/2012/12/lamp-server-1204.html)
. PHP
php.net/manual/en/install.php - .

Browser Editor
. Mozilla Firefox, Google Chrome
.

4.3 PHP (Code Delimiters):


php
<?php Opening Tag , ?> Closing Tag
. Tag php
.

www.kaniyam.com
32

1:
<?
//php codings
?>

2:
<?php
//php codings
php?>

3:
<script language=php>
//php codings
</script>

4:
<?php
//php codings
?>

<?php //php codings ?> .

4.4 PHP ?
PHP
.

Text Editor

www.kaniyam.com
33

<?php
echo phpinfo();
?>

phptest.php /var/www/
. localhost/phptest.php
PHP
.


Text Editor .
/var/www/ .

PHP . HTML
.

DocumentRoot .

/var/www , . /var/www/html ,

Apache configuration file

www.kaniyam.com
34

www.kaniyam.com
35

4.5 PHP :
1. HTML File - PHP
2. PHP File HTML

HTML File PHP (PHP into an HTML File) :


PHP PHP
. PHP
. HTML Tag
. HTML File PHP
.

Editor HTML File

<!DOCTYPE html>
<html>
<head>
<?php
echo <title>PHP in Tamil</title>;
?>
</head>
<body>
<?php
echo <p>This content was generated by PHP</p>;
?>
</body>
</html>

firstscript.php .
.

PHP .php file extentsion . ;


(semicolon) . semicolon PHP
(line separator) .

www.kaniyam.com
36

PHP HTML (Embedding HTML into a PHP Script):


HTML PHP .
. PHP HTML -
.

<?php
echo <html>\n;
echo <head>\n;
echo <title>My Second PHP Example</title>\n;
echo </head>\n;
echo <body>\n;
echo <p>Free Open Source Software.</p>\n;
echo </body>\n;
echo </html>\n;
?>

htmlintophp.php .
.

View Page Source


.

www.kaniyam.com
37

<html>
<head>
<title>My Second PHP Example</title>
</head>
<body>
<p>Free Open Source Software.</p>
</body>
</html>

. PHP pre-processor
. ? !

www.kaniyam.com
38

5 Comments -

(comments) .
- . comment
/
.
.

PHP - PHP pre-processor


.
.

1.
.
2. ,
.
.
3.
.
4.
,

www.kaniyam.com
39


. .
5. .
.

PHP .

1. Single line ( )
2. Multi line ( )

PHP C, C++ and Java


. PHP
.

5.1 :
.

//This is single line comment.

<?php
//php coding start here
echo Hello PHP!; //echo is used to print the statement
//php coding end here
?>


.
.

www.kaniyam.com
40

<?php
//echo Hello PHP!;
echo Hello Linux!;
?>

5.2 :
/* */ . /*
, */ .

<?php
/* This is a
multiline
comments
*/
echo Hello PHP;
?>


.
. .

www.kaniyam.com
41

6 (Variables)

PHP (Variables)

variable .
.
. .
.

6.1 :

.

PHP $ .

$ PHP pre-processor
.

_ (underscore)
.

, _
(underscore) .

PHP case sensitive scripting language

www.kaniyam.com

Free Tamil Ebooks at : www.TechFahim.com


42

$myName $myname . .

$_myName
$myName
$__myName
$myVar12

$_1myName underscore .
$1myName ,
.
$my-Name , , underscore .

6.2 :
assignment operator - . Assignment
operator = () .
=
. ; (semicolon) .

$myName = stallman;
$foss = Free Open Source Software;
$examNumber = 1002;
$cyclePrice = 1500.36;

$myName stallman
$foss Free Open Source Software

www.kaniyam.com
43

$examNumber 1002
$cyclePrice 1500.36 .

6.3 :
, , .

. .

. .

<?php
$myName = Kathirvel;
$myAge = 24;
$myHeight = 5.5;
$myWeight = 58;
echo <b>Old Data</b>;
echo <br>;
echo My Name is : $myName;
echo <br>;
echo My Age is : $myAge;
echo <br>;
echo My Height is : . $myHeight . inches;
echo <br>;
echo My Weight is : . $myWeight . Kg;
echo <br>;
$myName = Linux Kathirvel;
$myAge = 25;
$myHeight = 5.9;
$myWeight = 60;
echo <b>New Data</b>;
echo <br>;
echo My Name is : $myName;
echo <br>;
echo My Age is : $myAge;
echo <br>;
echo My Height is : . $myHeight . inches;
echo <br>;
echo My Weight is : . $myWeight . Kg;
?>

www.kaniyam.com
44

variables.php .
.

. (dot) concatenation character . statement


.
. .
. .

6.4 PHP :
PHP Data Type . integer, float, boolean,
array, object, resource and string.
. .

PHP Loosly typed language JavaScript . Loosly types language


data type variable data type
. interger float , float integer
.

Java, C, C++ Strongly Typed Languages.


data type data type
.

www.kaniyam.com
45

<?php

$myName = Kathir;
echo My Name is $myName;

$myName = 2500;
echo <br>;

echo My Salary is $myName;

?>

output:

$myName String Data Type , Integer Data type


.

6.5 (Check Whether a


variable is set):

. PHP
function isset(). Isset() function
. Function
.

www.kaniyam.com
46

<?php

$myName;

if (isset($myName)) {
echo It is Set.<br>;}

else {
echo It is Not Set.;}

?>

www.kaniyam.com
47

7 PHP :
Integer, String, Float, Boolean . Array,
Object .

7.1 (Integer Variable Type):


-2147483648 2147483647
. (-)
. (Float
Point) .

<?php
$mobilePrice = 13000;
$myNegative = -13457231;
echo Mobile Price : $mobilePrice;
echo <br>;
echo Negative Number : $myNegative;
?>

7.2 (Float Variable Type):


. 1.067, 0.25, 423454567098, 84664435.9576

www.kaniyam.com
48

<?php

$mobilePrice = 13000.3453453;
$myNegative = -13457231.3345354;

echo Mobile Price : $mobilePrice;


echo <br>;
echo Negative Number : $myNegative;

?>

7.3 (Boolean Variable Type):


true false
. Flow control and Looping
. if - . true
or false . PHP 0 or 1 .

<?php
$myName = Stallman;
echo isset($myName);
?>

www.kaniyam.com
49

isset($myName) true , 1 .

7.4 (String Variable Type):


(words and sentences)
.
PHP .

( ) Single Quotes ( ) Double Quotes


.

<?php

$myName = Kathirvel Rajendran;


$foss = Free Open Source Software.;
$string1 = This string contains single quotes';
$string2 = This string contains double quotes;

echo <br>;
echo $myName;
echo <br>;
echo $foss;
echo <br>;
echo $string1;
echo <br>;
echo $string2;

?>

www.kaniyam.com
50

backslash (\) escape character .


$
.

<?php
echo My Salary is \$5000.;
?>

Escape Sequences.

\n New Line
\r Carriage Return
\t Tab
\\ Backslash Character
\ Double Quotation Mark
\$ Dollar sign (prevents text from being treated as a variable name)
\034 Octal ASCII value
\xOC Hexadecimal ASCII Value

www.kaniyam.com
51

8 (Constants)
(Constants)

,
. , , , 1000 . = 1 ,
.
.

(constants) global scope - . Global scope


global scope - , function,
object .

(built-in)
constants PHP .

: (variable) (constants) .
.

8.1 (Defining a Constant):


(variable) $
. , (constants) define() function
. $ . define
function arguments . constant -
, constant - .

case sensitive .
. ,
(upper case letters)
.

www.kaniyam.com
52

<?php
define(WELCOME_MESSAGE, PHP is Easy to Learn.);
define(MY_WEIGHT,70);

echo WELCOME_MESSAGE;
echo <br>;
echo My Weight is : .MY_WEIGHT.Kg;
?>

constant ()
. $
$ .
.

defined () function
. define() function
argument .
true false .
MY_NAME
defined() function .

<?php
define(MY_NAME,KATHIRVEL R);
if (defined(MY_NAME)) {
echo My Name is : .MY_NAME;
echo <br>;
}

www.kaniyam.com
53

else {
echo What is your name?;
echo <br>;
}
?>

8.2 (Predefined Constants):


Web Developer PHP
(built-in)
. .
.

Script (Script and Environment Related


Constants):
PHP , (Client)
PHP .
.

__LINE__
.
__FILE__ .
__FUNCTION__ (function)
.
__CLASS__ class

www.kaniyam.com
54

.
__METHOD__ class method
.
PHP_VERSION PHP (Version) .
PHP_OS PHP pre-processor .
PHP_EOL (character) .
DEFAULT_INCLUDE_PATH include PHP
(default) .

(Mathematical Constants):
,
PHP .
.

(Constant)

M_E e
M_EULER Eulers
M_LNPI PI
M_LN2 2 -
M_LN10 10 -
M_LOG2E 2 E -
M_LOG10E 10 E
M_PI PI
M_PI_2 PI/2
M_PI_4 PI/4 -
M_1_PI 1/PI
M_2_PI 2/PI
M_SQRTPI PI
M_2_SQRTPI 2/PI
M_SQRT2 2
M_SQRT3 3
M_SQRT1_2 1/2

www.kaniyam.com
55

<?php
echo Value of e : .M_E;
echo <br>;
echo Value of Eulers constant : .M_EULER;
echo <br>;
echo The natural logarithm of PI : .M_LNPI;
echo <br>;
echo The natural logarithm of 2 : .M_LN2;
echo <br>;
echo The natural logarithm of 10 : .M_LN10;
echo <br>;
echo Value of base-2 logarithm of E : .M_LOG2E;
echo <br>;
echo The base-10 logarithm of E : .M_LOG10E;
echo <br>;
echo The value of PI : .M_PI;
echo <br>;
echo The value of PI/2 : .M_PI_2;
echo <br>;
echo The value of PI/4 : .M_PI_4;
echo <br>;
echo The value of 1/PI : .M_1_PI;
echo <br>;
echo The value of 2/PI : .M_2_PI;
echo <br>;
echo The square root of PI : .M_SQRTPI;
echo <br>;
echo The value 2/square root of PI : .M_2_SQRTPI;
echo <br>;
echo The square root of 2 : .M_SQRT2;
echo <br>;
echo The square root of 3 : .M_SQRT3;
echo <br>;
echo The square root of 1/2 : .M_SQRT1_2;
?>

www.kaniyam.com
56

www.kaniyam.com
57

9 Operators ()

Operators ()

(variables) (values) , , ,

. PHP .
++, , += .


. (Operands)
(Operators) .

(Operator)
, .

(expression)

1 + 3;

(expression) ,
. +
.

(expressions)
.

$myAddition = 1 + 3;

, $myAddition (variable)
(assignment)
(operator) (=) $myAddition .

www.kaniyam.com
58

9.1 (Assignment Operators):


= (equals)
(assignment operator) .
(Mathematical Operation) ,
.

PHP -
(Assignment Operators) .


(Type) (Description) (Example)
(Operator)


(Operands)
= $myVar=30;

.



+= , $myVar=10;$myVar+=5


.



= , $myVar=10;$myVar=5;


.



*= , $myVar=10;$myVar*=5;


.

www.kaniyam.com
59




/= , $myVar=10;$myVar/=10;


.



%= ModuloOperation $myVar=10;$myVar%=5;


.


$myName=Kathirvel;
.= $myName.=Rajendran;

.
:

<?php
echo <h3>Assignment</h3>;
$myVarA = 2500;
$myVarB = Free Open Source Software;
echo $myVarA;
echo <br>;
echo $myVarB;
//

echo <h3>Addition-Assignment</h3>;
$myVarC = 240;
$myVarC += 260;
echo $myVarC;
//

echo <h3>Subtraction-Assignment</h3>;
$myVarD = 1200;
$myVarD -= 500;
echo $myVarD;
//

echo <h3>Multiplication-Assignment</h3>;
$myVarE = 500;
$myVarE *= 500;
echo $myVarE;
//

www.kaniyam.com
60

echo <h3>Division-Assignment</h3>;
$myVarF = 1200;
$myVarF /= 200;
echo $myVarF;
//

echo <h3>Modulo-Assignment</h3>;
$myVar = 10;
$myVar %= 5;
echo $myVar;
//

echo <h3>Concatenation-Assignment</h3>;
$myName = Kathirvel;
$myName .= Rajendran;
echo $myName;
?>

www.kaniyam.com
61

9.2 (Arithmetic Operators):


.
.


(Operator) (Type) (Description) (Example)

+ $total=100+250;


.
$total=250100;

.

* . $total=100*200;
/ . $total=200/5;

% . $total=200%3;

<?php
echo <h3>Addition</h3>;
$myAdd1 = 240;
$myAdd2 = 260;
$myAddition = $myAdd1 + $myAdd2;
echo $myAddition;
//

echo <h3>Subtraction</h3>;
$mySub1 = 1200;
$mySub2 = 500;
$mySubtraction = $mySub1 $mySub2;
echo $mySubtraction;
//

www.kaniyam.com
62

echo <h3>Multiplication</h3>;
$myMul1 = 500;
$myMul2 = 500;
$myMultiplication = $myMul1 * $myMul2;
echo $myMultiplication;
//

echo <h3>Division</h3>;
$myDiv1 = 1200;
$myDiv2 = 200;
$myDivision = $myDiv1 / $myDiv2;
echo $myDivision;
//

echo <h3>Modulus</h3>;
$myMod1 = 10;
$myMod2 = 4;
$myModulus = $myMod1 % $myMod2;
echo $myModulus;
?>

9.3 (Comparison Operators):


(Comparison Operators)
. true false
. (strings)
. (Operands)
.
.

Operator
Type() Description() Examples()
()
== $myVar=10;if($myVar==10)
true
.

www.kaniyam.com
63

echomyVarequals10;

$myVar=10;if($myVar!=20)

!= true
. echomyVardoesnotequal10;

$myVar=10;if($myVar<>20)

<> true
. echomyVardoesnotequal10;

$myVar=10;$myString=10;

if($myVar===$myString)

=== true
echomyVarandmyStringaresame
typeandvalue;

$myVar=10;$myString=10;

if($myVar!==$myString)

!==

true echomyVarandmyStringarenot
sametypeandvalue.

$myVar=10;if($myVar<20)

< true echomyVariflessthan20;
.
$myVar=20;if($myVar>10)

> true echomyVariflessthan20;
.
$myVar=10;if($myVar<=5)

<= echomyVarislessthanorequalto
true 5;
.
>= $myVar=10;if($myVar>=5)

echomyVarisgreaterthanorequal
true
.

www.kaniyam.com
64

to5;

9.4 (Logical Operators):


(Logical Operators)
(expression)
(evaluate) true (1) false (0) . PHP
(Logical Operators)
.

Operator
Type() Description() Examples()
()
AND
&& AND If($a<25)&&($b>45))
.
OR
|| OR If(($a<25)||($b>45))
.
XOR
Xor XOR If(($a<25)xor($b>45))
.

9.5 (Increment and


Decrement Operators):
$myMark = 100;

$myMark = $myMark 1;


. ++
, PHP .

www.kaniyam.com
65

pre ()
post (). pre (mode)
(expression) . ,


pre .

post (mode)
(expression) . ,

post
.

,
pre post . $myMark++ , ++
post increment . ++$myMark
++ pre increment .

Operator
Type() Description() Equivalent()
()
$var=10;$var2=$var+1;

++$var (preincrement)
.


$var
(predecrement) . $var=10;$var2=$var1;

$var=10;$var2=$var;

$var++
. $var=$var+1;

$var=10;$var2=$var;

$var
. $var=$var1;

www.kaniyam.com
66

9.6 (String Concatenation Operator):


(string)
(operator) . (.)
. (values), (variable),
(constants), (strings)
.

,
echo 4589 . is my bike registration number;

4589 is my bike registration number.

9.7
(Execution Operator Executing Server Side
Commands)
,
. PHP .

.

(`) .
(`) . . (`)
(single quotes). (~)
.

<?php
echo `uname -a` . <br>;
echo `pwd` . <br>;
echo `date` . <br>;
?>

www.kaniyam.com
67

www.kaniyam.com
68

10 Flow Control and Looping


Flow Control and Looping

PHP , (web)
.
,
.

,


. (

). flow control and
looping .

(conditional Statements)

1. if statements
2. if else statements

(looping Statements)

1. while loops
2. do while loops

Switch Statements

, .

10.1 Conditional Statements


.

www.kaniyam.com
69

. ,
. ?
? ?
.


(instructions) . (conditional statements)
. Conditional statements (expression)

. (expression) true false
.

PHP . if if
else.

If statement ()
if
. If if
(parentheses) (expressions) .

$myMark = 98;

if ($myMark < 100)

, $myMark (variable) 2
? . true
false .

If , (expression) true ()
.
if open and closing braces
. braces . Braces
. if

www.kaniyam.com
70

braces .
,
.

<?php
$yourMark = 98;
if( $yourMark > 90 ) {
echo You have obtained ( .$yourMark. marks ) Good marks.;
}
?>

if else (if else statements)


if (expression) true ()
. (expression) false ()
if . if
else .
ifelse .

www.kaniyam.com
71

<?php
$milkPacketColor = blue;
if ( $milkPacketColor == blue ) {
$milkPrice = 45;
echo Milk Price is Rs..$milkPrice. p/l;
echo <br>;
}
else {
$milkPrice = 40;
echo Milk Price is Rs..$milkPrice. p/l;
echo <br>;
}
?>

if else if else if .

<?php
$customerName = Kathirvel;
if ( $customerName == Kathir ) {
echo Customer Name : .$customerName;
echo <br>;
}
else if ( $customerName == Kathirvel ) {
echo Customer Name : .$customerName;
echo <br>;
}
else {
echo Sorry!;
echo <br>;
}
?>

www.kaniyam.com
72

10.2 ( Looping Statements)



.
.
looping statements ( ) .

PHP .

1. for loop
2. while loop
3. do while loop

for loops (for )


PHP
.

<?php
$myInterest = 1;
$myInterest += $myInterest;
$myInterest += $myInterest;
$myInterest += $myInterest;
$myInterest += $myInterest;
$myInterest += $myInterest;
$myInterest += $myInterest;
$myInterest += $myInterest;

www.kaniyam.com
73

$myInterest += $myInterest;
$myInterest += $myInterest;
$myInterest += $myInterest;
echo My Interest Amount Rs..$myInterest;
echo <br>;
?>

, 10
. 1000 10000
.
? , .
for .

For (loop) (syntax):


for ( initializer; conditional expression; loop expression )

//PHP statements to be executed go here

initializer counter variable initialize . $i


. $i = 0 . $i 0
.

loop conditional expression .


Loop 1000 $i < 1000 .

www.kaniyam.com
74

, loop expression counter variable


. counter variable 1
.

$i++

?
.

<?php
$myInterest = 1;
for ( $i=0 ; $i < 10 ; $i++ ) {
$myInterest += $myInterest;
}
echo My Interest Rs..$myInterest;
echo <br>;
?>

While loops (while )


for loop loop
.
loop
? while loop .

www.kaniyam.com
75

While loop (syntax of while loop)


<?php

while ( condition )

// PHP statements go here

?>

condition true while loop . false loop


.

<?php
$myInterest = 1;
$j = 1;
while ( $j <= 10 ) {
$myInterest += $myInterest;
$j++;
}
echo My Interest Rs..$myInterest;
echo <br>;
?>

www.kaniyam.com
76

do while loops(do while )


do while loop while
. while loop while loop
while loop
. loop
loop . ,
loop
do while loop
. Do while loop .

do while (do while loop syntax):


<?php
do
{
PHP statements
}
while (conditional expression)
?>

<?php
$myInit = 0;
do
{
echo $myInit.Hello PHP!;
echo <br>;
$myInit++;
}
while($myInit < 5);
echo Thank You!;
?>

www.kaniyam.com
77

10.3 switch (switch statements)


ifelse .
ifelse .
ifelse ,
.
switch
.

switch (syntax)
switch (value)

case match1:

PHP statements

break;

case match2:

PHP statements

www.kaniyam.com
78

break;

case match3:PHP Essentials

PHP statements

break;

case match4:

PHP statements

break;

case match5:

PHP statements

break;

default:

PHP statements

break;

switch (value)
. case (statements)
. case
, .
case . case
. default
.
break . break
.

www.kaniyam.com
79

, a,e,i,o,u
. ifelse
.

<?php
$inputChar = e;

if ( $inputChar == a ) {
echo $inputChar is vowel.;
echo <br>;
}

elseif ( $inputChar == e ) {
echo $inputChar is vowel.;
echo <br>;
}

elseif ( $inputChar == i ) {
echo $inputChar is vowel.;
echo <br>;
}

elseif ( $inputChar == o ) {
echo $inputChar is vowel.;
echo <br>;
}

elseif ( $inputChar == u ) {
echo $inputChar is vowel.;
echo <br>;
}

else {
echo Input Character is not a vowel;
}
?>

www.kaniyam.com
80

switch
.

<?php
$inputChar = e;

switch ($inputChar) {

case a:
echo $inputChar is a vowel;
break;

case e:
echo $inputChar is a vowel;
break;

case i:
echo $inputChar is a vowel;
break;

case o:
echo $inputChar is a vowel;
break;

case u:
echo $inputChar is a vowel;
break;

default:
echo $inputChar is not a vowel;
break;
}
?>

www.kaniyam.com
81

10.4 (Breaking a Loop):


loop break .
break .

1000 . loop
10 break .

<?php
for ( $i = 0; $i < 1000; $i++) {
if ($i == 10) {
break;
}
echo <b>$i</b><br>;
}
?>

www.kaniyam.com
82

Breaking out of Nested Loops

<?php
for ( $i = 1; $i < 20; $i++) {
echo <h1>$i</h1><br>;
for ( $j = 1; $j < 50; $j++)
{
echo $j<br>;
if ($j == 5) {
break;
}
}
}
?>

www.kaniyam.com
83

www.kaniyam.com
84

11 Functions

Functions ()

11.1 Function () ?
PHP . PHP 1000
build-in functions .

(function) (statements) .

load .

11.2 (function) ?
,
. (variable)
(function) .

.

function (key word) (function)


. Function
. (a set of parentheses) .
(body of function) opening and closing braces .

www.kaniyam.com
85

<?php

//function creation
function myFunction() {
echo <h2>PHP Functions</h2>;
echo Hello PHP!;
}

//function calling
echo myFunction();
myFunction();
?>

www.kaniyam.com
86

11.3 (Returning a Value


from a function)
.
.
.

<?php

function myReturnFunction() {
$myFirstName = Kathirvel;
$myLastName = Rajendran;
$myFullName = $myFirstName. .$myLastName;
return $myFullName;
}

echo My Name is .myReturnFunction();


?>

11.4 (passing parameters


to a function)
.
. .

. (parameters names) (parentheses)

www.kaniyam.com
87

.
.
.

<?php

function myMultiplication($firstNumber, $secondNumber) {


return $firstNumber * $secondNumber;
}

echo <h2>Multiplication using Function Parameters</h2>;


echo myMultiplication(1540,2346.33);
?>

myMultiplication() function
firstNumber and secondNumber
.

11.5 (calling functions)



.
.

www.kaniyam.com
88

<?php

function addNumbers($firstNumber, $secondNumber) {


return $firstNumber + $secondNumber;
}

function mulNumbers($firstNumber, $secondNumber) {


return $firstNumber * $secondNumber;
}

function subNumbers($firstNumber, $secondNumber) {


return $firstNumber $secondNumber;
}
function divNumbers($firstNumber, $secondNumber) {
return $firstNumber / $secondNumber;
}

$first = 205;
$second = 40.57;
echo <h2>Simple Calculator Using Functions</h2>;
echo Addition of $first, $second = .addNumbers($first, $second);
echo <br>;
echo Multiplication of $first, $second = .mulNumbers($first,
$second);
echo <br>;
echo Subtraction of $first, $second = .subNumbers($first,
$second);
echo <br>;
echo Division of $first, $second = .divNumbers($first, $second);

?>

www.kaniyam.com
89

11.6 Passing Parameters by Reference


<?php

function myAddition($firstNumber , $secondNumber) {


$firstNumber += 100;
$secondNumber += 200;
return $firstNumber + $secondNumber;
}

$setFirstNumber = 100;
$setSecondNumber = 200;

echo <h4>Before</h4>setFirstNumber = $setFirstNumber,


setSecondNumber = $setSecondNumber <br>;
myAddition($setFirstNumber , $setSecondNumber);
echo <h4>After</h4>setFirstNumber = $setFirstNumber,
setSecondNumber = $setSecondNumber<br>;

?>

www.kaniyam.com
90

$setFirstNumber $setSecondnumber
myAddition() (function) .
,
myAddition() function . myAddition()
function $setFirstNumber
$setSecondNumber
.

function , function-

reference . passing by reference .
. function parameters
variable (&) . (&)
.

<?php
function myAddition(&$firstNumber , &$secondNumber) {
$firstNumber += 100;
$secondNumber += 200;
return $firstNumber + $secondNumber;
}

www.kaniyam.com
91

$setFirstNumber = 100;
$setSecondNumber = 200;

echo <h4>Before</h4>setFirstNumber = $setFirstNumber,


setSecondNumber = $setSecondNumber <br>;

myAddition($setFirstNumber , $setSecondNumber);
echo <h4>After</h4>setFirstNumber = $setFirstNumber,
setSecondNumber = $setSecondNumber<br>;

?>

11.7 Functions and Variable Scope


Two Scopes

1. global scope
2. local scope

www.kaniyam.com
92

Global Scope
function variable declare global scope
. Gobal scope variable
.

Local Scope
function variable declare local scope . local
scope variable declare function-
. function- .

www.kaniyam.com
93

12 Arrays

PHP Arrays (variable)


(variable) . Array
(items) , ,
, . Array
. Array
.

Array key .
Array . Array key
.

1. Numerical Array
2. Associative Array

12.1 Numerical Array


Numerical Key Array Array numerical position -
. Array element 0,
element 1 and so on.

www.kaniyam.com
94

12.2 Associative Array


Associative Array Array
.

12.3 Array (Creating a Array)


array() function Array . Array() function 0
argument array
. Assignment Operator (=) array
.

Array (grow),
(shrink). dynamic .
array
.

12.4 Empty Array (empty array creation)

<?php
$emptyArray = array();
?>

, array arguments -
array .

<?php
$linuxDistros = array(Redhat , Debian , Slackware , Ubuntu
, Fedora);
?>

www.kaniyam.com
95

12.5 Array -
numerical key array
square brackets ( [] ) - (index) .
0 .
?

<?php
$linuxDistros = array(Redhat , Debian , Slackware , Ubuntu
, Fedora);
echo elements 0 = .$linuxDistros[0];
echo <br>;
echo elements 1 = .$linuxDistros[1];
echo <br>;
echo elements 2 = .$linuxDistros[2];
echo <br>;
echo elements 3 = .$linuxDistros[3];
echo <br>;
echo elements 4 = .$linuxDistros[4];
?>

www.kaniyam.com
96

12.6 Associative Array (Creating an Associative


Array)
Associative Array numerical position .
associative array
. Associative Array array() function . Key =>
value associative array arguments .
key value , value value -
.

associative array
.

<?php
$myDetails = array(name=>KATHIRVEL R , age=>25 ,
mobile=>9999999999 ,qualification=>Engineering);
?>

12.7 Associative Array (Accessing


Elements of an Associative Array)
Associative Array .
? .
$myDetails .

<?php
$myDetails = array(name=>KATHIRVEL R , age=>25 ,
mobile=>9999999999 ,qualification=>Engineering);
echo $myDetails[name];
echo <br>;
echo $myDetails[age];
echo <br>;
echo $myDetails[mobile];
echo <br>;
echo $myDetails[qualification];
echo <br>;
?>

www.kaniyam.com
97

12.8 Array (Using Array Pointers)


Array (pointer)
. Next, previous, reset end function
. reset end (functions)
array - . Prev function
. Pre
next functions false
.
array array
.

<?php
$linuxDistros = array(Redhat , Debian , Slackware , Ubuntu
, Fedora);
echo elements 0 = .$linuxDistros[0];
echo <br>;
echo elements 1 = .$linuxDistros[1];
echo <br>;
echo elements 2 = .$linuxDistros[2];
echo <br>;

www.kaniyam.com
98

echo elements 3 = .$linuxDistros[3];


echo <br>;
echo elements 4 = .$linuxDistros[4];
echo <br>;
echo <b>Using Array Pointers</b>;
echo <br>;
echo The Last element of array is . end($linuxDistros);
echo <br>;
echo The Previous element is . prev($linuxDistros);
echo <br>;
echo The Previous element is . prev($linuxDistros);
echo <br>;
echo The First element of array is . reset($linuxDistros);
echo <br>;
echo The Next element is . next($linuxDistros);
?>

12.9 Array ,
(Changing, Adding and Removing Array Elements)

Array (change the element)




. function .

www.kaniyam.com
99

<?php
$mobileBrands = array(Samsung , Sony , MicroMax);
echo Before, Second Element of array : .$mobileBrands[1];
echo <br>;
$mobileBrands[1] = HTC;
echo After, Second Element of array : .$mobileBrands[1];
?>

(Add a new element)


array_push() function array
. array_push() function .
array , .

www.kaniyam.com
100

<?php
$mobileBrands = array(Samsung , Sony , MicroMax);
echo <b>Before</b>;
echo <br>;
echo $mobileBrands[0];
echo <br>;
echo $mobileBrands[1];
echo <br>;
echo $mobileBrands[2];
echo <br>;
echo <b>After</b>;
echo <br>;
array_push($mobileBrands, Panasonic);
echo $mobileBrands[0];
echo <br>;
echo $mobileBrands[1];
echo <br>;
echo $mobileBrands[2];
echo <br>;
echo $mobileBrands[3];
echo <br>;
?>

www.kaniyam.com
101

array_push() function array .


array_unshift() function .

<?php
$mobileBrands = array(Samsung , Sony , MicroMax);
echo <b>Before</b>;
echo <br>;
echo $mobileBrands[0];
echo <br>;
echo $mobileBrands[1];
echo <br>;
echo $mobileBrands[2];
echo <br>;
echo <b>After</b>;
echo <br>;
array_unshift($mobileBrands, Panasonic);
echo $mobileBrands[0];
echo <br>;
echo $mobileBrands[1];
echo <br>;
echo $mobileBrands[2];
echo <br>;
echo $mobileBrands[3];
echo <br>;
?>

Array (remove the array element)


array_pop() function array
.

<?php
$mobileBrands = array(Samsung , Sony , MicroMax);
echo <b>Before</b>;
echo <br>;
echo $mobileBrands[0];

www.kaniyam.com
102

echo <br>;
echo $mobileBrands[1];
echo <br>;
echo $mobileBrands[2];
echo <br>;
echo <b>After</b>;
echo <br>;
array_pop($mobileBrands);
echo $mobileBrands[0];
echo <br>;
echo $mobileBrands[1];
echo <br>;
echo $mobileBrands[2];
?>

array_shift() function - array


.

www.kaniyam.com
103

<?php
$mobileBrands = array(Samsung , Sony , MicroMax);
echo <b>Before</b>;
echo <br>;
echo $mobileBrands[0];
echo <br>;
echo $mobileBrands[1];
echo <br>;
echo $mobileBrands[2];
echo <br>;
echo <b>After</b>;
echo <br>;
array_shift($mobileBrands);
echo $mobileBrands[0];
echo <br>;
echo $mobileBrands[1];
echo <br>;
echo $mobileBrands[2];
?>

12.10 Looping array (Looping


through array Elements)
array ,
loop .
foreach loop. Foreach loop - array for
while loop .

Foreach loop . array


variable () -
loop body .

<?php
$mobileBrands = array(Samsung , Sony , MicroMax);
foreach( $mobileBrands as $mobileBrandArrayValues ) {
echo $mobileBrandArrayValues <br>;
}
?>

www.kaniyam.com
104

associative array .
. associative array key, value
key, value variable foreach loop
.

<?php
$myDetails = array(name=>KATHIRVEL R , age=>25 ,
mobile=>9999999999 ,qualification=>Engineering);

foreach ( $myDetails as $myDetailsKey => $myDetailsValue) {


echo Key = $myDetailsKey <br>;
echo Value = $myDetailsValue <br>;
}

?>

www.kaniyam.com
105

12.11 Replacing Sections of an Array


array_splice() function array
. array_splice() function ,
. Array
,
.

12.12 Array - .
.

sort() function , rsort() function -


.

function - . array
, (algorithm) .
.

SORT_NUMERIC

www.kaniyam.com
106

SORT_STRING

SORT_REGULAR

SORT_REGULAR .

<?php
$myArray = array(KATHIRVEL, 9500, KARTHIK, ARIVAZHAGAN,
4598);
echo <h2>Ascending Order</h2>;
echo <b>SORT_NUMERIC</b><br>;
sort($myArray, SORT_NUMERIC);

foreach ( $myArray as $mySortArray) {


echo $mySortArray<br>;
}

echo <br>;
echo <b>SORT_STRING</b><br>;
sort($myArray, SORT_STRING);

foreach ( $myArray as $mySortArray) {


echo $mySortArray<br>;
}
echo <br>;
echo <b>SORT_REGULAR</b><br>;
sort($myArray, SORT_REGULAR);

foreach ( $myArray as $mySortArray) {


echo $mySortArray<br>;
}

echo <h2>Descending Order</h2>;


echo <b>SORT_NUMERIC</b><br>;
rsort($myArray, SORT_NUMERIC);

foreach ( $myArray as $mySortArray) {


echo $mySortArray<br>;
}

echo <br>;
echo <b>SORT_STRING</b><br>;
rsort($myArray, SORT_STRING);

www.kaniyam.com
107

foreach ( $myArray as $mySortArray) {


echo $mySortArray<br>;
}

echo <br>;
echo <b>SORT_REGULAR</b><br>;
rsort($myArray, SORT_REGULAR);

foreach ( $myArray as $mySortArray) {


echo $mySortArray<br>;
}
?>

www.kaniyam.com
108

www.kaniyam.com
109

12.13 Associative Array -


Associative Array

1.key -

2.value -

www.kaniyam.com
110

Key
ksort() function , krsort() function
.

Value
asort() function , arsort() function
. Sort rsort syntax and options ,
.

12.14 Array
array (functions)
array function - PHP
.
.

Function() Description()
Print_r Array
array_keys Associativearray key
,
array_search
key .
array_values Array .
array true false
in_array
.
array_merge array array.
array_reverse Array .
Shuffle Random array .

www.kaniyam.com
111

13 Working with Strings and Text in PHP


PHP web content
. web content (text) .
,
(features) PHP .

PHP
. Web developer
. ,
,
.
. PHP .

13.1 (Changing the Case of a PHP


String)
(string)
(function) PHP .
(string) ,
.

nondestructive (), (Original String)
.
(variable) .

<?php
$myName = KATHIRVEL R;
$myOS = GNU/Linux;

www.kaniyam.com
112

$myNameInSmall = strtolower($myName);
$myOsInUpper = strtoupper($myOS);

echo My Name is $myNameInSmall.<br>;


echo I am using $myOsInUpper Operating System for past 5-
years.<br>;
?>

(string) .
.

<?php
$myName = KATHIRVEL R;
$myOS = GNU/Linux;

$myName = strtolower($myName);
$myOS = strtoupper($myOS);
echo My Name is $myName.<br>;
echo I am using $myOS Operating System for past 5-years.<br>;
?>

PHP ,
.

Strtolower() (lower case) .

Strtoupper() (upper case) .

www.kaniyam.com
113

Ucfirst() .

Ucwords()
.

13.2 ASCII ASCII



ASCII (American Standard Code for Information Interchange)
PHP . 127 ASCII
( ).

ASCII ASCII PHP


.

ord() character - ASCII code


.

Chr() ASCII character charater -


.

<?php
$smallCase = abcdefghijklmnopqrstuvwxyz;
$upperCase = strtoupper($smallCase);
echo <b>Character ASCII Code</b><br>;

for ( $i=0 ; $i<strlen($smallCase) ; $i++ ) {


echo $smallCase[$i] = . ord($smallCase[$i]);
echo || ;
echo $upperCase[$i] = . ord($upperCase[$i]) . <br>;
}

?>

www.kaniyam.com
114

www.kaniyam.com
115

ASCII to Character

www.kaniyam.com
116

<?php
echo <b>ASCII Codes</b><br>;
for ( $i = 33 ; $i < 127 ; $i++ ) {
echo $i = .chr($i).<br>;
}
?>

www.kaniyam.com
117

13.3 (Printing Formatted Strings)


fprintf() function (formatted) .
. .

fprintf(String, variable1, variable2);

string , formatting specifiers


variable .

printf Formatting Specifiers

formatting specifiers % .
specifier . decimal
number %d .

specifier .

Specifier Description
%% 1 .
%b 544.
$c ASCII character .
%d .
%e Scientificnotation(ex.1.2e+5)
%u Unsigneddecimalnumber
%f Floatingpointnumber
%F Floatingpointnumber
%o Octalnumber
%s String
%x Hexadecimalnumber
%X Hexadecimalnumber

www.kaniyam.com
118

<?php
$myName = KATHIRVEL;
$myAge = 25;
$myLang = Tamil;
$myHeight = 177.08;
printf(My name is %s. I am %d years old. my language is %s and my
height is %f cms,$myName,$myAge,$myLang,$myHeight);
?>

13.4 (Finding the Length of a


String)
strlen() function . Strlen() function
.

<?php
$myName = KATHIRVEL;
echo My Name Contains . strlen($myName) . letters.;
?>

www.kaniyam.com
119

13.5 Array (Converting a String into a


Array)
explode() function array . Explode() function
. Delimeter array -
. , space or comman . String array
(string). divisions()
.

<?php
$foss = Free Open Source Software;
$fossArray = explode( , $foss);
foreach ($fossArray as $i) {
echo $i;
echo <br>;
}
?>

www.kaniyam.com
120

<?php
$timeNow = 07:10:55;
$timeArray = explode(:, $timeNow);
echo $timeArray[0] . Hours, . $timeArray[1] . minutes, .
$timeArray[1] . Seconds;
?>

13.6 whitespace
(Removing Leading and Trailing Whitespace from a String)
, trim() function
. tab, space, newline, carriage return, NULL and vertical tab
. trim() function string
whitespace - .

<?php
$myName = KATHIRVEL ;
echo Before apply the trim() function<br>;
echo $myName -.strlen($myName).<br>;
echo After apply the trim() function<br>;
echo trim($myName). . strlen(trim($myName));
?>

www.kaniyam.com
121

13.7 (Comparing Strings)


web developing
.
(functions) PHP .
.

Strcmp() case-sensitive .
.

Strcasecmp() case-insensitive
.

Strncmp() ,
, character . case-
sensitive , .

Strncasecmp() ,
, character
. case-insensitive ,
.

(String Comparison
Functions Return Value)
ASCII (string comparison

www.kaniyam.com
122

functions) . character - ASCII


. strings ASCII 0
. ASCII , ASCII
negative number - .
positive number .

<?php
$string1 = A;
$string2 = K;

echo ASCII($string1) = .ord($string1);


echo <br>;

echo ASCII($string2) = .ord($string2);


echo <br>;

echo strcmp($string1, $string2);


?>

13.8 (Accessing and Modifying


Characters in String)

. string variable { }
. 0
. 1 .

<?php

www.kaniyam.com
123

$myName = KATHIRVEL;
$myNewName = $myName{6}.$myName{7}.$myName{8};

echo $myNewName;
echo <br>;

$myName{6} = 0;
$myName{7} = 0;
$myName{8} = 7;

echo $myName;
?>

13.9 ,
(Searching for Characters and Substrings in a String)
PHP .
substring . strpos() strrpos()
.

Strpos() .
, .
,
.

.

www.kaniyam.com
124

,
0 .
0(Numeric) , 0
(Boolean 0) .
=== (Identically equal) !== (Identically not equal)
. Operator .
?

<?php
$myName = KATHIRVEL;
$searchStr = V;

if ( strpos($myName,$searchStr) !== false ) {


echo $searchStr match at . strpos($myName, $searchStr) .
position in ( $myName );
}

else {
echo Match Not Found;
}

?>

13.10 Extracting and Replacing Substrings


substr() substr_replace()
, .

www.kaniyam.com
125

substr() . (source string),


.
.

<?php
$foos = Free Open Source Software;
$fossSub = substr($foos, 5, 11);
echo $fossSub;
?>

substr_replace() function . ,
,
,
.

<?php
$foos = Free Open Source Software;
$fossSub = substr($foos, 5, 11);

echo $fossSub;
echo <br>;
echo <b>Substring Replace</b>;

$fossRep = Libre;
echo <br>;
echo substr_replace($foos,$fossRep,0,4);
?>

www.kaniyam.com
126

13.11 Replacing All Instances of a Word in a String


Replace .
str_replace() function . ,
. ,
,
.

<?php
$foss = Free Open Source Software;
$fossSub = substr($foss, 5, 11);

echo $fossSub;
echo <br>;
echo <b>Substring Replace</b>;
$fossRep = Libre;

echo <br>;
echo substr_replace($foss,$fossRep,0,4);
echo <br>;
echo <b>String Replace</b>;
$fossRep = Libre;

echo <br>;
echo str_replace(Software, $fossRep, $foss);
?>

www.kaniyam.com
127

www.kaniyam.com
128

14 , /
(File systems and File I/O)

PHP server side scripting , web developer


(server)
. , ,
PHP . ,
, ,
.

14.1 (Opening and Creating


Files)
,
fopen() function . Fopen() function
.
.
.
. (web server) root - .
(create, read only, write only etc)
.

www.kaniyam.com
129

Mode
Description()
()
R Readonlyaccess. .
R+ ReadandWriteaccess. .
Writeonlyaccess. .
W
, .
ReadandWriteaccess. .
W+ ,
.
Writeonlyaccess. .
A
, .
Readandwriteaccess. .
A+
, .
Createandopenforwriteonly.
X . false
.
Createandopenforreadandwrite.
X+ . false
.

14.2 (Closing Files)


fclose() function -
. fclose() function .

<?php
$fileHandle = fopen(/tmp/phpintamil.txt, w+) or die(Cant
open the file);
fclose($fileHandle);
?>

www.kaniyam.com
130

/tmp/ phpintamil.txt .
w+ . w+
, .
. Fclose() function .

14.3 (Writing to a File)


,
. Fwrite() fputs() funtions
. Fwrite() . Fopen()
function variable ,
.

<?php
$myFile = fopen(/tmp/phpintamil.txt , w+) or die(Cant Open
the file.);
$myFileWrite = fwrite ( $myFile, Free Open Source Software );

www.kaniyam.com
131

if ( $myFileWrite ) {
echo Data Written Successfully.<br>;
}

else {
echo Data Write Failed.<br>;
}

fclose($myFile);
?>

www.kaniyam.com
132

14.4 (Reading From a File)


fread() function . fread() function
.
variable , byte
.

<?php
$fileOpen = fopen(/tmp/phpintamil.txt , w+) or die (Cant
Open the File);
fwrite ($fileOpen, Linux will rule the world.);
fclose($fileOpen);
$fileOpen = fopen(/tmp/phpintamil.txt , r) or die (Cant open
the file.);
$fileRead = fread ($fileOpen, 1024);
echo <b>Data from phpintamil.txt file</b><br> . $fileRead;
?>

die() function ,
.
function .

14.5 (Checking Whether a File


Exists)
file_exists()

www.kaniyam.com
133

function . path file_exists() function


. false , true
.

<?php

if ( file_exists(/tmp/phpintamil.txt) ) {
echo File Exist.;
}

else {
echo File Doent Exist.;
}

?>

14.6 , (Moving,
Copying and Deleting Files)
copy() function , rename() function , unlink()
function .

Copy

www.kaniyam.com
134

<?php
if ( copy(/tmp/practice.old , /tmp/practice) ) {
echo Copy Successfully<br>;
}
?>

Rename

<?php
if ( rename( /tmp/practice.txt , /tmp/practice.old) ) {
echo Renamed Successfully<br>;
}
?>

Delete

<?php
if ( unlink(/tmp/practice.txt) ) {
echo Delete Successfully<br>;
}
?>

14.7 (Accessing File Attributes)


, ,

PHP .

PHP stat() fstat()


(functions) .
, associative array - . array
.

stat() fstat() function


. Stat() function - (full path of
file), fstat() function - fopen()
.

www.kaniyam.com
135

Key Description
Dev DeviceNumber
Ino Inodenumber
Mode Inodeprotectionmode
Nlink Numberoflinks
Uid UserIDofowner
Gid GroupIDofowner
Rdev Inodedevicetype
Size Sizeinbytes
Atime Lastaccess(Unixtimestamp)
Mtime Lastmodified(Unixtimestamp)
Ctime Lastinodechange(Unixtimestamp)
Blksize BlocksizeoffilesystemIO(platformdependent)
Blocks Numberofblocksallocated

<?php
$results = stat (/tmp/phpintamil.txt);
$fileNew = fopen(/tmp/phpintamil.txt, r);
$fileDetails = fstat($fileNew);
echo <b>Using stat() function</b><br>;
echo File Size is : $results[size] bytes<br>;
echo File last modified on $results[mtime]<br>;
echo File Occupies $results[blocks] filesystem blocks<br>;
echo <b>Using fstat() function</b><br>;
echo File Size is : $fileDetails[size] bytes<br>;
echo File last modified on $fileDetails[mtime]<br>;
echo File Occupies $fileDetails[blocks] filesystem blocks<br>;
fclose($fileDetails);
?>

www.kaniyam.com
136

, (access rights )
. is_readable() is_writable() function
. true or false
.

14.8 (Output Buffering)



output stream - output
buffering mechanism .

Output Buffering ob_start() function . ob_start()


function - .
optional .

1.callback funtion

www.kaniyam.com
137

2.bytes

3.delete buffer

Buffer- ob_flush() function - .


ob_end_flush() function .

ob_clean() function buffer .


ob_get_contents() function - buffer -
.

<?php
echo <b>Before Using ob_start() function</b><br>;

ob_start(); //start buffering


echo This content will be buffered<br>; //write to the buffer

echo <b>Display buffered content using ob_get_contents()


function</b></br?;
echo <br> . ob_get_contents();
echo <br>;
ob_end_flush(); //flush the output from the buffer

echo <b>After Using ob_end_flush() function</b><br>;


echo ob_get_contents();
?>

www.kaniyam.com
138

www.kaniyam.com
139

15 (Working with
Directories)

? .
PHP ? .
, ,
function PHP .

15.1 (Creating Directories)


mkdir() function .

mkdir() function .

(full path) .

www.kaniyam.com
140

<?php
//create a new directory using PHP
$yourDirectoryName = /tmp/phpintamil;
if ( mkdir($yourDirectoryName) ) {
echo $yourDirectoryName is successfully created.<br>;
}
else {
echo Directory creation failed.<br>;
}
?>

www.kaniyam.com
141

15.2 (Deleting Directory)


rmdir() function .
.
.
.
.

<?php
//create a new directory using PHP
$yourDirectoryName = /tmp/phpintamil;
if ( rmdir($yourDirectoryName) ) {
echo $yourDirectoryName is successfully deleted.<br>;
}
else {
echo Cant delete the directory.<br>;
}
?>

www.kaniyam.com
142

15.3 Finding and Changing the Current Working Directory


getCwd() function
.

<?php
$currentDirectroy = getCwd();
echo Current Directory is $currentDirectroy;
?>

chdir() funtion .
.

<?php
$currentDirectroy = getCwd();
echo Current Directory is $currentDirectroy<br>;
$changeDirectory = /home/kathirvel/Pictures;
chdir($changeDirectory);
$currentDirectroy = getCwd();
echo Current Directory is now $currentDirectroy;
?>

www.kaniyam.com
143

15.4 (Listing Files


in a Directory)
scandir() function .
scandir() .
,
. 0 alphabetical , 1
reverse-alphabetical .

<?php
chdir(/tmp);
$currentDirectory = getCwd();
echo Current Directory is now $currentDirectory<br>;
$dirArray = scandir(., 1 );
print_r($dirArray);
?>

www.kaniyam.com
144

16 HTML Forms
(web based) (application)
.
web based application - ,
, (forms)
, .

HTML <form> tag (web forms) . PHP


HTML form , HTML
form .
HTML form . HTML
form
.

16.1 HTML (Creating HTML Forms)


HTML forms .

(web server) .
(process) .

<form> tag HTML form . GET


POST
. GET
URL - . GET
.
POST .
.

HTML form ?

www.kaniyam.com
145

<html>
<head>

<title>Simple HTML Form</title>

</head>

<body>

<form action="submit.php" method="post">

<input type="text" name="customerName" value="Your Name" />

<input type="submit" name="submit_button" value="Press to


Submit" />

</form>

</body>

</html>

16.2 HTML Text Object ( )


HTML Form -
Text Obect .
Text Object .

www.kaniyam.com
146

Text Object - Syntax

<input type=text name=objectname id=objectid value=currentvalue size=30


event_handling>

type text object .

Name text object - . JavaScript, PHP


text object -
.

Id getElementsById() method - text object - id


.

Value Text Object - .

Size Text Field


.

Text Object - event JavaScript


Action Event handling .

Text Object - Event Trigger .

onFocus

onBlur

onChange

onSelect

www.kaniyam.com
147

16.3 HTML TextArea Object ( )


<textarea> tag TextArea Object .
text object . ,
textarea . TextArea
Object - attributes .
row and columns( ) ,

. wrap() attribute
. virtual() and
physical().

virtual(soft) carriage return .

physical(hard) carriage return .

off .
, Enter Key .

<html>
<head>
<title>TextArea Example</title>
</head>
<body>
<b>wrap - soft</b><br>
<textarea rows="10" cols="10" wrap="soft"></textarea><br>
<b>wrap - hard</b><br>
<textarea rows="10" cols="10" wrap="hard"></textarea><br>
<b>wrap - off</b><br>
<textarea rows="10" cols="10" wrap="off"></textarea><br>
</body>
</html>

www.kaniyam.com
148

16.4 The HTML Button Object ( )


HTML (form) text object ,
button() object . .

type=button .
.
.

www.kaniyam.com
149

type=submit (server)
. <form> tag Onsubmit Attribute
onsubmit attribute
function . JavaScript
(validation)
onsubmit attribute .

type=reset clear default


value( ) .

<input> tag button object . Type


.

formuserinput.html

<html>
<head>
<title>User Input Form</title>
</head>
<body>
<form onsubmit="" method="post" action="formgetuserdata.php">
<p>First Name:<input type="text" name="firstname" size="15"><br>
Last Name:<input type="text" name="lastname" size="15"><br>
Email:<input type="email" name="emailid"><br></p>
<input type="submit" value="Send">
</form>
</body>
</html>

formgetuserdata.php

<?php
$name = $_POST["firstname"]." ".$_POST["lastname"];
$email = $_POST["emailid"];
echo "<p>Welcome <b>$name!</b><br>You can reach $name via
<i>$email</i></p>";
?>

www.kaniyam.com
150

16.5 HTML check Boxes


check box object . click
checked unchecked .
, checkbox object
.

<input> tag check box object .


.

checkbox.html

<html>
<head>
<title>Check Box</title>
</head>
<body>
<form method="post" name="orderform" action="checkboxgetdata.php">
<p>What is your favourite programming language?</p>
<input type="checkbox" name="language" value="Python">Python<br>
<input type="submit">
</form>
</body>
</html>

www.kaniyam.com
151

checkboxgetdata.php

<?php
$name = $_POST["language"];
echo "Your favorite programming language is
<i><big>$name</big></i>.";
?>

16.6 HTML Radio Button



Radio Button Object .

Radion Button ?

<html>
<head>
<title>Radion Button Example</title>
</head>
<body>
<form method="post" action="radiogetdata.php" name="userchoice">
<input type="radio" name="myLinux" value="Ubuntu" checked>Ubuntu
14.04 LTS
<input type="radio" name="myLinux" value="Fedora">Fedora 21

www.kaniyam.com
152

<input type="radio" name="myLinux" value="LinuxMint">Linux Mint 17


<br><input type="submit">
</form>
</body>
</html>

radiogetdata.php

<?php
$name = $_POST["myLinux"];
echo "Your favourite GNU/Linux OS is <i><big>$name</big></i>.";
?>

16.7 HTML Drop-down / Select Object


select object drop down list .
.

<html>
<head>
<title>Drop Down List</title>
</head>
<body>
<p>Select your Laptop Brand:</p>
<select name="myLaptopBrand">

www.kaniyam.com
153

<option value="Lenova">Lenova</option>
<option value="Acer">Acer</option>
<option value="HP">HP</option>
<option value="Samsung">Samsung</option>
<option value="DELL" selected>DELL</option>
</select>
</body>
</html>

size attribute , scrolled list .


scrolling .

<html>
<head>
<title>Drop Down List</title>
</head>
<body>
<p>Select your Laptop Brand:</p>
<select name="myLaptopBrand" size="2">
<option value="Lenova">Lenova</option>
<option value="Acer">Acer</option>
<option value="HP">HP</option>
<option value="Samsung">Samsung</option>
<option value="DELL" selected>DELL</option>
</select>
</body>
</html>

www.kaniyam.com
154

multiple attribute dropdown list


.

<html>
<head>
<title>Drop Down List</title>
</head>
<body>
<p>Select your Laptop Brand:</p>
<select name="myLaptopBrand[]" size="2" multiple>
<option value="Lenova">Lenova</option>
<option value="Acer">Acer</option>
<option value="HP">HP</option>
<option value="Samsung">Samsung</option>
<option value="DELL" selected>DELL</option>
</select>
</body>
</html>

www.kaniyam.com
155

16.8 HTML Password Object



password object . character - *
. , PIN
.

<html>
<head>
<title>Passwor Object</title>
</head>
<body>
Username:<input type="text" size="15"><br>
Password:<input type="password" size="20"><br>
<input type="submit" value="Login">
</body>
</html>

www.kaniyam.com
156

17 PHP and HTML Forms


, HTML
,
PHP Script .
Overview of HTML Forms
.

17.1 (Creating the Form)



.


. ,
, , , , ,
. HTML
.

<html>
<head>
<title>Contact Form</title>

<style>
#contactform {
background-color: lightblue;
width: 400px;
margin: auto;
border: 1px solid blue;
padding: 5px;
font-size: 20px;
}
</style>

</head>

<body>
<div id="contactform">
<b>Contact Form</b>
<form method="post" action="contactdetails.php">

www.kaniyam.com
157

Your Name : <input type="text" name="username" placeholder="Your


Name">
Father Name : <input type="text" name="fathername"
placeholder="Father Name">
Age : <input type="text" name="age" placeholder="Age">
Sex : <input type="radio" name="sex" value="Male"
checked>Male<input type="radio" name="sex" value="Female">Female
Mobile Number : <input type="text" name="mobilenumber"
placeholder="Your Mobile Number">
Address :
<textarea name="address" rows="5" cols="20" placeholder="Address
here..."></textarea>
<input type="submit">
</form>
</div>
</body>
</html>

www.kaniyam.com
158

17.2 PHP Process


(Processing Form Data Using PHP)
.
PHP . HTML Form -
(server) Mechanisms .
GET POST. ,
POST method .

PHP associative array


. array process .
HTML form method attribute POST
PHP $_POST associative array , GET PHP
$_GET associative array .

HTML process contactdetails.php


script $_POST .

Submit Button ,
contactdetails.php script .

contactdetails.php

<?php
$userName = $_POST["username"];
$fatherName = $_POST["fathername"];
$age = $_POST["age"];
$sex = $_POST["sex"];
$mobileNumber = $_POST["mobilenumber"];
$address = $_POST["address"];
echo "<b>Your Data is Successfully Received. Thanks.</b>";
//echo "$userName, $fatherName, $age, $sex, $mobileNumber,
$address";
print_r($_POST);
?>

www.kaniyam.com
159

contactdetails.php script
.

<?php
$userName = $_POST["username"];
$fatherName = $_POST["fathername"];
$age = $_POST["age"];
$sex = $_POST["sex"];
$mobileNumber = $_POST["mobilenumber"];
$address = $_POST["address"];
echo "<b>Your Data is Successfully Received. Thanks.</b>";
echo "Your Name is <i>$userName</i>";
echo "Your Father Name is <i>$fatherName</i>";
echo "You are <i>$age</i> years old.";
echo "You are <i>$sex</i>";
echo "Your Address is <i>$address</i>";
echo "<b>We will contact you soon...<b>";
?>

www.kaniyam.com
160

17.3 Processing Multiple Selections with PHP(


)
?
. Drop-down list .
.


.
,
. HTML Form , PHP Script
.

HTML Form

<select name=laptop[] size=2 multiple> name


[] .
multiple attribute .

Multiple Selections .

www.kaniyam.com
161

<html>
<head>
<title>Multiple Selections</title>
</head>
<body>
<form action="multipleselections.php" method="post">
<select name="laptop[]" size="2" multiple>
<option value="Acer">Acer</option>
<option value="Lenovo">Lenovao</option>
<option value="DELL">DELL</option>
<option value="HP">HP</option>
<option value="Samsung">Samsung</option>
<option value="Apple Mac">Apple Mac Book Pro</option>
</select>
<input type="submit">
</form>
</body>
</html>

PHP

<?php
print_r($_POST);
echo "";

echo $_POST["laptop"][0];
echo "";

echo $_POST["laptop"][1];
echo "";

echo $_POST["laptop"][2];
echo "";

www.kaniyam.com
162

echo $_POST["laptop"][4];
echo "";

echo $_POST["laptop"][5];
echo "";
?>

www.kaniyam.com
163

18 PHP and Cookies Creating, Reading and


Writing ( ,
)


,
.

.

.

, (web)
,
Cookies.

18.1
,
, Cookies
.
.
, ,

.

Cookies
. cookies
. cookies

www.kaniyam.com
164

.
cookies .

Cookies PHP
sessions . .
Cookies Sessions
. .

18.2 The Difference Between Cookies and Sessions (Cookies and


Sessions )
cookies sessions
.
.


(Hard Disk) Cookies .
Cookies .
Domain 20 . 4Kb
.

Sessions

Sessions (Web Server) .


Domain
sessions .
session .
.
.

18.3 (The Structure of Cookie)


name/value(/) cookies

www.kaniyam.com
165

. Name/value
. userName = Kathirvel
Rajendran .
expiration date
cookies .

name = Value; expires = expirationDateGMT; path=URLpath; domain=siteDomain

18.4 (Cookie Expiration


Setting)
expires=
. PHP time()
(function) .
.

18.5 (Cookie path Setting)


path= URL .
,
. , www.kaniyam/php/phpintamil.html
/php .

18.6 domain (Cookie domain Setting)


path setting
, .
. domain=domain name

.

, www.kaniyam.com ,
domain=www.gnutamil.blogspot.in

www.kaniyam.com
166

www.gnutamil.blogspot.in .

18.7 (Cookie Security Setting)


HTTPS(Hyper Text Transfer Protocol Secure)
HTTP
.

18.8 (Creating a Cookie in PHP)


setcookie() (funtion) .
arguments setcookie() function .
argument , argument .
argument . argument
active path, argument domain setting argument security
setting( 0 HTTP , 1 HTTPS .)

<?php
//Creating Cookies
echo "<b>Creating Cookies</b><br />";

setcookie('userName','Kathirvel Rajendran', time() + 15);


setcookie('emailid','<a class="autohyperlink"
href="mailto:linuxkathirvel.info@gmail.com"
title="mailto:linuxkathirvel.info@gmail.com">linuxkathirvel.info@g
mail.com</a>', time() + 15);

echo "<i>Cookies Created!</i><br />";


?>

www.kaniyam.com
167

userName=Kathirvel Rajendran .
15 .

18.9 (Reading a Cookie in PHP)


$_COOKIE array .
$_COOKIE array associative array . $_COOKIE array index
.

<?php
//Creating Cookies
echo "<b>Creating Cookies</b><br />";

setcookie('userName','Kathirvel Rajendran', time() + 15);

setcookie('emailid','<a class="autohyperlink"
href="mailto:linuxkathirvel.info@gmail.com"
title="mailto:linuxkathirvel.info@gmail.com">linuxkathirvel.info@g
mail.com</a>', time() + 15);

echo "<i>Cookies Created!</i><br />";

//Reading Cookies
echo "<b>Reading Cookies</b><br />";
echo "Username = ".$_COOKIE['userName']."<br />";
echo "E-Mail Address = ".$_COOKIE['emailid']."<br />";
?>

www.kaniyam.com
168

18.10 (Deleting a Cookie)


setcookie() (function) cookie . time()
function .
setcookie() function . setcookie()
function .
time() + seconds . time() seconds
. ( ) .

<?php

//Creating Cookies
echo "<b>Creating Cookies</b><br />";

setcookie('userName','Kathirvel Rajendran', time() + 15);


setcookie('emailid','<a class="autohyperlink"
href="mailto:linuxkathirvel.info@gmail.com"
title="mailto:linuxkathirvel.info@gmail.com">linuxkathirvel.info@g
mail.com</a>', time() + 15);

echo "<i>Cookies Created!</i><br />";

//Deleting Cookie
setcookie('userName', '' , time() - 15);
echo "UserName Cookie Deleted.<br />";

//Reading Cookies
echo "<b>Reading Cookies</b><br />";
echo "Username = ".$_COOKIE['userName']."<br />";
echo "E-Mail Address = ".$_COOKIE['emailid']."<br />";
?>

www.kaniyam.com
169

www.kaniyam.com
170

19 (Understanding PHP Sessions)


.
sessions . sessions
. sessions
sessions .

19.1 Session ?
PHP session (group) .
.
, (
) .
, . sessions ID
. ID
(server) session file .
session file content .
session . cookie support
session . cookie support
session ID .

19.2 PHP Session (Creation a PHP Session)


session_start() Function sessions .
session_start() function first function call .

<?php

//session creation
if(session_start())
{
echo "<h1>Session Started!</h1>";
}

www.kaniyam.com
171

else {
echo "<h1>Session Not Create!</h1>";
}
?>

19.3 Session (Creating and


Reading Session Variables)
$_SESSION array session variable
. $_SESSION Global Array .
session variable .
associative array . Array PHP Array
.

Session strings, numbers, arrays and objects


.

variable name assignment operator


$_SESSION array variable .

<?php

$_SESSION[userName] = Kathirvel Rajendran;

www.kaniyam.com
172

?>

<?php

//session creation
if(session_start())
{
echo "<h1>Session Started!</h1>";
$_SESSION['userName'] = 'Kathirvel Rajendran';
}

else {
echo "<h1>Session Not Create!</h1>";
}

//session accessing
if(isset($_SESSION['userName'])) {
echo "<b>User Name : </b><i>".$_SESSION['userName']."</i>";
}

else {
echo "Session Accessing Failed!";
}
?>

www.kaniyam.com
173

19.4 Session (Writing Session Data


to a File)
session session
. session
.

session
.

session session_encode() function


. file function
.

<?php

//session creation
if(session_start())
{
echo "<h1>Session Started!</h1>";
$_SESSION['userName'] = 'Kathirvel Rajendran';
$_SESSION['email'] = '<a class="autohyperlink"
href="mailto:linuxkathirvel.info@gmail.com"
title="mailto:linuxkathirvel.info@gmail.com">linuxkathirvel.info@g
mail.com</a>';
$_SESSION['blog'] = 'http://gnutamil.blogspot.in';
}

else {
echo "<h1>Session Not Create!</h1>";
}

//session data writer into the file


if(isset($_SESSION['userName']) && isset($_SESSION['email']) &&
isset($_SESSION['blog'])) {
//open a file for to save session datas
$fileopen = fopen('/tmp/sessiondatas.txt','w+');
//get the session datas
$session_data = session_encode();
//write the session datas into the file

www.kaniyam.com
174

if(fwrite($fileopen, $session_data)) {
echo "<i>Session Write Successfully!</i>";
}

//close the file


fclose($fileopen);
}

else {
echo "Session Accessing Failed!";
}
?>

www.kaniyam.com
175

19.5 session (Reading


Saved Session)
session_decode() function decode
.

<?php
$fileopen = fopen('/tmp/sessiondatas.txt','r');
//read the session datas
$session_data = fread($fileopen, 4096);
//close the file
fclose($fileopen);
session_decode($session_data);
print_r($session_data);
?>

www.kaniyam.com
176

20 (Object Oriented
Programming)
PHP .
.

. PHP -
OOP .
PHP ?
.

20.1 Object ?
Object .
.

Objects . Object
(functions) methods .
Object .
(members) .

20.2 Class ?
Class ,
.
? ?
Object Class
. methods , (members)
.

20.3 Class Object ?


object .
,

www.kaniyam.com
177

, Class Object .
Class , Object .
Class Object .

.

Object Class methods


. bankAccount class Object
.

$accountObject = new bankAcccount();

20.4 sub-classing ?
class class sub-class .
class variables methods
class . class
50% class ,
? 50% .

car class ,
vechile class
. sub-class. vechile
class Parent class , car class child class sub-class
.

20.5 PHP class


? Object
Class ? PHP class class
(keyword) . Class (body)
curly braces ({}) .

www.kaniyam.com
178

<?php

class bankAccount {

?>

class .
.

20.6 PHP class (class constructors


and destructors)
, Object
. Object . constructor
destructor method .

Constructor destructor (functions) function


. Function
public qualifier . public qualifier object
function .

constructor destructor __construct


__destruct . function - argument __construct and
__destruct .

<?php

class myProfile {

public function __construct($myName, $myAge) {


echo '<b style="color:green;">Object was just
instatiated</b><br>';
echo '<b>Name: </b>'.$myName.'<br>';

www.kaniyam.com
179

echo '<b>Age: </b>'.$myAge.'<br>';


echo '<hr>';
}

public function __destruct() {


echo '<b style="color:red;">Object was destroyed. Bye</b><br>';
}

$myProfileObject_one = new myProfile('KATHIRVEL RAJENDRAN', 26);

// Create another object

$myProfileObject_two = new myProfile('LINUX KATHIRVEL', 26);


?>

www.kaniyam.com
180

20.7 PHP class (members)


class - class members
. Members public private , static variable
.

public members object . private members


class . data encapsulation
.

Static member , .
Members (functions) class ,
public, private static
. Default public .

www.kaniyam.com
181

<?php
class LinuxProfile {
public $creator;
public $kernel;
public $icon;

// This variable is private.


private $os;

public function __construct($creator, $kernel, $icon, $os) {


$this->creator = $creator;
$this->kernel = $kernel;
$this->icon = $icon;
$this->os = $os;
echo $this->os;
echo '<br>';
}

// Create object for LinuxProfile class


$linux = new LinuxProfile('Linus', '3.13', 'Tux', 'Ubuntu 14.04.2
LTS');

// Access members using objects


echo 'Creator of GNU/Linux Kernel :'.$linux->creator;
echo '<br>';
echo 'Kernel version :'.$linux->kernel;
echo '<br>';
echo 'Icon of GNU/Linux :'.$linux->icon;

// This variable will not print due to private.


echo $linux->os;
?>

www.kaniyam.com
182

public .
class $creator, $kernel, $icon variable . Private
$os class - .

20.8 Methods (Defining and


Calling Methods)
constructor destructor method ,
methods .
methods . .

<?php

class User {
private $firstName;
private $lastName;

public function __construct($fname, $lname) {


$this->firstName = $fname;
$this->lastName = $lname;
echo '<h1>This name come from constructor function.</h1><br>';
echo $this->firstName.' '.$this->lastName;
echo '<br>';
}

public function __destruct() {


echo '<h1>destructor function</h1>';
echo 'Object was destroyed <br>';
}
public function setUserDetails($userName, $fatherName) {
$this->firstName = $userName;
$this->lastName = $fatherName;
}

public function getUserDetails() {


return $this->firstName.' '.$this->lastName;
}

www.kaniyam.com
183

// Create object to access methods


$user1 = new User('Kathirvel', 'Rajendran');
$user2 = new User('Linux', 'Kathirvel');
$user1->setUserDetails('Richard Matthew', 'Stallman');

echo '<h1>This name from getUserDetails function.</h1>';


echo $user1->getUserDetails();
?>

www.kaniyam.com
184

Object -> getUserDetails method .

20.9 Subclassing in PHP


class class subclass . class
, class .
Inheritence . Extends
subclass .

ParentClass name, email , childclass object


print . ParentClass variables ChildClass
. Methods .

<?php

class ParentClass {
public $name = 'Kathirvel';
public $email = '<a class="autohyperlink"
href="mailto:linuxkathirvel.info@gmail.com"
title="mailto:linuxkathirvel.info@gmail.com">linuxkathirvel.info@g
mail.com</a>';
}

class ChildClass extends ParentClass {


public $mobile = '9988776655';
}

$childclass = new ChildClass();

// print name, email using child class


echo $childclass->name;
echo '<br>';
echo $childclass->email;
echo '<br>';
echo $childclass->mobile;
?>

www.kaniyam.com
185

20.10 ChildClass ParentClass method


<?php

class ParentClass {
public $message1 = 'GNU/Linux is rule the world.<br>';

public function printMessage() {


echo $this->message1;
}

class ChildClass extends ParentClass {


public $message2 = 'I am ChildClass.<br>';
}

// Create ChildClass object


$child = new ChildClass();

// call printMessage method through ChildClass


$child->printMessage();
echo $child->message2;
?>

www.kaniyam.com
186

20.11 PHP Object Serialization


object serialize serialize() .
Unserialize unserialize() .

<?php

class UserProfile {
public $firstName;
public $lastName;
public $email;
public $mobile;

public function __construct($name, $fatherName, $email, $mob) {


$this->firstName = $name;
$this->lastName = $fatherName;
$this->email = $email;
$this->mobile = $mob;
}

// Create object
$profile = new UserProfile('Kathirvel', 'Rajendran', '<a
class="autohyperlink" href="mailto:linuxkathirvel.info@gmail.com"
title="mailto:linuxkathirvel.info@gmail.com">linuxkathirvel.info@g
mail.com</a>', '9988776655');

// Serialize using serialize() function


$ser = serialize($profile);

// print serialized values


echo $ser;

www.kaniyam.com
187

?>

20.12 PHP Object


get_declared_classes() Declare class array .

class_exists() Class , 1
. .

get_class_methods() methods .

get_parent_class() Parent class empty


string .

method_exists() method argument true


, false .

<?php

class ParentClass {
public $message1 = 'GNU/Linux is rule the world.<br>';

public function printMessage() {


echo $this->message1;
}

class ChildClass extends ParentClass {

www.kaniyam.com
188

public $message2 = 'I am ChildClass.<br>';


}

// Create ChildClass object


$child = new ChildClass();

// call printMessage method through ChildClass


$child->printMessage();
echo $child->message2;

// Get declared class names, It will print as Array.


echo '<br><hr>';
echo '<b>Declared Classes List<br></b>';
print_r(get_declared_classes());
// Find Class Exist or not
echo '<br><hr>';
echo '<b>Class Exist or not. (1=YES, otherwise=NO)</b><br>';
echo "ChildClass Exist:".class_exists('ChildClass').'<br>';
echo "ParentClass Exist:".class_exists('ParentClass').'<br>';
echo "KathirvelClass
Exist:".class_exists('KathirvelClass').'<br>';
?>

www.kaniyam.com
189

www.kaniyam.com
190

21 PHP (Using PHP with


MySQL)

, ,

(Database). ,
.
.

. ,

.

MySQL PHP . PHP


. MySQL
. . MySQL
.
PHP MySQL .

21.1 PHP MySQL (Connect with PHP to a


MySQL Server)
PHP MySQL mysql_connect() function
. mysql_connect function

. mysql_connect function arguments
. arguments .

argument (server) , default


localhost:3306 . argument
, argument (password).

mysql_close() function

www.kaniyam.com
191

.
argument .

PHP MySQL
?
, , (Database)
.
.

<?php

$dbhandle = mysql_connect('localhost','root', 'password');

//servername, username, password of user

if($dbhandle) {
echo "Connected to MySQL Database<br>";
echo "Successfully Connected!";
mysql_close($dbhandle);
}

else {
echo "Unable to connect to MySQL Database.<br>";
}

?>

www.kaniyam.com
192

21.2 MySQL PHP (Record)


(Selecting Records from a MySQL Database
Using PHP):
MySQL .
.
(Database) .
(Tables)
.
. mysql_select_db() function
. SQL Query mysql_query() function
argument .

mysql_query() function (results) array - .


array - mysql_fetch_array() funtion
.

<?php

$dbhandle = mysql_connect('localhost','root', 'password');


//servername, username, password of user

if($dbhandle) {
echo "Successfully Connected!<br />";
$db = mysql_select_db('phptest');
$query = 'SELECT * FROM customer';
$query_result = mysql_query($query, $dbhandle);

if(!$query_result) {
echo "Unable to perform query!<br />";
}

else {
while( $result_row = mysql_fetch_array($query_result,
MYSQL_ASSOC)) {
print_r($result_row);
echo "<br />";
}

www.kaniyam.com
193

}
}

mysql_close($dbhandle);
?>

21.3 Adding Records to MySQL


Database using PHP
.
mysql_query() function . SQL Query Insert Query
.

<?php

$dbhandle = mysql_connect('localhost','root', 'password');


//servername, username, password of user

if($dbhandle) {
echo "Successfully Connected!<br />";
$db = mysql_select_db('phptest');
$insert_query = "insert into customer(name, email, mobileno)
values( 'KATHIRVEL', '<a class="autohyperlink"
href="mailto:linuxkathirvel.info@gmail.com"
title="mailto:linuxkathirvel.info@gmail.com">linuxkathirvel.info@g
mail.com</a>', '9900990099')";
echo $query;
$select_query = "select * from customer";
$query_insert = mysql_query($insert_query, $dbhandle);
$query_select = mysql_query($select_query, $dbhandle);

www.kaniyam.com
194

if($query_insert) {
echo "Successfully Inserted!<br />";
}

else {
echo "Unable to perform inset query!<br />";
}

if(!$query_select) {
echo "Unable to perform query!<br />";
}

else {
while( $result_row = mysql_fetch_array($query_select,
MYSQL_ASSOC)) {
print_r($result_row);
echo "<br />";
}
}
}

mysql_close($dbhandle);
?>

21.4 Using PHP to get Information about a MySQL Database


MySQL PHP
functions . fields
mysql_list_fields() function .
, , mysql_connect() function -
arguments function .

www.kaniyam.com
195

fields mysql_num_fields()
funciton . function mysql_list_field() function
resource identifier argument .

mysql_list_fields() funtion resource identifier


field
mysql_field_name(), mysql_field_type(), mysql_field_len() function
.

<?php
$dbhandle = mysql_connect('localhost','root', 'password');
//servername, username, password of user

if($dbhandle) {
echo "Successfully Connected!<br />";
$db = mysql_select_db('phptest');
}

// Obtain the Database Information


$table_fields_list = mysql_list_fields('phptest', 'customer',
$dbhandle);
$table_no_of_fields = mysql_num_fields($table_fields_list);

for($i=0; $i<$table_no_of_fields; $i++) {


echo '<b>Field Name:</b> '. mysql_field_name($table_fields_list,
$i). " - ";
echo '<b>Field Type:</b> '. mysql_field_type($table_fields_list,
$i). " - ";
echo '<b>Field Length:</b> '. mysql_field_len($table_fields_list,
$i);
echo "<br />";
}

mysql_close($dbhandle);
?>

www.kaniyam.com
196

www.kaniyam.com
197

22 PHP SQLite (PHP and SQLite)


22.1 PHP SQLite Database (Creating an
SQLite Database with PHP)
SQLite MySQL Client, Server ,
. PHP
.

, .

22.2 PDO (PHP Data Objects) SQLite DB



SQLite Database , SQLite
Database PDO . PDO
sqlite:sqliteDBname.db argument . SQLite DB
Catch
.

<?php

try
{
$con = new PDO('sqlite:customer2.db');

if ($con) {
echo "Database Created";
}
}

catch (PDOException $e)


{
echo "DB Connections Failed!" . $e->getMessage();
}

www.kaniyam.com
198

$con = null;
?>

DB null PDO .

22.3 PHP SQLite Table (Using PHP


to Create Table to an SQLite Database)
PDO Table , Table query
exec function
. query execute Table
.

<?php

try
{
$con = new PDO('sqlite:customer2.db');

if ($con) {
echo "<p>Database Created</p>";
}

echo "<p>DB Connected Successfully!</p>";

// Table Creation
$create_table_query = "create table product(distribution
varchar(10), latest_version varchar(10))";

// Queries Execution
$create = $con->exec($create_table_query);

www.kaniyam.com
199

catch (PDOException $e)


{
echo "DB Connections Failed!" . $e->getMessage();
}

$con = null;
?>

22.4 Using PHP to Add Records to an SQLite Database


Table Records query
PDO Object exec() .

<?php

try
{
$con = new PDO('sqlite:customer2.db');

if ($con) {
echo "<p>Database Created</p>";
}

echo "<p>DB Connected Successfully!</p>";

// Table Creation
$create_table_query = "create table product(distribution
varchar(10), latest_version varchar(10))";

// Insert Data Into Table


$insert_data_query1 = "insert into product(distribution,
latest_version) values('Ubuntu', '14.10')";
$insert_data_query2 = "insert into product(distribution,
latest_version) values('Fedora', '21')";

// Queries Execution
$create = $con->exec($create_table_query);
$insert1 = $con->exec($insert_data_query1);
$insert2 = $con->exec($insert_data_query2);
}

www.kaniyam.com
200

catch (PDOException $e)


{
echo "DB Connections Failed!" . $e->getMessage();
}

$con = null;
?>

22.5 PHP Records (Using PHP to


Select Records from an SQLite Database)
Table Select . select
query , PDO
query() function . query() function
Associative Array . foreach loop
.

<?php

try
{
$con = new PDO('sqlite:customer2.db');
if ($con) {
echo "<p>Database Created</p>";
}
echo "<p>DB Connected Successfully!</p>";

// Table Creation
$create_table_query = "create table product(distribution
varchar(10), latest_version varchar(10))";

// Insert Data Into Table


$insert_data_query1 = "insert into product(distribution,
latest_version) values('Ubuntu', '14.10')";
$insert_data_query2 = "insert into product(distribution,
latest_version) values('Fedora', '21')";

www.kaniyam.com
201

// Select Query
$query = "select * from product";

// Queries Execution
$create = $con->exec($create_table_query);
$insert1 = $con->exec($insert_data_query1);
$insert2 = $con->exec($insert_data_query2);
$temp = $con->query($query);

foreach($temp as $details) {
echo $details['distribution']." - ".$details['latest_version'];
echo "<br />";
}
}
catch (PDOException $e)
{
echo "DB Connections Failed!" . $e->getMessage();
}

$con = null;
?>

www.kaniyam.com
202

www.kaniyam.com
203

23
PHP . PHP
Developer PHP
. HTML, CSS, JQUERY, JAVA SCRIPT, MY SQL
. jQuery, Java Script
HTML, CSS, MY SQL
. .
. Freshers
. WordPress
.

. .

www.phptpoint.com/

phppot.com/

www.w3resource.com/

www.w3programmers.com/

www.w3schools.com/php/default.asp

php.net/

HTML www.kaniyam.com/learn-html-in-tamil/
CSS www.kaniyam.com/learn-css-in-tamil-ebook/
MYSQL freetamilebooks.com/ebooks/learn-mysql-in-tamil/
www.kaniyam.com/learn-mysql-in-tamil-part2/

PHP ?
.

www.dollarfry.com/how-to-get-a-job-as-web-developer-by-learning-php/

www.kaniyam.com
204

www.kaniyam.com/how-to-get-a-computer-science-job/

www.kaniyam.com
205

24

Python Developer .
(Freedom Software) ,
.

.
.
, , , ,
. ,
.
.
.
,
. ?
.

?
. ?
.
, .
,
. ?
.
. . , ,

.

www.kaniyam.com
206

, . , ,
, , ,

.
.

. FOSS, GNU/Linux.
http://gnutamil.blogspot.in
.
.
(http://www.kaniyam.com/)
.
.

: linuxkathirvel.info@gmail.com

: http://gnutamil.blogspot.in/

www.kaniyam.com
207

25

, , .

, , .

editor@kaniyam.com
.

www.kaniyam.com
208

, .

,
.

, , , , ,
.

editor@kaniyam.com
.

, .

editor@kaniyam.com .

www.kaniyam.com
209


2013 .
http://creativecommons.org/licenses/by-sa/3.0/
.

,

, , , , ,
.

: . editor@kaniyam.com +91 98417 95468

www.kaniyam.com
210

26

Creative Commons ,

.

: KATHIRVEL R
: Karur Vysya Bank
: CHENNAI-MADIPAKKAM
: 1614155000037991
IFSC : KVBL0001614

www.kaniyam.com

You might also like