High Level Languages - PowerPoint PPT Presentation

1 / 42
About This Presentation
Title:

High Level Languages

Description:

In the first PHP lecture we considered the basics: The Danger of Computer Science ... BODY BGCOLOR= ?=$body_colour? TEXT= ?=$body_colour? reset_counter.php. 26 ... – PowerPoint PPT presentation

Number of Views:26
Avg rating:3.0/5.0
Slides: 43
Provided by: scie205
Category:

less

Transcript and Presenter's Notes

Title: High Level Languages


1
High Level Languages
  • Lecture 4
  • PHP

jog_at_cs.nott.ac.uk
2
Last lecture
  • Spy on your Users!
  • Environment Variables
  • Client Variables sent via Javascript
  • Cookies
  • Web Mail
  • Ripping other peoples Web Pages

3
Today Useful PHP
  • In the first PHP lecture we considered the
    basics
  • The Danger of Computer Science
  • Whats wrong with Cookies?
  • The Sessions solution
  • PHP MySQL
  • Starter MySQL
  • Connecting a database with PHP

4
1. The real danger of CS
Some worries about the amount of coursework. If
you are going to blame anyone
blame Bjarney creator of C
5
Larry Wall guy who wrote Perl
6
Conclusive Proof
Glasses
7
2. Sites that Remember
  • It is essential in good sites that we maintain
    state that we remember certain variables from
    page to page
  • Last Lecture we considered two ways of
    maintaining state of keeping variables common
    between scripts.
  • Adding variables to the url
  • Storing variables in cookies
  • Neither are satisfactory. So whats the answer?
  • Sessions!

8
Chaining Variables in URLs
  • You can chain variables on the end of a URL,
    starting with a question mark after the filee
    name and then using an ampersand.
  • myscript.php?variable1value1 variable2value2
    variable3value3variable3value3
  • This is a painful way of passing variables from
    script to script.
  • Messy and Cumbersome
  • Requires URL encoding
  • Error Prone
  • Too Public the user can see everything

9
Cookies
  • You may be thinking right now why learn sessions?
    I can do what I want with Cookies!
  • In his slides Chris - setting and playing around
    with cookies can be a fun. He lies. Hes like
    that.
  • Cookies are painful to use. While they can
    successfully store valuable information it is
    never easy and they are always one page call out
    of synch.

10
Problems with Cookies
  • Not only are cookies painful to code.
  • It may seem a suprisingly low statistic, but
    Cookies are about 30 unreliable on the web right
    now and it's getting worse.
  • More and more web browsers are starting to come
    with security and privacy settings and people
    browsing the net these days are starting to frown
    upon Cookies because they store information on
    their local computer that they do not want stored
    there.

11
The Session Solution
  • PHP has a great set of functions that can achieve
    the same results of Cookies and more without
    storing information on the user's computer.
  • PHP Sessions store the information on the web
    server in a location that you chose in special
    files.
  • These files are connected to the user's web
    browser via the server and a special ID called a
    "Session ID".
  • This is nearly 99 flawless in operation and it
    is virtually invisible to the user.

12
Session Start
  • The correct way to start a session is using the
    session_start() command.
  • We must include this statement at the start of
    every script of our site that we want to be able
    to use session variables in.
  • lt?
  • session_start() print We have started our
    session"
  • ?gt
  • This is essential and an easy thing to forget.

13
A common error
  • Just like Cookies you MUST call the
    session_start() function before anything is
    output to your web browser. This is absoultey
    important because you will get some ugly errors
    by PHP that will say something like this
  • lt?
  • echo This is incorrect and will cause an
    error" session_start()
  • ?gt
  • Generates the error
  • Warning Cannot send session cookie - headers
    already sent by (output started at
    session_header_error/session_error.php2) in
    session_header_error/session_error.php on line 3

14
Assigning Variables
  • lt? // start the session session_start()
    print Registering a session" // Get the
    user's input from the form for example
    data  _POSTdata' // Create a new
    Session variable session_register('name') //
    2 ways of putting data into the variable
    _SESSION'name'  data name data
  • ?gt
  • Welcome to my website lt? print name ?gtltBRgt
  • This is an example of receiving a data variable
    from an HTML form and putting it in the session.

15
Superglobals
  • Keep in mind that PHP has a switch in its setup
    which creates variable names for data sent to a
    script.
  • Often this register_globals setting may be turned
    OFF for security. This happens to be the same
    setting as the default PHP installation after PHP
    version 4.1 series.
  • _POSTdata and _Sessionname are
    superglobals
  • You have to use them if register_globals is OFF.

