0% found this document useful (0 votes)
20 views45 pages

Unit 1

Uploaded by

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

Unit 1

Uploaded by

Wakanda Forever
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

UNIT 1

PHP
Outline
1. Introduction to PHP
2. Basics of PHP
3. Variables
4. Array
5. Function
6. Browser Control
7. Browser Detection
8. String Functions
9. Form Processing
10. File Handling
11. Cookie / Session
12. Object Oriented PHP
Introduction to PHP
 PHP is a scripting language that allows you to create dynamic Web pages
 You can embed PHP scripting within normal html coding
 PHP was designed primarily for the Web
 PHP includes a comprehensive set of database access functions
 High performance/ease of learning/low cost
 Open-source
 Anyone may view, modify and redistribute source code
 Supported freely by community
 Platform independent
Basics of PHP
 PHP files end with .php, you may see .php3 .phtml .php4 as well
 PHP code is contained within tags
<?php ?> or
Short-open: <? ?>
 HTML script tags: (This syntax is removed after PHP 7.0.0)
<script language="php"> </script>
 Comments
// for single line
/* */ for multiline
PHP Basic Example
7 <?php
8 $name = "Arjun Bala";
Scripting delimiters
// declaration
9 ?>
Declare variable $name
10
11 <html xmlns = "http://www.w3.org/1999/xhtml">
12 <head> Single-line comment
13 <title>Untitled document</title>
14 </head>
15
16 <body style = "font-size: 2em">
17 <p>
18 <strong>
19
20 <!-- print variable name’s value -->
21 Welcome to PHP, <?php print( "$name" ); ?>!
22 </strong>
23 </p> Function print outputs the value of
24 </body> variable $name
25 </html>
Variables
 All variables begin with $ and can contain letters, digits and underscore
(variable name can not begin with digit)
 PHP variables are Case-sensitive
 Don’t need to declare variables
 The value of a variable is the value of its most recent assignment
 Variables have no specific type other than the type of their current value
 Can have variable variables $$variable (not recommended)
Example : $a = “b”;
$b = “Arjun Bala”;
echo($$a);
Variables (Cont.)
 Variable names inside strings replaced by their value
Example : $name = “Arjun Bala”;
$str = “My name is $name”;
 Type conversions
 settype function
 Type casting
 Concatenation operator
 . (period)
Variable types
Data Type Description
int, integer Whole numbers (i.e., numbers without a decimal point).
float, double Real numbers (i.e., numbers containing a decimal point).
string Text enclosed in either single ('') or double ("") quotes.
bool, boolean True or false.
array Group of elements.
object Group of associated data and methods.
resource An external data source.
NULL No value.
Variables Scope
 Scope refers to where within a script or program a variable has meaning or a
value
 Mostly script variables are available to you anywhere within your script.
 Note that variables inside functions are local to that function and a function
cannot access script variables which are outside the function even if they are in
the same file.
 The modifiers global and static allow function variables to be accessed outside
the function or to hold their value between function calls respectively
Example (Variables)

5 <!-- Demonstration of PHP data types -->


6
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>PHP data types</title>
10 </head>
11
12 <body>
13
14 <?php Assign a string to variable
15 $testString
16 // declare a string, double and integer
17 $testString = "3.5 seconds";
18 $testDouble = 79.2;
Assign a double to variable
19 $testInteger = 12;
Assign an integer to variable
$testDouble
$testInteger
20 ?>
21
Example (Variables) (Cont.)
<!-- print each variable’s value -->
<?php print( $testString ); ?> is a string.<br />
<?php print( $testDouble ); ?> is a double.<br />
<?php print( $testInteger ); ?> is an integer.<br />

<br />
Print each variable’s value
Now, converting to other types:<br />
<?php

// call function settype to convert variable


