Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views88 pages

CST463 M4 Ktunotes.in

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 88

Module 4

Downloaded from Ktunotes.in


Syllabus
• Advanced PHP: Form processing and Business Logic-Cookies- Sessions
& MySQL Integration-Connecting to MySQL with PHP- Performing
CREATE, DELETE, INSERT, SELECT and UPDATE operations on MySQL
table -Working with MySQL data-Reading from Database -Dynamic
Content.

Downloaded from Ktunotes.in


Form processing and Business Logic

Downloaded from Ktunotes.in


Form processing and Business Logic

Downloaded from Ktunotes.in


Form processing and Business Logic

Downloaded from Ktunotes.in


Form processing and Business Logic

Downloaded from Ktunotes.in


Form processing and Business Logic

Downloaded from Ktunotes.in


Form processing and Business Logic

Downloaded from Ktunotes.in


Form processing and Business Logic

Downloaded from Ktunotes.in


Form processing and Business Logic

Downloaded from Ktunotes.in


Form processing and Business Logic

Downloaded from Ktunotes.in


Form processing and Business Logic

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Cookies(Textbook 1-DEITAL)

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Cookies
• You can use cookies within your PHP scripts to store small bits of information
about a user.
• A cookie is a small amount of data stored by the user’s browser in compliance with
a request from a server or script.
• A single host can request that up to 20 cookies be stored by a user’s browser.
• Each cookie consists of a name, value, and expiration date, as well as host and
path information. The size of an individual cookie is limited to 4KB. After a cookie
is set, only the originating host can read the data, ensuring that the user’s privacy
is respected. Furthermore, users can configure their browser to notify them upon
receipt of all cookies, or even to refuse all cookie requests. For this reason, cookies
should be used in moderation and should not be relied on as an essential element
of an environment design without first warning users.

Downloaded from Ktunotes.in


• A PHP script that sets a cookie might send headers that look
something like this:

Downloaded from Ktunotes.in


• As you can see, this Set-Cookie header contains a name/value pair, a path,
and a domain. If set, the expiration field provides the date at which the
browser should “forget” the value of the cookie. If no expiration date is
set, the cookie expires when the user’s session expires—that is, when he
closes his browser.

• The path and domain fields work together: The path is a directory found
on the domain, below which the cookie should be sent back to the server.
If the path is “/”, which is common, that means the cookie can be read by
any files below the document root. If the path is “/products/”, the cookie
can be read only by files within the /products directory of the website

Downloaded from Ktunotes.in


• The domain field represents the Internet domain from which cookie-based
communication is allowed. For example, if your domain is www.yourdomain.com
and you use www.yourdomain.com as the domain value for the cookie, the
cookie will be valid only when browsing the www.domain.com website. This
could pose a problem if you send the user to some domain like
www2.domain.com or billing.domain.com within the course of his browsing
experience, because the original cookie will no longer work. Therefore, it is
common simply to begin the value of the domain slot in cookie definitions with a
dot, leaving off the host (for example, .domain.com). In this manner, the cookie
is valid for all hosts on the domain. The domain cannot be different from the
domain from which the cookie was sent; otherwise, the cookie will not function
properly, if at all, or the web browser will refuse the cookie in its entirety

Downloaded from Ktunotes.in


Accessing Cookies
• If your web browser is configured to store cookies, it keeps the cookie-
based information until the expiration date. If the user points the
browser at any page that matches the path and domain of the cookie, it
resends the cookie to the server. The browser’s headers might look
something like this:

Downloaded from Ktunotes.in


Setting a Cookie with PHP
• You can set a cookie in a PHP script in two ways. First, you can use the
header() function to set the Set-Cookie header. The header() function
requires a string that is then included in the header section of the
server response. Because headers are sent automatically for you,
header() must be called before any output at all is sent to the
browser:

Downloaded from Ktunotes.in


