LIS651 lecture 3 taming PHP - PowerPoint PPT Presentation

1 / 40
About This Presentation
Title:

LIS651 lecture 3 taming PHP

Description:

It shows the impressive array of functions within PHP. But one of the strengths of PHP is that you can create your own functions as you ... – PowerPoint PPT presentation

Number of Views:104
Avg rating:3.0/5.0
Slides: 41
Provided by: wota
Category:
Tags: php | lecture | lis651 | php | taming

less

Transcript and Presenter's Notes

Title: LIS651 lecture 3 taming PHP


1
LIS651 lecture 3taming PHP
  • Thomas Krichel
  • 2005-11-12

2
functions
  • The PHP function reference is available on its
    web site http//www.php.net/quickref.php. It
    shows the impressive array of functions within
    PHP.
  • But one of the strengths of PHP is that you can
    create your own functions as you please.
  • If you recreate one of the built-in functions,
    your own function will have no effect.

3
example
  • Stephanie Rubino was an English teacher and
    objects to sentences like
  • You have ordered 1 bottles of Grosswald Pils.
  • Let us define a function rubino_print(). It will
    take three arguments
  • a number to check for plural or singular
  • a word for the singular
  • a word for the plural

4
function and parameters
  • use the keyword "function" and declare your
    parameters, as in
  • function rubino_print (number,
    singular,plural)
  • if(number 1)
  • print "one singular"
  • else
  • print "number plural"

5
default arguments
  • Sometimes you want to allow a function to be
    called without giving all its arguments. You can
    do this by declaring a default value. For the
    previous example
  • function thomas_need(thing'beer')
  • print "I need thing\n"
  • thomas_need() // prints I need beer
  • thomas_need('sex') // prints I need sex

6
rubino_print using common plurals
  • function rubino_print (num, sing,plur1)
  • if(num 1)
  • print "one sing"
  • elseif(plur 1)
  • print "num sing"."s"
  • else
  • print "num plur"

7
return value
  • Up until now we have just looked at the effect of
    a function.
  • return is a special command that return a value.
  • When return is used, the function is left.

8
rubino_print with return
  • function rubino_print (number,
    singular,plural)
  • if(number 1)
  • return "one singular"
  • return "number plural"
  • orderrubino_print(2,"beer","beers")
  • print "you ordered order\n"
  • // prints you ordered 2 beers.