16
Sessions on Multiple Pages
  • The first thing you MUST do on each page you want
    to access a session variable is to start the
    session.
  • That may not sound right to you because "We
    already started the session on the last page."
  • That's true, but we need to keep the "connection"
    going between our session because they do not
    have persistent connections like MySQL does.

17
A Multiple Page Session
  • lt? // start the session session_start()
  • print In this script we use session variables
  • print that we created in the previous
    scriptltbrgt
  • // display the session variable
  • print Hi there name everything is
    working!ltbrgt
  • // of if register_globals is not active
  • print We can use the superglobal
    _SESSION'name'
  • ?gt

18
Unregistering Session Variables
  • PHP is really well designed.
  • With PHP Sessions, we have the ability to simply
    remove a single session variable without dumping
    our entire session and rebuilding it. The
    function is called session_unregister()
  • Here's how we unregister a single session
    variables and leave the rest intact.
  •   session_unregister('name')

19
Destroying a Whole Session
  • Why might it be necessary to destroy a session
    when the session will get destroyed when the user
    closes their browser?
  • Well, Imagine that you had a session you were
    using to determine if the user was logged into
    your site based upon a username and password -
    anytime you have a login feature, to make the
    users feel better, you should have a logout
    feature as well.
  • That's where session_destroy() may be useful it
    will delets the session files and clears any
    trace of that session.

20
Practical Sessions Hit Counter
  • What we're about to do here is
  • start your session
  • register a variable called "count
  • assign a value of 1 to it on the first page.
  • Then, we're going to increment the counter as we
    go through the website.
  • Were also going to provide a reset page

21
Hit Counter counter page
hit_counter.php
  • lt? session_start() if (!PHPSESSID)
    session_register('count') if(_SESSION'count' 
     0) _SESSION'count'  1 else 
       _SESSION'count'
  • ?gt
  • Youve visited lt?_SESSION'count'?gt pages so
    far!ltbrgt
  • lta hrefhit_counter.php"gtIncrement Your
    Counter!lt/agtltbrgt
  • lta hrefreset.php"gtReset Your Counter!lt/agtltbrgt

22
Hit Counter Reset Page
reset_counter.php
lt? session_start() session_register('count')
_SESSION'count'  1 ?gt Youve
visited lt?_SESSION'count'?gt pages so far!ltbrgt
lta hrefhit_counter.php"gtIncrement Your
Counter!lt/agtltbrgt lta hrefreset_counter.php"gtReset
Your Counter!lt/agtltbrgt
  • Pretty easy!?

23
Viewing All Session Variables
  • You can view every single session variable you
    have stored and what its value is by using the
    following code
  • lt?   session_start() print "Sessions ltBRgt"
    print_r(_SESSION)
  • ?gt
  • This script is pretty straight forward and gives
    all the info about what's in your session's scope.

24
Viewing Your Session ID
  • Every Session has a unique Session ID. A session
    ID looks like someone has had a typing fit and
    collapsed on the keyboard.
  • There's a function in PHP called session_id()
    that allows you to display the current session ID
    or utilize it however you need.
  • lt? session_start() echo "Your session ID is
    ltBgt". session_id() ."lt/Bgt"
  • ?gt
  • This will simply display something like
  • Your session ID is Bd315d2ed59dfa1c2d0fb0b0339c758
    d

25
Practical Sessions User Prefs
reset_counter.php
  • lt?
  • session_start()
  • if (!PHPSESSID)
  • session_register('body_color')
    session_register('text_color')
  • else if ((!body_color) (!text_color))
  • body_colour 000000
  • text_colour FFFFFF
  • ?gt
  • ltHTMLgt
  • ltBODY BGCOLORlt?body_colour?gt
    TEXTlt?body_colour?gtgt

26
Practical Sessions User Prefs
  • There's a reason for the if statements
  • If we just used this at the top of the page
  • lt?
  • session_start()
  • session_register('body_color')
  • session_register('text_color')
  • ?gt
  • then each time the page is loaded, the value of
    body_color and text_color would be overwritten
    by an empty string or a newly registered, empty
    variable.

27
IE6 Session Problem
  • When you click your back button to make changes
    in the form, you have to click the REFRESH button
    on that page to get the information that you
    posted back into the form.
  • This only works about 50 of the time. The other
    50 the users information is lost
  • This can be horrific for users but there is a
    simple solution. Enter this right below the
    session_start() of each script
  • header("Cache-control private")