• The setcookie() function does what its name suggests—it outputs a
Set-Cookie header. For this reason, it should be called before any
other content is sent to the browser. The function accepts the cookie
name, cookie value, expiration date in UNIX epoch format, path,
domain, and integer that should be set to 1 if the cookie is to be sent
only over a secure connection. All arguments to this function are
optional apart from the first (cookie name) parameter.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
• Even though the listing sets the cookie (line 2) when the script is run
for the first time, the $_COOKIE[‘vegetable’] variable is not created at
this point. Because a cookie is read only when the browser sends it to
the server, you cannot read it until the user revisits a page within this
domain

Downloaded from Ktunotes.in


• The cookie name is set to “vegetable” on line 2, and the cookie value to
“artichoke”.
• The time() function gets the current timestamp and adds 3600 to it (3,600 seconds
in an hour). This total represents the expiration date. The code defines a path of
“/”, which means that a cookie should be sent for any page within this server
environment.
• The domain argument is set to “.yourdomain.com” (you should make the change
relevant to your own domain or leave it blank if you are working on localhost),
which means that a cookie will be sent to any server in that group.
• Finally, the code passes 0 to setcookie(), signaling that cookies can be sent in an
unsecure environment. Passing setcookie() an empty string (“”) for string
arguments or 0 for integer fields causes these arguments to be skipped

Downloaded from Ktunotes.in


Viewing a stored cookie in a web
browser.

Downloaded from Ktunotes.in


Deleting a Cookie with PHP

Downloaded from Ktunotes.in


Session Function Overview
• Session functions provide a unique identifier to a user, which can then
be used to store and acquire information linked to that ID.
• When a visitor accesses a session enabled page, either a new
identifier is allocated or the user is reassociated with one that was
already established in a previous visit.
• Any variables that have been associated with the session become
available to your code through the $_SESSION superglobal.
• Session state is usually stored in a temporary file, although you can
implement database storage or other server-side storage methods
using a function called session_set_save_handler().

Downloaded from Ktunotes.in


Starting a Session

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Working with Session Variables

Downloaded from Ktunotes.in


Accessing the stored session
variables

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
• The listing starts or resumes a session by calling session_start() on line
2. This call gives access to any previously set session variables. An
HTML form begins on line 24 and, on line 26, creates a SELECT
element named form_products[], which contains OPTION elements
for a number of products.

Downloaded from Ktunotes.in


• The block of PHP code beginning on line 11 tests for the presence of the
$_POST[‘form_products’] array (line 12).
• If the variable is present, you can assume that the form has been submitted
and information has already been stored in the $_SESSION superglobal.
• Line 12 tests for an array called $_SESSION[‘products’]. If the array exists, it
was populated on a previous visit to this script, so the code merges it with
the $_POST[‘form_products’] array, extracts the unique elements, and
assigns the result back to the $products array (lines 14–16).
• Then the $products array is added to the $_SESSION superglobal on line 17.
Line 35 contains a link to another script, which will demonstrate access to
the products the user has chosen.

Downloaded from Ktunotes.in


Accessing an Array of Session
Variables
• This new script is created in Listing 12.6, but in the mean time you can
save the code in Listing 12.5 as arraysession.php. Moving on to Listing
12.6, you see how to access the items stored in the session created in
arraysession.php.

Downloaded from Ktunotes.in


Destroying Sessions and Unsetting
Variables

Downloaded from Ktunotes.in


Questions
• Explain any six string handling functions used in PHP with example(6)
• How does a PHP array differ from an array in C? List the different ways
to create an array in PHP with an example. Explain any 4 functions that
deals with PHP array.(8)
• During the process of fetching a web page from a web server to a client
browser, at what point does an embedded PHP script get executed.
What are the two modes that the PHP processor operates in? Explain
(6)
• Why is PHP considered to be dynamically typed? Distinguish between
implode and explode function in PHP with suitable examples.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
• Describe how input from an HTML form is retrieved in a PHP program,
with an example(3)
• Discuss the various steps for establishing PHP-MySQL connection with
a MySQL db

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
• PHP Sorting Arrays - sort(), rsort(), asort(), ksort(), arsort(), krsort() |
jobtensor

Downloaded from Ktunotes.in


PHP& MySQL Integration-Connecting
to MySQL with PHP .
• Making a Connection

Downloaded from Ktunotes.in


Making a Connection

Downloaded from Ktunotes.in


