Unit 1
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)
<br />
Print each variable’s value
Now, converting to other types:<br />
<?php
<?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
?> ?>
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();
?> ?>