web programming cookies, session and object oriented programming with php

59
WEB PROGRAMMING COOKIES, SESSION and Object Oriented Programming With PHP

Upload: peter-dixon

Post on 28-Dec-2015

242 views

Category:

Documents


3 download

TRANSCRIPT

WEB PROGRAMMING

COOKIES, SESSION and Object Oriented Programming With PHP

INTRODUCTION Cookies are a technology which can be

easily and simply used by a Webmaster to achieve a great many very useful tasks when creating websites.

Although cookies are well known to users, many people are not really sure what they are used for, and a large amount of webmasters don't realise the possibilities open to them when they use cookies.

Cookies can be set and used by a simple command in most scripting languages.

What Is A Cookie? Apart from being a type of biscuit, a cookie is also a

very useful piece of technology for use on the web. One of the problems which many websites need to

overcome is that there is no way of directly finding out who is on a website.

They basically give the website owner the opportunity to store a little piece of information on a user's computer which they can then retrieve at a later date.

Cookies are just tiny text files (only up to 4Kb in size) and a website can write them to the user's computer via the web browser.

What Use Is A Cookie?

So why would anyone want to store 4000 characters of text on a user's computer?

It isn't enough to put anything really worthwhile on there! The power of the cookie, though, is to recognise a site visitor over and over again.

Using Cookies A cookie is a very basic data file. It has a name and a value and also stores the

address of websites which are allowed to access it and an expiry time.

Basically, a website will set a cookie and give it a name and value.

This name is used by the website to refer to it, and no other website can access the cookie, even if they know it's name.

The name should be unique to the website, but it doesn't matter if it clashes with the name of a cookie from another website.

Using Cookies To retrieve data, the website simply has to

request if the user has a cookie with a particular name.

If the user does, the value is returned to the script and it can be dealt with however the website owner chooses (for example a name stored in a cookie could be returned, a user ID could be loaded from a database, or a record could be made of a user visiting a site).

Using Cookies

Every cookie is assigned an expiry date and time.

It is up to the website owner to decide how long the cookie should exist for.

Many owners may just choose to set the cookie for an hour, meaning it is only available for the user's single session.

This is common in visitor tracking.

Cookie Security Despite much worrying in the news a few

years ago, cookies pose no real danger to users.

Unless they are really worried about themselves being recognised by a website, they are harmless.

The browser actually writes and reads cookies from the computer when requested to by a website, so a malicious website cannot damage the computer.

Cookie Security For webmasters, there are some security

concerns. When the cookie is set, the domain(s)

which can access it are set. Usually this is just the website who set the

cookie. This makes them relatively secure, as you

can be sure that your competitor cannot load your cookie from one of your visitors' computers (they cannot even find out if it exisits).

Cookie Security One major security problem with cookies,

though, is that they can easily be read by anyone using the computer.

They are just a simple text file, so you should not under any circumstances store passwords in cookies.

A common way to log people in automatically is to store an encrypted version of their password, which can then be matched with an encrypted version on the server.

Cookie Security Another method is to store a unique

ID and a unique validation number on the user's system.

This is then referenced in a database to the user's account.

This way, no actual details are stored and a malicious user cannot simply guess users' IDs (as there is the validation number).

Setting a Basic Cookie The PHP function for setting cookies is

called:

setcookie()

It is a PHP function which can be used without returning a value (for example you can simply execute a setcookie()) command, or you can take the return value and use it.

Setting a Basic Cookie The setcookie() function returns a boolean

(true or false) value depending on whether it is successful. So you could execute:

if(setcookie()){echo "Cookie set";}else{echo "Cookie not set";}

Setting a Basic Cookie The most basic information for a cookie is

it's name and it's value. The name of the cookie must be something

which you can refer to it later as. You don't need to worry about it clashing

with other sites as cookie names are site specific but you should try and use a descriptive and unique name for your cookies.

Setting a Basic Cookie

For this first example, assume that you have used PHP to load the user's name into the variable $name and want to greet the user in the future by their name.

You would need to create a cookie which stores their name as follows:

setcookie("UsersName",$name);

Reading Cookie Values PHP makes it extremely simple to read the

value of a cookie. In PHP, reading form values are achieved using $_GET and $_POST. PHP has a similar global variable for cookies:

$_COOKIE['CookieName'];

This variable contains the value of the cookie with name 'CookieName'.

Reading Cookie Values

So on your website, if you wanted to display the name of the user, you could simply use the following:

echo "Hello, ".$_COOKIE['UsersName']."! Welcome back!";

Reading Cookie Values Of course, the user may not already have the cookie, so

you should use the PHP function isset. This returns true if a variable has been set and false if not. Using this, your site could do the following:

if(isset($_COOKIE['UsersName']){echo "Hello, ".$_COOKIE['UsersName']."! Welcome back!";}else{setcookie("UsersName",$name);}

Cookie Settings One of the most powerful features of cookies is the

ability to set and expiry date for the cookie. The cookie will remain on the users computer until the expiry date, then will automatically delete itself.

To set a cookie with an expiry date, use:

setcookie("UsersName", $name, time()+3600);

This code takes the current time (using time()) and then adds 3600 seconds to it, and uses this value to set as the expiry time for the cookie.

Cookie Settings

Basically this means that the cookie will remain on the user's computer for an hour (it expires 3600 seconds (1 hour) from the current time). For one week (for example) you would set the cookie as:

setcookie("UsersName", $name, time()+604800);

Cookie Settings There are three other options which can be

used when setting cookies. Firstly, the path

This refers to where in the domain you are able to access the cookie in future.

A second setting you can change is the domain. a cookie is only available in the domain you

set it in, Finally, a cookie has the option to be set as a

secure cookie. If this is turned on, the cookie will only ever

be surrendered to the site over a secure connection, not an insecure one.

Cookie Settings

The following code shows the imiplementation of a cookie with all settings specified:

setcookie("UsersName", $name, time()+3600, "/", ".mysite.com", 1);

Cookie Settings The cookie set here, is called 'UsersName'

and again stores the value $name. It will expire an hour from the current time.

It is available in all directories of the site (/ is the root directory).

It is available across any subdomain of the site mysite.com as '.mysite.com' has been given as the domain.

The final 1 means that this is a secure cookie, and can only be transmitted over a secure connection. This would be 0 for a standard (non-secure) cookie.

Deleting Cookies There are occasions on which you may wish

to delete a cookie from a user's computer. This could be if, for example, you want to

log the user out of a system (perhaps they are on a public computer).

Deleting a cookie is quite simple to do because all you have to do is to set the expiry time in the past.

By doing this, the cookie will be automatically deleted as soon as it is created, and will remove any data that already exists there.

Deleting Cookies

The simplest way is using:

setcookie("UsersName", "", time()-3600);

This sets the expiry time in the past so it should be deleted immediately.

There is also no information stored in the cookie.

Deleting Cookies There is a known problem with this, though. Although

it works in most cases, there can be problems if a user's timezone is set wrongly. The safest way to completely delete a cookie is to use the following:

setcookie("UsersName", "", mktime(12,0,0,1, 1, 1990));

The mktime() function is a PHP function for setting up a time specified. The time specified here is in the year 1990, so even a badly configured computer should still delete the cookie immediately.

WEB PROGRAMMING

Sessions

Introduction

Session is an alternative and effective solution to cookies in PHP which might actually be better for your website and security

A session is defined in PHP and throughout the Internet as a unique visit to a particular website and it's subsidiaries

Introduction

How can sessions in PHP help you out? Let's say you have a dynamic website

where you want to have a person sign in with a username and password.

Once he's in, you want him to be able to access all parts of your website using that name and password.

Introduction There are several ways to "remember" his

username and password while he's at your site.

One way is to use cookies. The advantage of using cookies is that once

he logs in, the cookie stores the visitors information on that computer for as long as the duration of the cookie, even if the session is over.

Introduction The obvious disadvantage of cookies

is that it's a security hazard. Also, some people have cookies

disabled so it may not be a viable solution.

PHP Sessions are a safer, always working method of storing variables in PHP throughout the duration of the visitors stay.

How to start a session?

The first thing you have to place in your php page is:

<? session_start(); header("Cache-control: private");

?>

How to start a session?

Explanation The session_start() and the header has

to be placed on the TOP (before any output) of every page you want these variables to follow along with the user

Once you have started the session, to add variables to the session, all you have to do is use the _session varible

How to start a session?

For example, if you want to have a username variable with a value of “Popo", you write:

<? $_SESSION["username"] = “Popo";?>

How to destroy/kill a session?

Now, just think of $_SESSION["username"] as any other variable like $username

You can do anything you want with it, and it'll follow around your website from one page to another

How to destroy/kill a session?

A session is ended whenever the visitor leaves your site, if you ever want to destroy/kill a variable inside the session, just use this command:

<? unset($_SESSION["variable"]); ?> and replace variable, with the name

of the variable you want to delete.

How to destroy/kill a session?

If you want to end the session all together while still keeping the visitor on your site, use:

<? session_destroy(); ?>

WEB PROGRAMMING

Object Oriented Programming With PHP

Introduction

What is object-oriented programming? Object-oriented programming consists of

three main vocabulary words: classes, methods, and objects

Introduction

First off, an object (also know as a class) is a very simple section of code that has a section of its own variables and functions.

An object is basically a data structure (also known as an abstract data type), which are encapsulated in a set of routines known as methods

Introduction In a simple way an object is kind of like a

program itself. Objects can be used for many different things

as they are very expandable What an object is capable of doing is entirely

up to the developer. A class can be used for things as simple as

creating a link and or to store data loaded from a file and or SQL query.

Introduction A class is a collection of methods and

objects. What's the purpose of classes in PHP?

It's the same reason as any other programming language: for large projects, classes provide superior organization and less repetitive code

A class can be used for things as simple as creating a link and or to store data loaded from a file and or SQL query.

Basic Syntax The basic syntax of an object is quite

simple. As you can see in the example bellow the syntax is much different from that of a function. class className {

<? code ?> }

In the above code we have created a simple object that is named "className".

Object Variables An Object can have variables declared

inside the object. While it is not necessary for an object to

have any variables it is most likely that they will.

Most, if not all, objects use variables to store information that can be accessed at any time by any function within ,and outside of, the object.

To create an object variable you must use the 'var' command when creating the variable.

Object Variables An example of variable declaration is listed

bellow.

class className { var $variable1; var $variable2; <? code ?> }

Accessing Object Variables

The method of accessing object variables is different depending on if you are accessing the variables from within or outside of the object.

Accessing Object Variables Accessing From Within The Object:

To access a variable from within an objects own function you must use the '$this' reference. An example of this would be:

$localvar = $this->variable1;

Notice how we didn't not use the '.' (period) operator but instead we used the '->' (reference/arrow) operator. This is because we are pointing to the variable within the object.

Accessing Object Variables Accessing From Outside of The Object: Accessing a variable from out side of an

object isn't that dissimilar from accessing one within the object.

Instead of using the '$this' reference you use the name of the object you wish to access. An example of this would be:

$localvar = $object->variable1;

Object Functions

Creating an object function is not that dissimilar from creating a normal function.

To create an object function all you have to do is create a function inside of the objects brackets as shown on next slide.

Object FunctionsClass className { var $variable1; var $variable2;

function classFunction($arg1, $arg2) { <? function code ?> } }

Object Functions In the previous code we have create a

function called classFunction. This function can not be called from out

side of object unless you use a pointer reference.

We will talk more about that later on. Also, a function can have any amount of

arguments that will. We have used two arguments above called

$arg1 and $arg2.

Object Constructors

Although not required it is good practice for each object to have a constructor.

A constructor is a function within the object that is called when the object is created.

A constructor is mostly used for setting default and or initiating values for the objects variables.

Object FunctionsClass className{ var $variable1; var $variable2; function className($arg1, $arg2="default value") { $this->variable1 = $arg1; $this->variable2 = $arg2; } function classFunction($arg1, $arg2) { <? function code ?> }}

Object Functions

As you can see above we have given $arg2 in the constructor function a default value.

This is what the value of $arg2 will be if the user does not pass any value to $arg2.

Using The Object Using an object is quite simple. First We must create the object. This is done by setting a variable using the new

command as shown bellow:

$object_var = new className("test");

Notice how we passed a value when creating the object. This is done because it is required by the object's

constructor function. If both of the object's constructor function's arguments

have a default value then this would not be required.

Using The Object

Using an objects functions is also quite simple.

To do this we will once again be using the '->' (reference/arrow) operator as shown bellow:

$object_var->classFunction("value1", "value2");

Using The Object

If the function returns a variable then you would use the function as follows:

$return_val = $object_var->classFunction("value1", "value2");

Conclusion Objects can be a great tool for any

developer but try not to over use them Based on experience, objects are best used

for storing multiple pieces of information and or for easy to use, automated, tasks such as creating html/xml style tags

Remember, objects to take up more memory then standard functions and variables so if you can accomplish the same task without using an object I recommend you do so