Making a Connection

Downloaded from Ktunotes.in


Modified connection

Downloaded from Ktunotes.in


Executing Queries
• The mysqli_query() function in PHP is used to send your SQL query to MySQL.

• In lines 8–10, the text that makes up the SQL statement is assigned to the variable $sql. This is
arbitrary, and you do not even need to place the content of your SQL query in a separate variable

Downloaded from Ktunotes.in


Executing Queries
• The mysqli_query function returns a value of true or false, and this
value is checked in the if...else statement beginning in line 13.
• If the value of $res is true, a success message is printed to the screen.
• If you access MySQL through the command-line interface to verify the
creation of the testTable table, you will see the following output of
DESCRIBE testTable:

Downloaded from Ktunotes.in


Executing Queries
• When mysqli_error() has been used in conjunction with the PHP die()
function, which simply exits the script at the point at which it appears,
the mysqli_error() function returns a helpful error message when you
make a mistake.

Downloaded from Ktunotes.in


Working with MySQL Data
• Inserting, updating, deleting, and retrieving data all revolve around the
use of the mysqli_query() function to execute the basic SQL queries.
• SQL Injection: In the types of dynamic websites or web-based
applications that you are likely to build, you will most often be
INSERTing data into a table or SELECTing from a table based on user
input from a form or other process.
• If you do not pay attention to this user input and sanitize it before
using it in your queries, you are vulnerable to SQL injection

Downloaded from Ktunotes.in


Working with MySQL Data
• SQL injection happens when nefarious individuals take the
opportunity to type full or partial SQL queries in your form fields, with
the assumption that when the script processes these queries, security
will be breached and data potentially exposed.

Downloaded from Ktunotes.in


Example-SQL Injection

Downloaded from Ktunotes.in


Performing CREATE, DELETE, INSERT
operations on MySQL table from PHP Program
• Refer pdf shared

Downloaded from Ktunotes.in


Performing SELECT and UPDATE operations
on MySQL table from PHP Program.

Downloaded from Ktunotes.in


Inserting Data with PHP

Downloaded from Ktunotes.in


Inserting Data with PHP

Downloaded from Ktunotes.in


Inserting Data with PHP

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Inserting Data with PHP

Downloaded from Ktunotes.in


Inserting Data with PHP
Text typed in the form field

Downloaded from Ktunotes.in


Inserting Data with PHP
• The record has been successfully added.

Downloaded from Ktunotes.in


Inserting Data with PHP
To verify the work that has been done with PHP, you can use the MySQL
command line interface to view the records in the table using a

SELECT query: SELECT * FROM testTable;

Downloaded from Ktunotes.in


Retrieving Data with PHP
• Because you have a few rows in your testTable table, you can write a
PHP script to retrieve that data.
• We write a script that issues a SELECT query but doesn’t overwhelm
you with result data. Let’s just get the number of rows. To do this, use
the mysqli_num_rows() function.

Downloaded from Ktunotes.in


Retrieving Data with PHP
• Save this script as count.php, place it in your web server document
directory, and access it through your web browser.
• Result set has 4 rows.

Downloaded from Ktunotes.in


Retrieving Data with PHP

Downloaded from Ktunotes.in


Retrieving Data with PHP
• Easiest method is to retrieve each row from the table as an array
• You use a while statement to go through each record in the resultset,
placing the values of each field into a specific variable and then
displaying the results onscreen.
• The syntax of mysqli_fetch_array() is as follows:
$newArray = mysqli_fetch_array($result_set);

Downloaded from Ktunotes.in


Retrieving Data with PHP

Downloaded from Ktunotes.in


Retrieving Data with PHP
• Selecting records from MySQL.

Downloaded from Ktunotes.in


Building Dynamic Content in PHP
application
• PHP can dynamically change the HTML5 it outputs based on a user’s
input

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Variables
• Lines 19–28 create variables that are used throughout the script to fill
in form fields and check for errors.
• Lines 19–24 use the isset function to determine whether the $_POST
array contains keys representing the various form fields.
• These keys exist only after the form is submitted.
• If function isset returns true, then the form has been submitted and
we assign the value for each key to a variable. Otherwise, we assign
the empty string to each variable.

