Developing Web Applications - PowerPoint PPT Presentation

1 / 38
About This Presentation
Title:

Developing Web Applications

Description:

Each time the same computer requests a page with a browser, it will send the cookie too. ... Create a login-page gives the user a userid and password form and posts to ... – PowerPoint PPT presentation

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

less

Transcript and Presenter's Notes

Title: Developing Web Applications


1
Lecture 8 More PHP
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
  • Any form element in an HTML page will
    automatically be available to your PHP scripts.
    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
Form Validation
  • User input should be validated whenever possible.
  • Client side validation is faster, and will reduce
    server load.
  • However, client side validation is not secure.
  • Should use server side validation if the form
    accesses a database.
  • Good server side form validation post the form
    to itself, not to a different page.
  • The user will then get the error messages on the
    same page as the form. This makes it easier to
    discover the error.

6
PHP for Forms
  • When a form is submitted to a PHP script, any
    elements from that form will be automatically
    made available to the PHP script as variables.
  • These variables will be located in the
    associative arrays HTTP_POST_VARS,
    HTTP_GET_VARS
  • 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.

7
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

8
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

9
The _GET Variable
  • The _GET variable is used to collect values from
    a form with method"get".
  • This variable is an associative array of variable
    names and values sent by the HTTP GET method.
  • Information sent from a form with the GET method
    is visible to everyone (it will be displayed in
    the browser's address bar) and it has limits on
    the amount of information to send (max. 100
    characters).
  • So this method should not be used when sending
    passwords or other sensitive information!
  • However, because the variables are displayed in
    the URL, it is possible to bookmark the page.
    This can be useful in some cases.

10
Example
  • ltform action"welcome.php" method"get"gt
  • Name ltinput type"text" name"name" /gt
  • Age ltinput type"text" name"age" /gt
  • ltinput type"submit" /gt
  • lt/formgt
  • When the user clicks the "Submit" button, the URL
    sent could look something like this
  • http//www.w3schools.com/welcome.php?namePeterag
    e37
  • The "welcome.php" file can now use the _GET
    variable to catch the form data
  • Welcome lt?php echo _GET"name" ?gt.ltbr /gt
  • You are lt?php echo _GET"age" ?gt years old!

11
The _REQUEST Variable
  • The PHP _REQUEST variable contains the contents
    of _GET, _POST, and _COOKIE.
  • The PHP _REQUEST variable can be used to get the
    result from form data sent with both the GET and
    POST methods.
  • Example
  • Welcome lt?php echo _REQUEST"name" ?gt.ltbr /gt
  • You are lt?php echo _REQUEST"age" ?gt years old!

12
The _POST Variable
  • The _POST variable is used to collect values
    from a form with method"post".
  • The _POST variable is an associative array of
    variable names and values sent by the HTTP POST
    method.
  • Information sent from a form with the POST method
    is invisible to others and has no limits on the
    amount of information to send.
  • However, because the variables are not displayed
    in the URL, it is not possible to bookmark the
    page.

13
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

14
Sending email by PHP
  • PHP allows you to send e-mails directly from a
    script.
  • The PHP mail() function is used to send emails
    from inside a script.
  • Syntax
  • mail(to,subject,message,headers,parameters)

15
  • 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)

16
PHP Mail Form
17
PHP cookies
  • A cookie is often used to identify a user.
  • A cookie is a small file that the server embeds
    on the user's computer.
  • Each time the same computer requests a page with
    a browser, it will send the cookie too.
  • With PHP, you can both create and retrieve cookie
    values.
  • Problems
  • User can disable cookies in the browser
  • Cookies may be viewed by other users
  • Can only store 20 cookies max 4KB.

18
How to Create a Cookie?
  • The setcookie() function is used to set or create
    a cookie.
  • Note The setcookie() function must appear BEFORE
    the lthtmlgt tag.
  • Syntax setcookie(name, value, expire, path,
    domain)
  • Example 1
  • lt?php setcookie("user", "Alex Porter",
    time()3600) ?gt
  • lthtmlgt .....
  • Example 2
  • lt?php expiretime()60602430
  • setcookie("user", "Alex Porter", expire) ?gt
  • lthtmlgt .....
  • Note The value of the cookie is automatically
    URLencoded when sending the cookie, and
    automatically decoded when received (to prevent
    URLencoding, use setrawcookie() instead).

