Developing Web Applications - PowerPoint PPT Presentation

1 / 27
About This Presentation
Title:

Developing Web Applications

Description:

9/14/09. 1. Developing Web ... HTML Forms are used to select different kinds of user input. ... session_decode -- Decodes session data from a string ... – PowerPoint PPT presentation

Number of Views:39
Avg rating:3.0/5.0
Slides: 28
Provided by: ralphm5
Category:

less

Transcript and Presenter's Notes

Title: Developing Web Applications


1
Developing Web Applications Lecture 7 More
PHP Dr. Ralph Moseley
2
  • Review
  • PHP Basics
  • Variables and arrays
  • Output
  • Sequence, repetition and selection

3
  • This week
  • Forms
  • Email
  • Functions
  • Cookies
  • Sessions

4
PHP for Forms
  • HTML Forms are used to select different kinds of
    user input.
  • Make your form using your favourite tool
  • Set the form action attribute to
  • ltform action"lt?php echo PHP_SELF ?gt"
    method"post"gt - or
  • ltform action"script.php" method"post"gt
  • Make sure that you name each form field that you
    want to process as these names will be available
    to the processing script as variables
  • ltinput type"text" name"inputtext"gt
  • inputtext will contain whatever is typed into
    the text field

5
PHP for Forms
  • When a form is submitted to a PHP script, any
    variables from that form will be automatically
    made available to the script by PHP. If the
    track_vars configuration option is turned on,
    then these variables will be located in the
    associative arrays HTTP_POST_VARS,
    HTTP_GET_VARS, and/or HTTP_POST_FILES,
    according to the source of the variable in
    question.
  • Example. Simple form variable
  • ltform
    action"foo.php" method"post"gt
  • Name ltinput
    type"text" name"username"gtltbrgt
  • ltinput
    type"submit"gt
  • lt/formgt
  • When the above form is submitted, the value from
    the text input will be available in
    HTTP_POST_VARS'username' this is an
    associative array.

6
Form Example
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtForm example 1lt/TITLEgt
  • lt/HEADgt
  • ltBODYgt
  • lt!-- File form1 --gt
  • ltFORM METHOD"POST" ACTIONscript1.php"gt
  • Enter a numeric value
  • ltBRgtltINPUT TYPE"TEXT" NAME"number"gt
  • lt/FORMgt
  • lt/BODYgt
  • lt/HTMLgt

7
Form Example Processing
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtForm 1 processinglt/TITLEgt
  • lt/HEADgt
  • ltBODYgt
  • lt! script1.php --gt
  • lt?php
  • number _POSTnumber
  • echo "The number entered was number."
  • if (number gt 10)
  • echo "ltBRgtThat's a big number."
  • ?gt
  • lt/BODYgt
  • lt/HTMLgt

8
PHP Predefined variables
  • PHP has a range of predefined variables available
    - for example Apache variables, environment
    variables and PHP-specific variables
  • PHP_SELF - the filename of the currently
    executing script
  • HTTP_POST_VARS - an associative array of
    variables passed to the current script via the
    HTTP POST method.
  • HTTP_GET_VARS - an associative array of
    variables passed to the current script via the
    HTTP GET method.
  • HTTP_ENV_VARS - an associative array of
    variables passed to the current script via the
    parent environment.
  • SERVER_NAME - the name of the server host under
    which the current script is executing.
  • DOCUMENT_ROOT - the document root directory
    under which the current script is executing, as
    defined in the server's configuration file.
  • HTTP_REFERER - the address of the page (if any)
    which referred the browser to the current page.
  • REMOTE_ADDR - IP address of the client
  • REMOTE_HOST - Host name of the client eg browser
  • Etc demo phpinfo()

9
  • Sending an email
  • recipient's email address
  • to EMAIL
  • subject of the message
  • re COURSE_TITLE." Submission"
  • message from the feedback form
  • comments "Hello student, your submission for
    ".COURSE_TITLE." course work has been
    successful\n\n"
  • msg comments."\n\nFile file_name\n
    Assignment ass\n Size file_size bytes\n Type
    file_type\n Receipt Code part_code\n\n!Remember
    to keep a copy of this work!\n"
  • set the From header
  • headers "From ".COURSE_EMAIL
  • send the email now...
  • mail(to,re,msg, headers)

10
Using Custom Functions
  • If you have some things that you do in a number
    of different scripts, you might consider putting
    them into custom functions. You could collect
    them into a file called functions.php and include
    them in all your scripts, or you could name them
    individually and include them only as needed.
    For example, you might want to make your own mail
    function which includes some default values. To
    make it flexible, you will want to pass it
    information (arguments) to use in different
    circumstances.

11
  • You could use the previous email example as a
    function and turn it into one with the header
  • my_mail("My sample subject", msg, email)
  • You could then include it in all your scripts as
  • require (functions.php)

12
Functions
  • Another example of a function
  • function compute_area(height, width)
  • return heightwidth
  • Function names are not case sensitive
  • Return statement terminates function
  • Exit() terminates script
  • If no return statement NULL is returned

13
Default Arguments
  • Eg. function gst(amount, rate0.12)
  • Return amountrate
  • May be called using to override rate
  • tax gst(purchase, 0.08)
  • Or to use default rate
  • tax gst(purchase)