28
Discussion of Prefs
  • Now this is all great at the moment but we do
    have a problem a session automatically closes
    when a user shuts his web browser.
  • If that person has spent hours setting all their
    user preferences and they disappear when the
    browser is closed you arent going to get many
    repeat users.
  • So while sessions maintain state over a visit we
    need someway of storing data between visits.

29
PHP MySQL
  • Open source has brought a lot more than Linux to
    the computing world. It has also given us PHP and
    MySQL.
  • PHP and MySQL are viewed by many as the world's
    best combination for creating data-driven sites.
  • MySQL databases are ideal for storing that data
    we have collected about a user or for holding
    user preferences between visits. It is free and
    it is easy.

30
MySQL
  • MySQL central is http//www.mysql.com/.
  • Were not going to go through installation of
    mysql. PHPDEV4 is the way to go if you want to
    setup at home
  • http//www.firepages.com.au/phpdev4.htm
  • However the university offers mysql accounts
    this is what well be using and instruction will
    be in Mondays next labs tutorial sheets.

31
A Web Application
  • The diagram below shows the relationship between
    your user, the scripting language and the DB.

Web Application
PHP
Database
32
The Query
  • The Query is the basic method by which data is
    entered or extracted from a database.
  • It is common to all database systems.
  • It is simply a command to the MySQL database in
    order to tell it to do something.

33
SQL Commands
  • SQL is a reasonably powerful query language.
  • However it is incredibly simple. You can learn it
    in a night.
  • The fundamental SQL commands are
  • CREATE
  • SELECT
  • INSERT
  • DELETE
  • UPDATE

34
Creating a Table
  • CREATE TABLE people (
  • first varchar(30),
  • last varchar(30),
  • address varchar(255)
  • )
  • INSERT INTO people VALUES
  • (Adolf',Hitler',Hell')
  • INSERT INTO people VALUES
  • (Saddam', Hussein,Beeston')
  • INSERT INTO people VALUES (Pete,roberts',Curre
    ntly Homeless')

35
First MySql/PHP Program
  • lt?
  • db mysql_connect("localhost", "root")
    mysql_select_db("mydb",db)
  • result mysql_query("SELECT FROM
    employees")
  • firstname mysql_result(result,0,"first")
  • lastname mysql_result(result,0,last")
  • address mysql_result(result,0,address")
  • ?gt
  • Hello lt?firstname?gt lt?lastname?gt ltBRgt
  • Your address is lt?address?gt

36
mysql_connect()
  • mysql_connect() establishes a connection to a
    MySQL server.
  • It takes 3 parameters.
  • The address of the server
  • Your Username for that db account
  • Your password
  • conn mysql_connect(address", user,
    pass)
  • The university mysql server is found at the
    following address
  • mysql.cs.nott.ac.uk

37
mysql_select_db()
  • In our code mysql_select_db() then tells PHP that
    any queries we make are against the mydb
    database.
  • mysql_select_db(dbname",conn)
  • We could create multiple connections to
    databases on different servers. But for now,
    youll only need one database.

38
mysql_query()
  • Next, mysql_query() does all the hard work.
  • Using the database connection identifier, it
    sends a line of SQL to the MySQL server to be
    processed.
  • This is the key command for interacting with the
    database.
  • In our example the results that are returned are
    stored in the variable result.

39
mysql_result()
  • Finally, mysql_result() is used to display the
    values of fields from our query
  • mysql_result(result,0,"first")
  • Using result, we go to the first row, which is
    numbered 0, and return the value of the specified
    fields.

40
Its as easy as that
  • So there we have it.
  • We have successfully executed a simple PHP script
    to retrieve some information.
  • In the next (and final) lecture we will be
    extending this to produce some more powerful PHP
    scripts.
  • These will really help with the coursework

41
Coursework 3 The time has come
  • Coursework 3 will soon be available.
  • The coursework is to create your very own simple
    but functional Web Forum. It will involve
  • Basic Sessions
  • Very Simple database Backend
  • It will follow on from the lab sheet
  • Good design will be essential. Any code without
    functions or require statements will get very low
    marks.

42
Special Labs Next Week
  • Because I am a kind kind soul of this there can
    be no argument - special labs are being arranged
    for next week.
  • Tuesday 9am labs are over
  • Next week there will be 3 labs. Monday, Tuesday
    and Thursday afternoons. I will give you the
    exact times next lecture.
  • Now please go home.
Write a Comment
User Comments (0)
About PowerShow.com