19
How to Retrieve a Cookie Value?
  • The PHP _COOKIE variable is used to retrieve a
    cookie value.
  • Example
  • lt?php// Print a cookieecho _COOKIE"user"
  • // A way to view all cookies
  • print_r(_COOKIE)
  • ?gt

20
How to Retrieve a Cookie Value?
  • lthtmlgt ltbodygt
  • lt?php
  • if (isset(_COOKIE"user"))
  • echo "Welcome " . _COOKIE"user" . "!ltbr /gt"
  • else
  • echo "Welcome guest!ltbr /gt"
  • ?gt
  • lt/bodygt lt/htmlgt

21
Deleting a Cookie
  • Automatically deleted after expiration time
  • Can manually delete by setting negative time
  • setcookie(username,,time()-3600)

22
Sessions
  • Application and session When you are working
    with an application, you open it, do some changes
    and then you close it. This is much like a
    Session. The computer knows who you are. It knows
    when you start the application and when you end.
    But on the internet there is one problem the web
    server does not know who you are and what you do
    because the HTTP address doesn't maintain state.
  • A PHP session solves this problem by allowing you
    to store user information on the server for later
    use (i.e. username, shopping items, etc).
  • However, session information is temporary and
    will be deleted after the user has left the
    website. If you need a permanent storage you may
    want to store the data in a database.
  • Sessions work by creating a unique id (UID) for
    each visitor and store information about the
    visitor based on this UID. The UID is either
    stored in a cookie or is propagated via URL
    between different pages.

23
Sessions
  • UID and related information can be stored as
    cookies, but cookies can be disabled by a
    browser.
  • Need to store on the server, through the use of
    session variables.
  • A session variable is used to store information
    about a user session, and is available to all
    pages in one application.
  • Built-in SESSION associative array variable
  • User-defined must be registered.
  • Session variables can be deleted after use.

24
Start a PHP Session
  • Before you can store user information in your PHP
    session, you must first start up the session by
    the session_start() function.
  • This function must appear BEFORE lthtmlgt
  • lt?php session_start() ?gt
  • lthtmlgt ltbodygt lt/bodygt lt/htmlgt
  • The code above will register the user's session
    with the server, allow you to start saving user
    information, and assign a UID for that user's
    session.

25
Use Built-in Session Variable
  • lt?php session_start()
  • _SESSION'views'1 // store session data
  • ?gt
  • lthtmlgt ltbodygt
  • lt?php
  • echo "Pageviews". _SESSION'views'
    //retrieve session data
  • ?gt
  • lt/bodygt lt/htmlgt
  • Output
  • Pageviews1

26
An example page-views counter
  • The isset() function checks if the "views"
    variable has already been set. If "views" has
    been set, we can increment our counter. If
    "views" doesn't exist, we create a "views"
    variable, and set it to 1
  • lt?phpsession_start()
  • if(isset(_SESSION'views')) _SESSION'views'
    _SESSION'views'1else _SESSION'views'1
    echo "Views". _SESSION'views' ?gt

27
Register user-defined session variables
  • To register a session variable, call
  • session_register("variable_name").
  • On all subsequent pages that uses sessions (by
    calling session_start()), the variable
    variable_name will become available.
  • Store and retrieve values through this variable.

28
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

29
Destroy a Session
  • To delete some session data
  • unset() delete a session variable free up
    space
  • session_destroy() delete a whole session and you
    lose all stored session data
  • lt?php unset(_SESSION'views') ?gt
  • lt?php session_destroy() ?gt

30
  • 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.

31
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

32
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

33
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.

34
  • 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)

35
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

36
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)

37
Today
  • Forms
  • Email
  • Functions
  • Cookies
  • Sessions

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