9
utility function from php.net
  • function mysql_fetch_all(query)
  • r_at_mysql_query(query)
  • if(errmysql_error()) return err
  • if(mysql_num_rows(r))
  • while(rowmysql_fetch_array(r))
    resultrow
  • return result
  • if(is_array(rowsmysql_fetch_all(query))
  • // do something
  • else if (! is_null(rows))
  • die("Query failed!")

10
visibility of variables
  • variables used inside a function are not visible
    from the outside. Example
  • beer"Karlsberg"
  • function yankeefy (name'Sam Adams')
  • beername
  • yankeefy()
  • print beer // prints Karlsberg
  • the variable inside the function is something
    different than the variables outside.

11
accessing global variables.
  • There are two ways to change a global variable,
    i.e. one that is defined in the main script.
  • One is just to call it as GLOBAL'name' where
    name is the name of the global variable.
  • function yankeefy (name"Sam Adams")
  • GLOBAL'beer'"name"

12
brewer_quiz.php introduction
  • lt?php
  • brewersarray('Großwald Brauerei','Homburger
    Brauhaus', 'Karlsberg Brauerei','Ponter
    Hausbrauerei', 'Saarfürst Merziger
    Brauhaus','Mettlacher Abtei-Bräu','Körpricher
    Landbräu','Brauerei G.A. Bruch','Neufang
    Brauerei','Zum Stiefel')
  • form_top"ltform action\"_SERVERPHP_SELF\"
    method\"get\"gtltpgt\n"
  • form_submit'ltinput type"submit" value"I
    try!"/gt'."\n"
  • form_end'ltinput type"hidden" name"submitted"
    value"1"/gtlt/pgtlt/formgt'

13
brewer_quiz.php form building
  • function build_form(answer,comment)
  • print "ltdivgtTake the Saarland brewery
    challengelt/divgt\n"
  • print GLOBALS'form_top'
  • print "ltinput type\"text\" name\"guess\"
    value\"answer\"/gt"
  • print GLOBALS'form_submit' print
    GLOBALS'submit_check'
  • print GLOBALS'form_end' print comment

14
brewer_quiz.php form processing
  • function process_form(answer,brewers)
  • ranswer
  • foreach(brewers as brew)
  • if(answer "brew")
  • r'ltdivgtCongradulation! This is
    correct!lt/divgt'
  • return r
  • r'ltdivgtThis is a bad answer, try
    again!lt/divgt' return r

15
brewer_quiz.php main part
  • if(_GET'submitted')
  • from_formprocess_form(_GET'guess',brewers)
  • build_form(from_form0,from_form1)
  • ?gt

16
working with many source files
  • Many times it is useful to split a PHP script
    into several files.
  • PHP has two mechanisms.
  • require(file) requires the to be included. If the
    file is not there, PHP exits with an error.
  • include(file) includes the file.

17
require() and include()
  • Both assume that you leave PHP. Thus within your
    included file you can write simple HTML.
  • If you want to include PHP in your included file,
    you have to surround it by lt?php and ?gt, just
    like in a PHP script.
  • Here is an example to use include to build the
    basic web page.

18
top.html
  • lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Strict//EN"
  • "http//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd
    "gt
  • lthtmlgt
  • ltheadgtlttitlegttitlelt/titlegt
  • ltmeta http-equiv"content-type"
    content"text/html charsetUTF-8"/gt
  • ltlink rel"stylesheet" type"text/css"
    href"main.css"/gt
  • lt/headgt
  • ltbodygt

19
bottom.html
  • ltp id"validator"gt
  • lta href"http//validator.w3.org/check?urireferer
    "gtltimg
  • style"border 0pt"
  • src"http//wotan.liu.edu/valid-xhtml10.png"
  • alt"Valid XHTML 1.0!" height"31" width"88"
    /gtlt/agt
  • lt/pgt
  • lt/bodygt
  • lt/htmlgt

20
validated.php
  • lt?php
  • title"my basic page\n"
  • include("top.html")
  • print "ltdivgthello, worldlt/divgt"
  • include("bottom.html")
  • ?gt

21
trouble
  • title in the top.html is not understood as the
    title. It reads as title, which means "idiot"
    for your web user.
  • Even if you replace title with
  • lt?php title ?gt
  • title is empty. The definition from the
    outer file is not seen in the included file.
  • So you have to split into three files, and print
    the title in the main file. I leave that to you
    to figure out.

22
login.php create_account.php
  • Both require a database that has three fields
  • id which is an auto_increment int acting as a
    handle
  • username is the username of the account. it must
    be unique and this is enforced by mySQL
  • password is a varchar(41) because the sha1 of the
    password is stored. This is 40 chars long.

23
login.php
  • function show_form(message)
  • print "ltdivgtlth1gtmessagelt/h1gtlth2gtLoginlt/h2gt
  • ltform action\"_SERVERPHP_SELF\"
    method\"post\"gt
  • ltdivgtltinput type\"hidden\"
    name\"submitted\" value\"1\" /gtlt/divgtltpgtUsername
    ltinput type\"text\"
  • name\"username\" maxlength\"15\"
    value\"_POSTusername\" /gtlt/pgtltpgtPassword
    ltinput type\"password\" name\"pass\"
    value\"_POSTpass\"/gtlt/pgtltpgtltinput
    type\"submit\" value\"Login\" /gt Not yet a
    member? lta href\"create_account.php\"gtCreate an
    accountlt/agt!
  • lt/pgtlt/formgtlt/divgt"

24
  • function process_form()
  • usernametrim(_POST'username')
  • passtrim(_POST'pass')
  • sha_passsha1(pass)
  • dbmysql_connect('localhost','krichel','laempel
    ')
  • query"SELECT FROM beer_shop.users WHERE
  • username'username' AND password
    'sha_pass'"
  • resultmysql_query(query)
  • errormysql_error()
  • if(error) return "Sorry query gives an
    errorltbr/gt
  • error"
  • affectedmysql_affected_rows()
  • if(! (affected)) return "Invalid username or
    password"

25
login.php (end)
  • if(_POST'submitted')
  • errorprocess_form()
  • if(error) show_form(error)
  • else
  • user_POST'username'
  • print "lth1gtWelcome to userlt/h1gt"
  • else show_form('')

26
create_account.php
  • function show_form(message)
  • print "ltdivgtlth1gtmessagelt/h1gtlth2gtCreate
  • Accountlt/h2gtltpgtPlease complete the form below to
    create
  • your account. lt/pgt ltform action\"_SERVERPHP_SE
    LF
  • \" method\"post\"gtltdivgtltinput type\"hidden\"
  • name\"submitted\" value\"1\" /gtlt/divgt It must
    be more
  • than 5 characters and cannot be your
    username.lt/pgtltpgt
  • ltinput type\"submit\" value\"Create Account\"
    /gt
  • lt/pgtlt/formgtlt/divgt"

27
create_account.php
  • lth3gtPasswordlt/h3gtltpgt Password ltinput
    type\"password\"
  • name\"pass1\" value\"_POSTpass1\"/gtConfirm
  • Password ltinput type\"password\" name\"pass2\"
  • value\"_POSTpass2\"/gt lt/pgtltpgtThe password you
    enter
  • will be used to access your account. It must be
    more than 5
  • characters and cannot be your username.lt/pgt
    ltpgtltinput
  • type\"submit\" value\"Create Account\"
  • /gtlt/pgtlt/formgtlt/divgt"

28
create_account.php
  • function process_form()
  • usernametrim(_POST'username')
  • pass1trim(_POST'pass1')
  • pass2trim(_POST'pass2')
  • if(strlen(username)lt6)
  • return "Username is too short."
  • if(! (pass1 pass2)) return "Passwords do
    not match."
  • passpass1
  • if(pass username)
  • return "Your username can not be your
    password."

29
create_account.php
  • if(strlen(pass)lt6) return "Password is too
    short."
  • sha_passsha1(pass)
  • dbmysql_connect('localhost','krichel','laempel
    ')
  • query"INSERT INTO beer_shop.users VALUES
    ('','username','sha_pass')"
  • resultmysql_query(query)
  • errormysql_error()
  • if(error "Duplicate entry 'username' for
    key 2") return "Sorry Username username is
    already taken, choose another."
  • else print "lth1gtThank you for registering with
    us!lt/h1gt"

1
30
create_account.php (end)
  • if(_POST'submitted')
  • errorprocess_form()
  • if(error)
  • show_form(error)
  • else
  • show_form('')

31
sessions
  • You will recall that HTTP is a stateless
    protocol. Each request/response is
    self-contained.
  • Statefulness is crucial in Web applications.
    Otherwise users have to authenticate every time
    they access a new page.
  • Traditionally, one way to create statefullness is
    to use cookies.
  • PHP uses cookies to create a concept of its own,
    sessions, that makes it all very easy.

32
cookies
  • A cookie is a piece of attribute/value data. A
    server can send cookies as value of a HTTP header
    Set-Cookie. Multiple headers may be sent.
  • When the client visits the web site again, it
    will send the cookie back to the server with a
    HTTP header Cookie

33
Set-Cookie
  • Set-Cookie namevalue expires date
    pathpath domain domain secure
  • where
  • name is the variable name set in the cookie
  • value is the variable's value
  • date is a date when the cookie expires
  • path restricts the cookie to be sent only when
    requests to a path starting with path are made
  • domain restricts the sending of the cookie to a
    certain domain
  • secure restricts transmission to https

34
Cookies
  • The browser compares the request it wants to make
    with the URL and the domain that sent the cookie.
  • If the path is not set the cookie will only be
    sent to a request with the originating URL.
  • If the cookie matches the request a request
    header of the form
  • Cookie name1value1 name2value2
  • is sent.

35
sessions
  • Sessions are a feature of PHP. PHP remembers a
    session through a special cookie PHPSESSID.
  • To activate the sessions, include
    session_start() at the beginning of your script,
    before any printing has been done.
  • One a session is active, you have a special
    super-global variable _SESSION. Session data is
    stored in special files on wotan.

36
_SESSION
  • This is an array where you can read and set
    variables that you want to keep during the
    session.
  • if(_SESSIONuser_name)
  • print "welcome _SESSIONuser_name"
  • else
  • // show users login form
  • print login_form()

37
ending sessions
  • At 9 and 39 past each hour, wotan deletes all
    session files that have not been changed for 24
    minutes or more.
  • If you want to remove a session yourself, you can
    call session_destroy() in your script.

38
visit.php
  • lt?php
  • top'lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML
    1.0 Strict//EN"
  • "http//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd
    "gt
  • lthtmlgtltheadgtlttitlegtlt/titlegtltmeta
    http-equiv"content-type"
  • content"text/html charsetUTF-8"/gt
  • lt/headgtltbodygtltdivgt'
  • bottom'lt/divgtltpgt
  • lta href"http//validator.w3.org/check?urireferer
    "gt
  • ltimg style"border 0pt" src"/valid-xhtml10.png"
  • alt"Valid XHTML 1.0!" height"31"
    width"88" /gt
  • lt/agtlt/pgtlt/bodygtlt/htmlgt'

39
visit.php
  • session_start()
  • currentmktime() // look at the current time
  • if(_SESSIONlast_click)
  • passedcurrent-_SESSIONlast_click
  • to_print."passed seconds have passed since
    your last visit.\n"
  • _SESSIONlast_clickcurrent
  • else
  • to_print"This is your first visit.\n"
  • _SESSIONlast_clickcurrent
  • print "top\nto_print\nbottom"
  • ?gt

40
http//openlib.org/home/krichel
  • Thank you for your attention!
  • Please switch off machines b4 leaving!
Write a Comment
User Comments (0)
About PowerShow.com