Downloaded from Ktunotes.in


Arrays
• Lines 31–41 create three arrays, $booklist, $systemlist and $inputlist, that are
used to dynamically create the form’s input fields.
• We specify that the form created in this document is self-submitting (i.e., it
posts to itself) by setting the action to the script 'dynamicForm.php' in line 125.
• Line 44 uses function isset to determine whether the Register button has been
pressed, in which case the $_POST array will contain the key "submit" (the
name of the button in the form).
• If it has, each of the text input fields’ values is validated. If an error is detected
(e.g., a text field is blank or the phone number is improperly formatted), the
corresponding entry in array $formerrors is set to true and variable $iserror is
set to true.
• If the Register button has not been pressed, we skip ahead to line 115.

Downloaded from Ktunotes.in


Dynamically Creating the Form
• Line 71 determines whether any errors were detected. If $iserror is false
(i.e., there were no input errors)
• lines 74–111 display the page indicating that the form was submitted
successfully—we’ll say more about these lines later.
• If $iserror is true, lines 74–111 are skipped, and the code from lines
115–179 executes.
• These lines include a series of print statements and conditionals to
output the form,(19.20 a)

Downloaded from Ktunotes.in


Dynamically Creating the Form
• Lines 129–138 iterate through each element in the $inputlist array.
• In line 132 the value of $$inputname is assigned to the text field’s value attribute. If
the form has not yet been submitted, this will be the empty string "".
• The notation $$variable specifies a variable variable, which allows the code to
reference variables dynamically.
• You can use this expression to obtain the value of the variable whose name is equal to
the value of $variable.
• PHP first determines the value of $variable, then appends this value to the leading $ to
form the identifier of the variable you wish to reference dynamically. (The expression $
$variable can also be written as ${$variable} to convey this procedure.)
• For example, in lines 129–138, we use $$inputname to reference the value of each
form-field variable.

Downloaded from Ktunotes.in


Dynamically Creating the Form
• During the iteration of the loop, $inputname contains the name of one of
the text input elements, such as "email".
• PHP replaces $inputname in the expression $$inputname with the string
representing that element’s name forming the expression ${"email"}.
• The entire expression then evaluates to the value of the variable $email.
Thus, the variable $email, which stores the value of the e-mail text field
after the form has been submitted, is dynamically referenced.
• This dynamic variable reference is added to the string as the value of the
input field (using the concatenation operator) to maintain data over
multiple submissions of the form

Downloaded from Ktunotes.in


Dynamically Creating the Form
• Lines 134–135 add a red asterisk next to the text input fields that were filled out incorrectly.
• Lines 140–142 display the phone number format instructions in red if the user entered an
invalid phone number.
• Lines 150–155 and 165–175 generate options for the book drop-down list and operating-
system radio buttons, respectively.
• In both cases, we ensure that the previously selected or checked element (if one exists)
remains selected or checked over multiple attempts to correctly fill out the form.
• If any book was previously selected, line 153 adds selected to its option tag.
• Lines 170–171 select an operating system radio button under two conditions.
• If the form is begin displayed for the first time, the first radio button is selected.
• Otherwise, if the $currsystem variable’s value matches what’s stored in the $os variable
(i.e., what was submitted as part of the form), that specific radio button is selected.

Downloaded from Ktunotes.in


Inserting Data into the Database
• Inserting Data into the Database If the form has been filled out correctly,
lines 74–95 place the form information in the MySQL database
MailingList using an INSERT statement.
• Line 77 uses the function mysql_real_escape_string to insert a backslash
(\) before any special characters in the passed string.
• We must use this function so that MySQL does not interpret the
parentheses in the phone number as having a special meaning aside
from being part of a value to insert into the database.
• Lines 98–110 generate the web page indicating a successful form
submission, which also provides a link to formDatabase.php (Fig. 19.21).

Downloaded from Ktunotes.in


Displaying the Database’s Contents
• The script in Fig. 19.21 displays the contents of the MailingList
database.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Displaying the Database’s Contents

Downloaded from Ktunotes.in

You might also like