14
Cookies and Sessions
  • Cookies are useful for storing user info that
    should be retained from one page to the next.
    (Overcome the stateless nature of the web)
  • Cookies are written to the clients hard drive.
  • Problems
  • User can disable cookies in the browser
  • Cookies may be viewed by other users
  • Can only store 20 cookies max 4KB.
  • Some browsers may display incorrectly unless all
    options are set in setcookie()

15
Creating a Cookie
  • setcookie(name,value,expiration)
  • E.g. setcookie(fruit,banana,time()3600) The
    cookies is called fruit and has a value of
    banana it will expire 1 hr from now.
  • E.g. setcookie(username,ralph,time()1800)
  • Cookie values are sent as part of the HTTP
    headers (transparent to user). No output should
    be sent to the browser (echo etc) until the
    cookie is set else cookie will not be set.

16
Accessing a Cookie
  • Once created,cookie values are automatically
    available to PHP scripts as a variable having the
    same name as the cookie.
  • Eg. echo the current user is username
  • PHP associative array HTTP_COOKIE_VARS contain
    the value of every current cookie
  • Foreach (HTTP_COOKIE_VARS as name gtvalue)
    echo ltBRgtname gt value

17
Deleting a Cookie
  • Automatically deleted after expiration time
  • Can manually delete by setting negative time
  • setcookie(username,,time()-3600)
  • Other cookie options
  • setcookie(name,value,expire,path,domain,secure)
  • pathwhich scripts have access to cookie values?.
    By default, any script in the current server
    directory downward have access. Parent directory
    doesnt.

18
Other Cookie Options
  • domain by default, a cookie is only available
    to scripts on the current web server. Specify a
    domain name for other servers. NOTE that some
    browsers need at least two dots in the domain
    name (Netscape).
  • secure how cookies are sent.
  • 1 https (secure connection)
  • 0 http (normal connection)
  • Eg.setcookie(username,ralph,time()3600,/webr
    oot,http//www.mdx.ac.uk,0)

19
Sessions
  • Alternative to cookies
  • Can use a special cookie to identify the session
  • Or pass the session id from one script to the
    next via the URL

20
Sessions - Session Variables
  • What if user disables cookies? Need to store data
    on the server. This is done in session variables.
  • A session variable is a regular global variable
    that, when registered as a session variable,
    keeps its value on all pages that use PHP4
    sessions. To register a session variable, assign
    a value to a variable that is to become a session
    variable and call
  • session_register("variable_name").
  • On all subsequent pages that uses sessions (by
    calling session_start()), the variable
    variable_name will have the value assigned to it
    before it was registered as a session variable.
    Changes to the variable value will be
    automatically registered in the session and saved
    for further reference

21
Session Functions
  • session_start -- Initialise session data
  • session_destroy -- Destroys all data registered
    to a session
  • session_name -- Get and/or set the current
    session name
  • session_module_name -- Get and/or set the current
    session module
  • session_save_path -- Get and/or set the current
    session save path
  • session_id -- Get and/or set the current session
    id
  • session_register -- Register one or more
    variables with the current session
  • session_unregister -- Unregister a variable from
    the current session
  • session_unset -- Free all session variables
  • session_is_registered -- Find out if a variable
    is registered in a session
  • session_get_cookie_params -- Get the session
    cookie parameters
  • session_set_cookie_params -- Set the session
    cookie parameters
  • session_decode -- Decodes session data from a
    string
  • session_encode -- Encodes the current session
    data as a string
  • session_set_save_handler -- Sets user-level
    session storage functions
  • session_cache_limiter -- Get and/or set the
    current cache limiter
  • session_cache_expire -- Return current cache
    expire
  • session_write_close -- Write session data and end
    session

22
count.php
  • lt?php
  • session_start()
  • session_register("count")
  • count
  • msg"You have visited the page count times in
    this session"
  • ?gt
  • lthtmlgtltheadgtlttitlegtCount visitslt/titlegtlt/headgt
  • ltbodygt
  • lt?php echo( msg ) ?gt
  • lt/bodygtlt/htmlgt

23
  • Using session variables for authentication in
    conjunction with a database . Create a login-page
    gives the user a userid and password form and
    posts to another PHP page (this example uses
    mysql)  
  • lt?php
  • session_start()
  • if (userid password)
  • res mysql_query("SELECT userid FROM users
    WHERE userid'userid' AND password'password'")
  • if(mysql_num_rows(res) ! 0)
  • verified_user userid
  • session_register("verified_user")
  • Header("Location your_main_page.php")
  • ?gt  
  • Now, on 'your_main_page.php', you call
    session_start() and then you can check the
    verified_user variable to see if the user has
    been authenticated (and who he is). Other uses
    for session variables, easing database load by
    caching certain values in the session rather than
    reading them from the database on each page
    access.

24
Destroying a Session
  • lt?php
  • // Initialize the session.
  • // If you are using session_name("something"),
  • // don't forget it now!
  • session_start()
  • // Unset all of the session variables.
  • session_unset()
  • // Finally, destroy the session.
  • session_destroy()
  • ?gt

25
Redirection
  • Once login data is captured/validated then want
    to go to a new page.
  • Header(Location URL)
  • header("Location http//ralph-moseley.co.uk/cmt3
    092/lab7.html")
  • General technique
  • Site start page login page
  • Login page validates user and set cookies
  • Redirect to new page
  • New page uses cookie data to access DB info

26
Today
  • Forms
  • Email
  • Functions
  • Cookies
  • Sessions

27
Next Week
  • Databases SQL
Write a Comment
User Comments (0)
About PowerShow.com