// testString to different data types
print( "$testString" );
settype( $testString, "double" );
print( " as a double is $testString <br />" );
print( "$testString" );
settype( $testString, "integer" );
print( " as an integer is $testString <br />" );
settype( $testString, "string" );
Call function settype to
print( "Converting back to a string results in
$testString <br /><br />" ); convert settype
Call function the data to
type of
variable
convert $testString
the data type of to a
double.
variable $testString to an
Convert variable
integer.
$testString back to a string
Example (Variables) (Cont.)
44 $data = "98.6 degrees";
45 // use type casting to cast variables to a
46 // different type
47 print( "Now using type casting instead: <br />
48 As a string - " . (string) $data .
49 "<br />As a double - " . (double) $data .
50 "<br />As an integer - " . (integer) $data );
51 ?>
52 </body> Use type casting to cast variable
53 </html> $data to different types
PHP Arrays
 Array is a group of variable that can store multiple values under a single name.
 In PHP, there are three types of array.
 Numeric Array
These arrays can store numbers, strings and any object but their index will be represented
by numbers. By default array index starts from zero.
 Associative Array
The associative arrays are very similar to numeric arrays in term of functionality but they
are different in terms of their index. Associative array will have their index as string so that
you can establish a strong association between key and values.
 Multidimensional Array
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array
are accessed using multiple index.
PHP Arrays (Example)
7 <html xmlns = "http://www.w3.org/1999/xhtml">
8 <head>
9 <title>Array manipulation</title>
10 </head>
11
12 <body>
13 <?php Create the array $first by assigning a
14
value to an array element.
15 // create array first
16 print( "<strong>Creating the first array</strong>
17 <br />" );
18 $first[ 0 ] = "zero";
19 $first[ 1 ] = "one";
Assign a value to the array, omitting the
20 $first[ 2 ] = "two";
Use a for
index. Appends loop
a new to printtoout
element theeach
end element’s index and
21 $first[] = "three";
22
value. Function count returns the total number of
of the array.
23 // print elements
each element’s index in the array.
and value
24 for ( $i = 0; $i < count( $first ); $i++ )
25 print( "Element $i is $first[$i] <br />" );
PHP Arrays (Example) (Cont.)
27 print( "<br /><strong>Creating the second array
28 </strong><br />" ); Call function array to create an array that
29 contains the arguments passed to it. Store the
30 // call function array to create arraysecond
array in variable $second.
31 $second = array( "zero", "one", "two", "three" );
32 for ( $i = 0; $i < count( $second ); $i++ )
33 print( "Element $i is $second[$i] <br />" );
34
35 print( "<br /><strong>Creating the third array
36 </strong><br />" );
37
38 // assign values to non-numerical indices
39 $third[ "ArtTic" ] = 21;
Assign values to non-numerical
40 $third[ "LunaTic" ] = 18;
indices in array $third.
41 $third[ "GalAnt" ] = 23;
42
Function reset sets the internal pointer to
43 // iterate through theelements
the array first element of each
and print the array.
44 // element’s name and value
45 for ( reset( $third ); $element = key( $third );
46 next( $third ) )
47 Function key returns the index of the element
print( "$element is $third[$element] <br />" );
Function
which thenext moves
internal the internal
pointer pointer to the next
references.
element.
PHP Arrays (Example) (Cont.)
49 print( "<br /><strong>Creating the fourth array
50 </strong><br />" );
51
52 // call function array to create array fourth using
53 // string indices
54 $fourth = array(
55 "January" => "first", "February" => "second",
56 "March" => "third", "April" => "fourth",
57 "May" => "fifth", Operator
"June" =>=>is"sixth",
used in function array to assign
58 "July" => "seventh",each element
"August" => a string index. The value to the left
"eighth",
59 "September" => "ninth", of"October"
the operator is the array index, and the value to
=> "tenth",
60 "November" =>
the right is the element’s value.
"eleventh","December" => "twelfth"
61 );
62
63 // print each element’s name and value
64 foreach ( $fourth as $element => $value )
65 print( "$element is the $value month <br />" );
66 ?>
67 </body>
68 </html>
PHP Array Functions
 count($array) / sizeof($array)
Count all elements in an array, or something in an object
 array_shift($array)
Remove an item from the start of an array and shift all the numeric indexes
 array_pop($array)
Remove an item from the end of an array and return the value of that element
 array_unshift($array,”New Item”)
Adds item at the beginning of an array
 array_push($array,”New Item”)
Adds item at the end of an array
PHP Array Functions (Cont.)
 sort($array [, $sort_flags])
 Array can be sorted using this command, which will order them from the lowest to
highest
 If there is a set of string stored in the array they will be sorted alphabetically.
 The type of sort applied can be chosen with the second optional parameter
$sort_flags which can be
 SORT_REGULAR compare items normally (don’t change type)
 SORT_NUMERIC compare items numerically
 SORT_STRING compare items as string
 SORT_LOCALE_STRING compare items as string, based on the current locale
 rsort($array [, $sort_flags])
 It will sort array in reverse order (i.e. from highest to lowest)
PHP Array Functions (Cont.)
 shuffle($array)
It will mix items in an array randomly.
 array_merge($array1,$array2)
It will merge two arrays.
 array_slice($array,$offset,$length)
returns the sequence of elements from the array $array as specified by the $offset and
$length parameters.
PHP Functions
 A function is a piece of code which takes one more input in the form of
parameter and does some processing and returns a value.
 Creating PHP function
Begins with keyword function and then the space and then the name of the function
then parentheses”()” and then code block “{}”

<?php
function functionName()
{
//code to be executed;
}
?>

Note: function name can start with a letter or underscore "_", but not a number!
PHP Functions (Cont.)
 Where to put the function implementation?
In PHP a function could be defined before or after it is called.

<?php <?php
function functionName() functionName();
{
//code to be executed; function functionName()
} {
Here function call
//code to beisexecuted;
before
functionName(); implementation,
} which is also valid
?> ?>

Here function call is after


implementation, which is valid
Browser Control
 PHP can control various features of a browser.
 This is important as often there is a need to reload the same page or
redirecting the user to another page.
 Some of these features are accessed by controlling the information sent out in
the HTTP header to the browser, this uses the header() command such as :
header(“Location: index.php”);
 We can also control the caching using same header() command
header(“Cache-Control: no-cache”);
Or can specify the content type like,
header(“Content-Type: application/pdf”);
Browser Detection
 The range of devices with browsers is increasing so it is becoming more
important to know which browser and other details you are dealing with.
 The browser that the server is dealing can be identified using:
$browser_ID = $_SERVER[‘HTTP_USER_AGENT’];
 Typical response of the above code is follows:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/56.0.2924.87
 which specifies that user is using Chrome browser and windows 10 OS with
64 bit architecture
PHP String Functions
 Most of the time in PHP we suppose to do manipulation of strings, wheatear it
be input from the user, databases or files that have been written.
 String can be think as a array of characters, so it is possible to do something
like this,
$mystring = “Welcome to ITMBU(SLS)”;
print ($mystring[11]) ; // which will print ‘D’
 This uses an index as an offset from the beginning of the string starting at 0
 Often, there are specific things that need to be done to a string, such as
reversing, extracting part of it, finding a match to part or changing case etc..
PHP String Functions (Cont.)
String Function Purpose
strlen($string) Returns length of string.
strstr($str1,$str2) Finds str2 inside str1 (returns false if not
found or returns portion of string1 that
contains it)
strpos($str1,$str2) Finds str2 inside str1 and returns index.
str_replace($search,$replace,$str[,$count]) Looks for $search within $str and replaces
with #replace, returning the number of times
this is done in $count
substr($string,$startposition[,$endposition]) Returns string from either start position to
end or the section given by $startpos to
$endpos
trim($string) Trims away white space, including tabs,
rtrim($string) newlines and spaces, from both beginning
ltrim($string) and end of a string. ltrim is for the start of a
string only and rtrim for the end of a string
only
PHP String Functions (Cont.)
String Function Purpose
strip_tags($string,$tags) Strips out HTML tags within a string, leaving
only those within $tags intact
stripslashes($string) Strips out inserted backslashes
explode($delimiters,$string) It will breaks $string up into an array at the
points marked by the $delimiters
implode($array) Function returns combined string from an
array.
strtolower($string) Converts all characters in $string to
lowercase.
strtoupper($string) Converts all characters in $string to
uppercase.
ucword($string) Converts all the first letters in a string to
uppercase.
Form Processing
 We can access form data using there inbuilt PHP associative array.
 $_GET => in case we have used get method in the form
 $_POST => in case we have used post method in the form
 $_REQUEST => in both the cases

 For example,

html recive.php
<form action=“recive.php” <?php
method=“get”> $u = $_GET[‘UserName’];
<input type=“text” echo($u);
name=“UserName”> ?>
<input type=“submit”>
</form>
GET vs. POST

 Both GET and POST create an array (e.g. array( key1 => value1,
key2 => value2, key3 => value3, ...)). This array holds key/value
pairs, where keys are the names of the form controls and values
are the input data from the user.
 Both GET and POST are treated as $_GET and $_POST. These are
super global, which means that they are always accessible,
regardless of scope - and you can access them from any function,
class or file without having to do anything special.
 $_GET is an array of variables passed to the current script via the
URL parameters.
 $_POST is an array of variables passed to the current script via
the HTTP POST method.
When to use GET?
 Information sent from a form with the GET method is visible
to everyone (all variable names and values are displayed in
the URL).
 GET also has limits on the amount of information to send. The
limitation is about 2000 characters. However, because the
variables are displayed in the URL, it is possible to bookmark
the page. This can be useful in some cases.
 GET may be used for sending non-sensitive data.
 Note: GET should NEVER be used for sending passwords or
other sensitive information!
When to use POST?
 Information sent from a form with the POST method
is invisible to others (all names/values are embedded
within the body of the HTTP request) and has no
limits on the amount of information to send.
 Moreover POST supports advanced functionality such as
support for multi-part binary input while uploading files
to server.
 However, because the variables are not displayed in the
URL, it is not possible to bookmark the page.
 Developers prefer POST for sending form data.
File Handling in PHP
 PHP has several functions for creating, reading, uploading, and editing files.
 fopen($filename, $mode) will return the handle to access file.
 "r" (Read only. Starts at the beginning of the file)
 "r+" (Read/Write. Starts at the beginning of the file)
 "w" (Write only. Opens and clears the contents of file; or creates a new file if it
doesn't exist)
 "w+" (Read/Write. Opens and clears the contents of file; or creates a new file if it
doesn't exist)
 "a" (Write only. Opens and writes to the end of the file or creates a new file if it
doesn't exist)
 "a+" (Read/Write. Preserves file content by writing to the end of the file)
File Handling in PHP (Cont.)
Function Purpose
file_exists($file) Will return true if file is found, false
otherwise
filesize($file) Returns the size of the file in bytes.
fread($file,$bytesToRead) Will read $bytesToRead from $file handle
fwrite($file,$str) Will write $str in the $file handle
fclose($file) Will close the $file handle
copy($source,$destination) Will copy from $source to $destination
rename($oldname,$newname) Will rename the file to $newname
unlink($file) Will delete the file
File Handling Example

text.txt
Hello World From Darshan College

Read File
<?php
$file = fopen("text.txt","a+");
$text = fread($file,filesize("text.txt"));
echo($text);
?>
Write File
<?php
fwrite($file," New Content");
$text = fread($file,filesize("text.txt"));
echo($text);
?>
Cookies in PHP
 HTTP cookies are data which a server-side script sends to a web client to keep
for a period of time.
 On every subsequent HTTP request, the web client automatically sends the
cookies back to server (unless the cookie support is turned off).
 The cookies are embedded in the HTTP header (and therefore not visible to the
users).
 Shortcomings/disadvantages of using cookies to keep data
 User may turn off cookies support.
 Users using the same browser share the cookies.
 Limited number of cookies (20) per server/domain and limited size (4k bytes) per
cookie
 Client can temper with cookies
Cookies in PHP (Cont.)
 To set a cookie, call setcookie()
 e.g., setcookie('username', ‘AVB');
 To delete a cookie (use setcookie() without a value)
 e.g., setcookie('username');
 To retrieve a cookie, refer to $COOKIE
 e.g. $username = $_COOKIE['username‘];
 Note :
 Cookies can only be set before any output is sent.
 You cannot set and access a cookie in the same page. Cookies set in a page are
available only in the future requests.
Cookies in PHP (Cont.)
setcookie(name, value, expiration, path, domain, secure, httponly)
 Expiration
 Cookie expiration time in seconds
 0  The cookie is not to be stored persistently and will be deleted when the web client
closes.
 Negative value  Request the web client to delete the cookie
 e.g.: setcookie('username', 'Joe', time() + 1800); // Expire in 30 minutes
 Path
 Sets the path to which the cookie applies. (Default is ‘/’)
 Domain
 The domain that the cookie is available.
 Secure
 This can be set to 1 to specify that the cookie should only be sent by secure transmission
using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
Session in PHP
 Session is a way to make data accessible across the various pages of an entire
website is to use a PHP Session.
 A session creates a file in a temporary directory on the server where registered
session variables and their values are stored.
 The location of the temporary file is determined by a setting in the php.ini file
called session.save_path.
 When a session is started following things happen
 PHP first creates a unique identifier for that particular session which is a random
string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
 A cookie called PHPSESSID is automatically sent to the user's computer to store
unique session identification string.
 A file is automatically created on the server in the designated temporary directory
and bears the name of the unique identifier prefixed by sess_,
sess_3c7foj34c3jj973hjkop2fc937e3443.
Starting a PHP Session
 A PHP session is easily started by making a call to the session_start()
function.This function first checks if a session is already started and if none is
started then it starts one.
 <?php
It is recommended to put the call to session_start() at the beginning of the
page. session_start();
if( isset( $_SESSION['counter'] ) ) {
 The following example starts a session then register a variable called counter
$_SESSION['counter'] += 1;
that is incremented
}else { each time the page is visited during the session.
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= "in this session.";
?>
<html><head>
<title>Setting up a PHP session</title>
</head><body>
<?php echo ( $msg ); ?>
</body></html>
Destroying a PHP Session
 A PHP session can be destroyed by session_destroy() function.
 This function does not need any argument and a single call can destroy all the
session variables.

Logout.php
<?php
session_destroy();
?>
 If you want to destroy a single session variable then you can use unset()
function to unset a session variable.

Logout.php
<?php
unset(S_SESSION[‘counter’]);
?>
Object Oriented Concepts
 Classes, which are the "blueprints" for an object and are the actual code that
defines the properties and methods.
 Objects, which are running instances of a class and contain all the internal
data and state information needed for your application to function.
 Encapsulation, which is the capability of an object to protect access to its
internal data
 Inheritance, which is the ability to define a class of one kind as being a sub-
type of a different kind of class (much the same way a square is a kind of
rectangle).
 Polymorphism, which means that, depending on the circumstances, an object
will act diffrently.
Creating Class
 Let's start with a simple example. Save the following in a file called
MyClass.php:

MyClass.php
<?php
class Demo
{
// Code Here
}
?>
Adding Method
 The Demo class isn't particularly useful if it isn't able to do anything, so let's
look at how you can create a method.

MyClass.php
<?php
class Demo
{
function SayHello($name)
{
echo “Hello $name !”;
}
}
?>
Adding Properties
 Adding a property to your class is as easy as adding a method.
MyClass.php
<?php
class Demo{
public $name;
function SayHello($name){
echo “Hello $name !”;
}
}
?>
 There are three different levels of visibility that a member variable or method
can have :
 Public : members are accessible to any and all code (Default)
 Private : members are only accessible to the class itself
 Protected : members are available to the class itself, and to classes that inherit
from it
Constructor / Destructor
 Constructor is the method that will be implemented when object has been
initiated, Commonly, constructor is used to initialize the object
 Use function __construct (also referred as Magic Function) to create
constructor in PHP

MyClass.php
<?php
class Demo{
function __construct
{
}
function __destruct
{
}
}
?>
Inheritance
Human.php Student.php
<?php <?php
class Human{ class Student extends Human{
private $name = “a”; private $rollno = “001”;
public function getName() { public function getRoll() {
return $this->name; return $this->rollno;
} }
} }
?> ?>

Faculty.php My.php
<?php <?php
class Faculty extends Human{ $mystu = new Student();
private $staffInitial = “abc”; $mystu->getRoll();
public function getInitial() { $mystu->getName();
return $this->staffInitial; $myfac = new Faculty();
} $myfac->getName();
} $myfac->getInitial();
?> ?>

You might also like