Professional Documents
Culture Documents
Dynamic Web Sites are flexible, accurately describes as applications than merely sites:
Respond to different parameters (for example, the time of day or the version of the visitors Web browser Have a memory allowing user registration & login Involve HTML forms, so that people can perform searches, provide feedback, etc Often have interfaces where administrators can manage the sites content Easier to maintain, upgrade and build open
What is PHP?
PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) PHP is an open source software (OSS) PHP is free to download and use
Php.net
PHP files may contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or ".phtml"
Why PHP?
PHP runs on different platforms (Windows, Linux, Unix, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP is FREE to download from the official PHP resource: www.php.net PHP is easy to learn and runs efficiently on the server side
Where to Start?
Install an Apache server on a Windows or Linux machine Install PHP on a Windows or Linux machine Install MySQL on a Windows or Linux machine Or download FoxServ/EasyPHP
PHP Installation
Download PHP http://www.php.net/downloads.php
Server-side scripting. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. Command line scripting. You can make a PHP script to run it without any server or browser.
Writing desktop applications. Ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution.
Basic syntax
echo() print ()
For example, <?php echo This was done using PHP; ?> Will display: This was done using PHP
PHP is generally white space insensitive, meaning that you can space out your code to make your scripts more legible.
To alter the spacing of the finished Web page, use the HTML tags <br /> (line break) and <p></p> (paragraph).
To alter the spacing of the HTML source created with PHP:
Use echo() or print() over the course of several lines Use the newline character (\n) within the double quotation marks.
# This is a comment // This is also a comment /* This is a longer comment that spans two lines */
Variables
A variables name (identifier) must start with a dollar sign ($), for example $name Can contain combination of strings, numbers & underscore ($my_report1) First character after dollar sign ($) must be either a letter or an underscore (it cannot be a number)
Variables
Variable names in PHP are casesensitive. Variables can be assigned using the equal sign (=)
Variables: Strings
Strings are case sensetive so $Welcome_Text is not the same as $welcome_text When assigning numbers to strings you do not need to include the quotes so: $user_id = 987 would be allowed.
Outputting Variables
To display a variable on the screen uses exactly the same code as to display text but in a slightly different form. The following code would display your welcome text:
<? $welcome_text = "Hello and welcome to my website."; print($welcome_text); ?>
As you can see, the only major difference is that you do not need the quotation marks if you are printing a variable. String variables are created and their values sent to the Web browser in this script
Concatenating strings
$city = Ipoh; $state = Perak $address = $city . $state ; Will display: IpohPerak To improve: $address = $city . , . $state ;
Using numbers
Valid number-type variables can be like: 8, 3.14, 109080808, -4.524 To format the number into thousands and round it to two decimal places:
$total = number_format ($total, 2);
Understanding Functions
Function: subroutine/individual statements grouped into a logical unit that performs specific task. To execute a function, must invoke or call it from somewhere in your script. The statement that calls a function is referred to as a function call and consists of the function name followed by any data of the function needs.
Arguments / Actual parameters: The data (which you place in parentheses following the function name). Passing arguments: Sending data to a called function. Many functions generate, or return, some sort of a value that you can use in your script. E.g. round() function that rounds a decimal value to the nearest whole number.
round() function
You pass a number as an argument to the round()function, which calculates and returns the nearest whole number. The following statements calls the round()function and passes to it a value of 3.556. The round()function calculates and returns a value of 4, which is then displayed with an echo statement.
round() function
Many functions can accept multiple arguments, which you separate with commas. The following statements calls the round() function and then passes to it a first argument of 3.556 and a second argument of 2. The round() function calculates and returns a value of 3.56 (rounded to two decimal places)
Constants
Constants are a specific data type in PHP, that unlike variables, retain their initial value throughout the course of a script. You cant change the value of a constant once it has been set. Constants can be assigned any single value a number or a string of characters.
Defining Constants
A constant contains information that does not change during the course of program execution. Common practice to use all uppercase letters for constant names. Use define( ) function to create constant.
By default, constant names are case sensitive, but you can make constant names case insensitive by passing a Boolean value of TRUE as third argument to the define function.
You can pass a constant name to the echo statement on the same manner as you pass a variable name, but without the dollar sign.
Data Types
Data Type Integer numbers Floating point numbers Boolean String NULL Description The set of all positive and negative numbers and zero, with no decimal places Positive or negative numbers with decimal places or numbers written using exponential notation A logical value of true or false Text such as Hello World An empty value, also referred ti as a NULL value
Programming languages that do not require you to declare the data types of variables are called loosely typed programming languages. Loose typing is also known as dynamic typing because the data types for a variable can change after it has been declared. In PHP, you are not required to declare the type of variables, in fact you are not allowed to do so.
= Hello World; //
= 8; // Integer = 5.367; // Floating = TRUE; // Boolean = NULL; // NULL
Using double quotation marks: echo "You are purchasing <b>$quantity</b> widget(s) at a cost of <b>\$$price</b> each. With tax, the total comes to <b>\$$total</b>.\n";
Using single quotation marks echo 'You are purchasing <b>$quantity</b> widget(s) at a cost of <b>\$$price</b> each. With tax, the total comes to <b>\$$total</b>.\n';
The script to demonstrate the difference between using single and double quotation marks
cont
Overview
Creating an HTML Form Handling an HTML Form Managing Magic Quotes Conditionals & Operators Validating Form Data Arrays
An HTML form is created using the form tags and various input types.
<form action=script.php method=post> </form>
Create the corresponding script that will receive and process the form data
Form
The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.
Form example:
<html> <body><form action="welcome.php" method="post"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form></body> </html>
cont
<html> <body>Welcome <?php echo $_POST["name"]; ?>.<br /> You are <?php echo $_POST["age"]; ?> years old.</body> </html> A sample output of the above script may be:
Welcome John. You are 28 years old.
$_REQUEST
$_REQUEST is a special variable type in PHP. It stores all of the data sent to PHP page through either the GET or POST methods, as well as data accessible in cookies.
The built-in $_GET function is used to collect values from a form sent with method="get".
Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send (max.
When the user clicks the "Submit" button, the URL sent to the server could look something like this:
The "welcome.php" file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array):
When using method="get" in HTML forms, all variable names and values are displayed in the URL. Note: 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. Note: The get method is not suitable for large variable values; the value cannot exceed 100 characters.
The built-in $_POST function is used to collect values from a form sent with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).
When the user clicks the "Submit" button, the URL will look like this:
The "welcome.php" file can now use the $_POST function to collect form data (the names of the form fields will automatically be the keys in the $_POST array):
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
$_REQUEST
If the PHP scripts show blank spaces where the variables should have printed out, it means that the variable have no values. Likely causes:
Misspelled or mis-capitalized the variable names $_REQUEST is not available because youre using an outdated version of PHP
When Magic Quotes is enables, it will automatically escape single and double quotation marks in the values of variables. In PHP, there are 2 types of Magic Quotes
magic_quotes_gpc: Applies to form, URL & cookie data (gpc stands for get, post, cookie) magic_quotes_runtime: Applies to data
cont
If Magic Quotes is enabled on your server, you can do undo its effect using the stripslashes() function &var = stripslashes($var)
This function will remove any backslashes found in $var.
The apostrophe entered in the form was escaped automatically by PHP, generating unseemly results
Open handle_form.php Change the first & third variable assignment lines to
$name=stripslashes($_REQUEST[nam e]); $comments=stripslashes($_REQUEST[ comments]);
PHPs three primary terms for creating conditionals are if, else and elseif (which can also be written as two words else if)
IF conditions
if (condition) { //DO something! }
If else
if (condition) { //DO something! } else } //DO something else }
if elseif
if (condition) { //DO something! } elseif (condition2) { //DO something else } else { //DO something different }
cont
A condition can be true in PHP for any number of reasons. These are common true conditions:
$var, if $var has a value other than 0, an empty string, or NULL isset($var), if $var has any value other than NULL, including 0 or an empty string TRUE, true, True, etc
isset($var)
This function checks if a variable is set, meaning that it has a value other than NULL. Example:
Form Validation
Form Validation
The first aim of form validation is ensuring that something was entered or selected in form elements. The second goal is to ensure that submitted data is of the right type (numeric, string, etc) or a specific acceptable value (like &gender being equal to either F or M.
Form Validation
cont
Validating form data requires the use of conditionals and any number of functions, operators & expressions. One common function to be used is isset(), which tests if a variable has a value (including 0, FALSE, or an empty string, but not NULL). One problem with isset()function is that an empty string tests as TRUE, meaning that its not effective way to validate text inputs and text boxes from an HTML form.
Form Validation
cont
To check that a user typed something into textual elements like name, email, and comments you can use the empty() function.
It checks if a variable has an empty value: an empty string, 0, null or FALSE Script to validate form
Arrays
Array can hold multiple, separate pieces of information, unlike strings and numbers (which are scalar variables, meaning they can store only a single value at a time). PHP supports two kinds of arrays:
indexed associative.
Array: Indexed
0
1 2 3
Rihanna
Madonna Sting Daughtry
Maroon5
Array: Associative
Array Example1: $states KEY KL PP PRK KEL VALUE Kuala Lumpur Pulau Pinang Perak KELANTAN
To retrieve a specific value from an array, you refer to the array name first, followed by the key, in square brackets:
Note that array keys are used like other values in PHP: number (e.g., 2) are never quoted, whereas strings (KL) must be.
Printing array
Wrap around your array name and key in curly braces when your array uses strings for its keys: echo PP is the abbreviation for {$states[PP]}.; Numerically, indexed arrays dont have this problem, though: echo The artist with an index of 4 is $artists[4].;
To use arrays
Open handle_form.php Change the assignment of the $name and $comments variables to
$name = striplashes($_POST[name]) $comments= striplashes($_POST[comments]); In the previous version of this script, the values of $name and $comments were assigned by referring to the $_REQUEST array which will work. But since these variables come from a form that uses the post method, $_POST would be more exact, and therefore more secure
cont
Alter the echo() statement echo <p>Thank you, <b>$name</b>, for the following comments:<br /> <tt>$comments</tt></p> <p>We will reply to you at <i> {$_POST[email]}</i>/</p>\n ;
Creating arrays
Add an element at a time to build one Use array() function to build an entire array in one step
Example:
$array[] = Tobias; $array[] = Maeby; $array[wife] = Lindsay;
Its important to note that if you specify a key and a value already exists indexed with that same key, the new value will overwrite the existing one. For example,
$array[son] = Buster; $array[son] = Michael;
This function can be used whether or not you explicitly set the key
$artists=array (Incubus, Coldplay, Nelly);
If you set the first numeric key value, the added values will be keyed incrementally thereafter:
$days=array(1=>Sunday, Monday,Tuesday); echo $day[3];//Tuesday If you want to create an array of sequential numbers, use the range() function: $ten = range (1,10); Calendar: To create & access arrays
Multidimensional arrays
Then, these two arrays could be combined into one multidimensional array like:
$abbr=array (UD=>$states, Canada=>province);
Multidimensional arrays
cont
To access the $states array, refer to $abbr[US] To access Maryland, use $abbr[US][MD] Simply use the name of the multidimensional array, followed by the key of the first array in square brackets, followed by the key of the second inner array in square brackets. To print, surround the whole construct in curly braces: echo The US state whose abbreviation is MD is {$abbr[US][MD].; To use multidimensional arrays About.html About.txt To handle the form: handle_about.php
PHP has two functions for converting between strings and arrays
$array=explode (separator, $string); $string=implode (glue, $array);
When turning an array into a string, you set the glue the characters or code that will be inserted between the array values in the generated string.\ Conversely, when turning into an array, you specify the separator, which is the code that delineates between the different elements in the generated array
cont
$string1 = Mon Tue Wed Thur Fri; $days_array = explode( - , $string1);
The $days_array variable is now a five-element array, with Mon indexed at 0, Tue indexed at 1, etc. $string2=implode(, , $days_array); The $string2 variable is now a comma-separated list of days: Mon, Tue, Wed, Thur, Fri
Sorting arrays
sort() Sort an array by value, discarding the original keys. Its important to note that the arrays keys will be reset after the sorting process, so if the key-value relationship is important, you should NOT use this function. asort() sort an array by value while maintaining the keys ksort() sort an array by key rsort(), arsort(), krsort() sort in reverse order
As long as the condition part of the loop is true, the loop will be executed. Once it becomes false, the loop stopped. If the condition is never true, the loop will never be executed. The while loop will most frequently be used when retrieving results from a database
condition
Do this if TRUE
condition
after expression
Upon first executing the loop, the initial expression is run. Then, the condition is checked and, if true, the contents of the loop are executed. After execution, the closing expression is run and the condition is checked again. This process continues until the condition is false.
for ($i = 1; $i <=10; $i++) { echo $i; }
The first time this loop is run, the $i variable is set to the value of 1. Then, the condition is checked (is 1 less than or equal to 10?) Since this is true, 1 is printed out (echo $i) Then, $i is incremented to 2 ($i++), the condition is checked, and so forth. The result of this script will be the numbers 1 through 10 printed out Example of loops: calendar.php
88
Overview
1.
2.
3.
4.
5.
6. 7.
Including Multiple Files Handling HTML Forms with PHP Redux Making Sticky Form Creating & Calling Your Own Functions Variable Scope Date & Time Functions Sending Email
89
90
The functions are exactly the same when working properly but behave differently when they fail. If an include() function doesnt work (it cannot include the file for some reason), a warning will be printed on the Web browser, but the script will continue to run.
91
If require() fails, error is printed and the script is halted. These two functions are used to create functions, headers, footers, or elements that can be reused on multiple pages. This can save the developer a considerable amount of time by creating a standard header or menu file. When the header needs to be updated, you can only update this one include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all web pages).
92
The include() function takes all the text in a specified file and copies it into the file that uses the include function. Example 1: Assume that you have a standard header file, called "header.php". To include the header file in a page, use the include() function, like this:
<html> <body><?php include("header.php"); ?><h1>Welcome to my home page</h1><p>Some text</p></body> </html>
93
*_once() function
Both functions have a *_once() version, which guarantees that the file in question is included only once regardless of how many times a script may (presumeably inadvertently) attempt to include it. require_once(filename.php) ; include_once(filename.php)
94
Site structure
When you begin using multiple files, the overall site structure becomes more important. When laying out your site, there are 3 considerations:
Site structure
Ease of maintenance
Using external files for holding standard procedures (i.e. PHP code), CSS, JavaScript and HTML design greatly improve the ease of maintaining site because commonly edited code is placed in one central location.
96
Site structure
Security
Use .inc or .html file for extension documents where security is not issue (such as HTML templates) Use .php for files containing sensitive data (such as database access information) You can also use both .inc and .html or .php so that a file is clearly indicated as an include of a certain type: functions.inc.php or header.inc.html
97
Site structure
Structure your sites so that they are easy for users to navigate, both by clicking links and by manually typing a URL. Try avoid creating too many nested folders or using hard-to-copy directory names and filenames containing upper and lowercase letters and all manner of punctuation
98
The previous examples showed that there are two separate scripts for handling HTML forms: one that displayed the form and another that received it. To have the entire process in one script, use a conditional if (/* form has been submitted */) { //Handle it } else { //Display it }
99
cont
To determine if the form has been submitted, check that a $_POST variable. For example, check the $_POST[submitted]
if (isset($_POST[submitted])) { //Handle it } else { // Display it }
100
cont
If you want a page to handle a form and then display it again (e.g. to add a record to a database and then give an option to add another), use
if (isset($_POST[submitted])) { //Handle it } // Display the form
Example (calculator.php)
101
Step 2: Write the conditional for handling the form if (isset($_POST['submitte d'])) {
103
A sticky form is simply a standard HTML form that remembers how you filled it out. This is particularly nice feature for end users especially if your are requiring them to resubmit a form (for instance, after filling it out incorrectly on the first place) To make sticking form, open calculator.php
108
109
To create your own functions Creating a function that takes arguments Setting default argument values Returning values from a function
110
PHP has a the capability for you to define and use your own functions. The syntax:
function function_name () { // Function code }
The name of your function can be any combination of letters, numbers & underscores, but it must begin with either a letter or the underscore.
111
The main restriction is that you cannot use an existing function (print, echo, isset, etc). Function names are case-insensitive (unlike variable names), so you could call that function use function_name() or FUNCTION_NAME() or Function_Name(), etc.
Exercise: To create your own function (dateform.php)
112
Just like PHPs built-in functions, those you write can take arguments (also called parameters). A function can take any number of arguments that you choose, but the order in which you put them is critical. To allow for arguments, add variables to your functions definition:
function print_hello() ($first, $last) { // Function code 113 }
cont
You can call the function as you would any other function in PHP, sending literal values or variables to it:
print_hello (Jimmy, Stewart); $surname = Stewart; $print_hello (Jimmy, surname);
As with any function in PHP, failure to send the right number of arguments results in an error. Exercise: Rewrite the calculator process as a function
114
function calculate_total
function calculate_total ($qty, $cost, $tax) { $taxrate = $tax / 100; $total = ($qty * $cost) * ($taxrate + 1); echo '<p>The total cost of purchasing ' . $qty . ' widget(s) at $' . number_format ($cost, 2) . ' each, including a tax rate of ' . $tax . '%, is $' . number_format ($total, 2) . '.</p>'; }
115 Notice that the variables being defined are not $_POST[quantity], $_POST[price], $_POST[tax]
Another variant on defining your own functions is to preset an arguments value. To do so, assign the argument a value in the functions definition:
function greet ($name, $greeting = Hello) { echo $greeting, $name!; }
The end result of setting a default argument value is that that particular argument becomes optional when calling the function. If a values is passed to it, the passed value is used; otherwise the default value is used
116
cont..
You can set default values for as many of the arguments as you want, as long as those arguments come last in the function definition. In other words, the required arguments should always be first. Example:
greet ($surname, $message); greet (Roberts); greet (Grant, Good Evening);
However, greet() will not work, and theres no way to pass $greeting a value without passing one to $name as well. Exercise: To set default argument values
117
119
120
cont
The function can return a value (number/string) or a variable whose value has been created by the function. When calling this function, assign the returned value to a variable $my_sign = find_sign (July, 9); Or use it as a parameter to find another function: print find_sign (July, 9); Exercise: To have a function return a value
121
Variable Scope
Every variable in PHP has a scope to it, which is to say a realm in which the variable (and therefore its value) can be accessed. For starters, variables have the scope of the page in which they reside, So, if you define $var, the rest of the page can access $var, but other pages generally cannot (unless you use special variables).
122
Since included files act as if they were part of the original (including) script, variables defined before the include() line are available to the included file. Further, variables defined within the included file are available to the parent (including) script after the include() line.
123
Variable Scope
cont
Functions have their own scope, which means that variables used within a function are not available outside of it; and variables defined outside of a function are not available within it. For this reason, a variable inside of a function can have the same name as one outside of it and still be an entirely different variable with a different value. This is a confusing concept for most beginners.
124
Variable Scope
global() Statement
To alter the variable scope within a function, use the global() statement
function function_name() { global $var; } $var = 20; function_name(); // Function call
In this example, $var inside the function is now the same as $var outside of it. This means that the function $var already has a value of 20, and if the value changes inside of the function, the external $var s value will also change
125
Variable Scope
Superglobals
Another option for circumventing variable scope is to make use of the superglobals: $_GET, $_POST, $_REQUEST, etc.
These variables are automatically accessible within your functions. Exercise: To use global variables
126
date() function returns a string of text for a certain date and time according to a format specified date (format, [timestamp]); The timestamp is an optional argument representing the number of seconds . It allows you to get information, like the day of the week, for a particular date. If timestamp is not specified, PHP will just use the current time on the server.
127
cont
There are myriad formatting parameters available and these can be used in conjunction with literal text. For example:
echo date (F j, Y); // January 26, 2005 echo date (H:i); 23:14 echo date(Today is D); // Today is Mon
128
MEANING
Year as 4 digits
EXAMPLE
2005
y
N m F M j d L (lowercase L)
Year as 2 digits
Month as 1 or 2 digits Month as 2 digits Month Month as 3 letters Day of the months as 1 or 2 digits Day of the months as 2 digits Day of the week
129
05
2 02 February Feb 8 08 Monday
MEANING
Day of the week as 3 letters
EXAMPLE
Mon
g
G h H i S a A
6
18 06 18 45 18 am PM
getdate() Function
getdate() Function to return an array of values for date and time. Example:
$dates = getdate(); echo $dates [month]; // January
This function also takes an optional timestamp argument. If that argument is not used, getdate() returns information of the current date and time. Exercise: dateform.php
131
The getdate()Array
KEY year mon month mday weekday hours minutes seconds VALUE
Year Month 2005 12
EXAMPLE
Month name Day of the month Day of the week Hours Minutes Seconds
132
December 25 Tuesday 11 56 47
Sending Email
Use mail() function to send email in mail ($to, $subject, $body); $to = email address or a series of addresses, separated by commas $subject = emails subject line $body = contents of the email. Use the newline character (\n) within the double quotation marks when creating your body to make the text go over multiple lines
133
Sending Email
cont
The mail() function takes a fourth, optional parameter for additional headers. This is where you can set the From, Reply-To, Cc, Bcc and etc. For example: mail (sarirah97@yahoo.com, Hello, $body, From: fcet3rd@yahoogroups.com);
134
Sending Email
cont
To use multiple headers of different types in email, separate each with \r\n
$headers = From: fcet3rd@yahoogroups.com \r\n; $headers .= Cc: unatuna97@yahoo.com\r\n; mail (sarirah97@yahoo.com, Hello, $body, $headers);
135
PHPs mail function doesnt actually send the email itself. Instead, it tells the mail server running on the computer to do so. This means, that your computer must have a WORKING MAIL SERVER in order for this function to work.
136
If you have a computer running a UNIX variant or through a professional host, this should not be a problem. But if you are running PHP on your own computer, youll probably need to make adjustments.
137
If you are running on Windows and have ISP that provides with SMTP server, this information can be set in the php.ini file. Unfortunately, this will only work if your ISP doesnt require authentication to use the SMTP server. Otherwise, you need to install an SMTP server on your computer. Google for free windows smtp server.
138
If you are running on Mac OS X, youll need to enable the built-in SMTP server (either sendmail or postfix, depending upon the specific version of Mac OS X you are running). You can find instructions online for doing so google: enable sendmail Mac OS X
139
140
Cookies
A cookie is a small file that is stored on the client computer when visiting a website. Cookies got a bad rap a few years ago and as a result there is a good deal of people out there with their cookies disabled. Cookies are harmless. Some sites will use them to track visitor usage and
Features of a cookie
Stored on the client computer and are thus decentralized. Can be set to a long lifespan and/or set to expire after a period of time from seconds to years. They work well with large sites that may use several web servers. Wont do you any good if the client has set their browser to disable cookies.
Limitations on size and number: a browser can keep only the last 20 cookies sent from a particular domain, and the values that a cookie can hold are limited to 4 KB in size. Can be edited beyond your control since they reside on the client system. Information set in the cookie is not available until the page is reloaded.
The PHP $_COOKIE variable is used to retrieve a cookie value. In the example below, we retrieve the value of the cookie named "user" and display it on a page:
If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One method is to pass the data through forms.
PHP Sessions
PHP session
A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.
Features of sessions
Server-size cookie can store very large amounts of data while regular cookies are limited in size. Since the client-side cookie generated by a session only contains the id reference (a random string of 32 hexadecimal digits, such as fca17f071bbg9bf7f85ca281653499a4 called a session id) you save on bandwidth. Much more secure than regular cookies since the data is stored on the server and cannot be edited by the user.
Only last until the user closes their browser. Wont work if client has cookies disabled in their browser unless some extra measures are taken. Can be easily customized to store the information created in the session to a database. Information is available in your code as soon as it is set.
Your server-side cookie can contain very large amounts of data with no hassle client-side cookies are limited in size Your client-side cookie contains nothing other than a small reference code - as this cookie is passed each time someone visits a page on your site, you are saving a lot of bandwidth by not transferring large client-side cookies around Session data is much more secure - only you are able to manipulate it, as opposed to client-side cookies which are editable
Cookies vs Session?
Cookies generally should be used for nonsensitive throw-away information like the following:
Displaying the users name next time they visit the site. Simple user display preferences. Anything small and disposable that needs to be stored for a period of time (for info like, email address, contact info etc. a database should be used)
Sessions are used for more sensitive info like controlling user access or loading info from a database that expires when the session ends or the browser window is closed.
Before you can store user information in your PHP session, you must first start up the session. The session_start() function must appear BEFORE the <html> tag:
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.
In the next example, we create a simple 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:
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function. The unset() function is used to free the specified session variable: <?php unset($_SESSION['views']); ?>
You should not use sessions in very large projects which are likely to be deployed on multiple load-balancing servers. The reason behind this may not be apparent at first, but if you recall, session data is actually stored in a file on a server's computer. If a user visits your site, and your load-balancer redirects them to one server for a request, that server has their session data. Next time they read a page, your load-balancer may well shift them to another server, leaving their original session data on the original server. The second server might also save some session data of its own.
The end result? They lose their information part-way through their visit, and what data you do have is fragmented across your servers. There are ways around this problem, never fear:
Use a networked file system (NFS on Unix or the equivalent). Pretty much all operating systems allow you to connect to other computers and read/write their data. If you have a shared session data source, you would be able to bypass the above problem Write your own session implementation that stores data in a medium you can handle and share between all computers. This is tricky, and error-prone. Use a database to store your sessions.
Different versions of browsers on different platforms define their cookie handling policies in different places. In IE, Windows XP:
choose Tools > Internet Options Click Privacy tab Click Advanced button under Settings Click Override automatic cookie handling Choose Prompt for both First- and
In Firefox on Windows
Choose Tools > Options Click Privacy Expand the Cookies section Select ask me every time in the Keep Cookies dropdown menu
If you are using Firefox on Mac OS X, the steps are the same, but start by choosing Firefox > Preferences
setcookie() function
To see the effect of the setcookie() function, set your Web browser to ask before storing cookie.
setcookie() function
To send a cookie
Create new PHP document <?php # login.php 2. Validate the form // Check if the form has been submitted. if (isset($_POST['submitted'])) {
1.
require_once ('/mysql_connect.php'); // Connect to the db. $errors = array(); // Initialize error array.
If user entered the correct information, log the user in. The $row variable will have a value only if the preceding query returned at least one record
Complete the $row conditional and the $errors conditional, and the close the database connection
loggedin.php
?php # Script 9.2 Check the loggedin.php presence of a cookie // If no cookie is present, redirect the user. if (!isset($_COOKIE['user_id']) ) { // Start defining the URL. $url = 'http://' .
loggedin.php
// Check for a trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { $url = substr ($url, 0, -1); // Chop off the slash. } $url .= '/index.php'; // Add the page. header("Location: $url"); exit(); // Quit the script.
}
// Set the page title and include the HTML header. $page_title = 'Logged In!'; include ('./includes/header.html'); // Print a customized message. echo "<h1>Logged In!</h1> <p>You are now logged in, {$_COOKIE['first_name']}!</p> <p><br /><br /></p>";
include ('./includes/footer.html'); ?>
The expiration argument is used to set a definitive length of time for a cookie to exist, specified in seconds. If it is not set, the cookie will continue to be functional until the user closes his or her browser.
As with all functions that take arguments, you must pass the setcookie() values in order. To skip any parameter, use NULL or an empty string. The expiration and secure values are both integers and are therefore not quote.
Change the two setcookie() lines to include an expiration date thats 60 minutes away
Deleting cookies
Create a new PHP document <?php # logout.php
Check for the existence of a user_id cookie if it is present, delete both cookies. // If no cookie is present, redirect the user. if (!isset($_COOKIE['user_id'])
Summary
Define cookies and session Create a Cookie: setcookie() Retrieve a Cookie Value: PHP $_COOKIE How to Delete a Cookie? Starting a PHP Session: The session_start() function must appear BEFORE the <html> tag: Destroying a Session: use the unset() or the session_destroy() function
Pros and Cons of Cookies and Sessions
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Copyright 2009 Pearson Education,
Slide 11-206
Inc.
Slide 11-206
How has the growth of social networking enabled the creation of more specific niche sites? What are some examples of social network sites with a financial or business focus? Describe some common features and activities on these social networking sites.
Slide 11-207
Internet began as community building technology for scientists, researchers The Well Early communities limited to bulletin boards, newsgroups 2002: Mobile Internet devices, blogs, sharing of rich media began new era of social networking Social networking one of most common
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-208
Area online where people who share common ties can interact with one
Involve:
A group of people Shared social interaction Common ties among members People who share an area for some period of time
e.g. MySpace, Friendster, Flickr, Facebook Portals and social networks moving closer together as portals add social networking features and community Copyright 2009 Pearson Slide 11-209 Education, Inc. Publishing as Prentice Hall sites add portal-like services
Top 10 social networks account for over 90% social networking activity
MySpace: 50% of all social networking activity Users: Over 50% over 35, wealthy, with college degrees MySpace: 60 million/month Yahoo: 133 million/month
Unique visitors
Advertising revenue
Top 4 portals generate $12 billion annually Social networking sites: $1.4 billion
Slide 11-210
Early networking sites relied on subscriptions; today social networks rely primarily on advertising
General communities:
Offer opportunities to interact with general audience organized into general topics Advertising supported by selling ad space on pages and videos
Practice networks:
Offer focused discussion groups, help and knowledge related to area of shared practice or non-profit; Slide 11-211 advertising or user rely on
donations
Offer focused discussion groups based on shared interest in some specific subject Usually advertising supported
Affinity communities:
Offer focused discussion and interaction with other people who share same affinity (self or group identification) Advertising and revenues from sales of products
Sponsored communities:
Created by government, non-profit or for-profit organizations for purpose of pursuing organizational goals
Slide 11-212
LinkedIn display business profile and accomplishment StockTickr stock performance Duedee users rated against their virtual portfolio TradeKing to view trading styles Motley Fool online stock investment services
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-213
DailyStrength for healthcare LawLink for law practitioners Sermo physicians INMobile wireless industry executives AdGabber advertising professionals
Slide 11-214
Profiles Friends network Network discovery Favorites E-mail Storage Instant messaging
Message boards Online polling Chat Discussion groups Experts online Membership management tools
Slide 11-215
Insight on Technology
What does Mark Zuckerberg, Facebooks CEO, mean by social operating system? Why have Facebook applications become so popular? Do they have any limitations? How has Google responded? Which core functions can their programs
Slide 11-216
Online Auctions
Online auction sites among the most popular consumer-to-consumer sites on the Internet eBay: Market leader Several hundred different auction sites in U.S. alone
Established portals and online retail sites increasingly are adding auctions to their sites
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-217
Dynamic pricing
Prices based on demand characteristics of customer and supply situation of seller Bundling
Trigger pricing Utilization pricing
Slide 11-218
Personalization pricing
Auctions
B2C auctions
Business owns assets; often used for excess goods $19 billion gross revenue 2008
Insight on Society
What is dynamic pricing? What are the various types of dynamic pricing?
Revenues
Figure 11.3, Page 724
SOURCES: eMarketer, 2005; Jupiter Research, 2001; authors estimates. Copyright 2009 Pearson Slide 11-221
Education, Inc. Publishing as Prentice Hall
Benefits of Auctions
General
Liquidity Price discovery Price transparency Market efficiency Lower transaction costs Consumer aggregation Network effects
warehouse costs
Slide 11-222
For market-makers
No inventory, Copyright 2009 Pearson
Education, Inc. Publishing as Prentice Hall
Fulfillment costs
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-223
Last much longer (usually a week) Variable number of bidders who come and go from auction arena
Slide 11-224
Uniform pricing rule: Multiple winners who all pay the same price
Discriminatory pricing rule: Winners pay different amount depending on what they bid
Bid rigging
Slide 11-225
Slide 11-226
Types of Auctions
English auctions:
Uses a clock that displays starting price Clock ticks down price until buyer stops it
Slide 11-227
Pioneered by Priceline Users specify what they are willing to pay for goods or services and multiple providers bid for their business not descend and are fixed
Slide 11-228
Facilitate group buying of products at dynamically adjusted discount prices based on high volume purchases Based on two principles
Sellers are more likely to offer discounts to buyers purchasing in volume Buyers increase their purchases as prices fall
Auction Aggregatorsuse Web crawlers to search thousands of Web auction sites and accumulate information on products, bids, auction duration, etc.
Factors to consider
Type of auction
Initial pricing Bid increments Auction length Number of items Price allocation rule Closed vs. open bidding
Slide 11-230
Profit to seller: A function of arrival rate, auction length, and number of units at auction
Auction prices not necessarily the lowest
Reasons include herd behavior (tendency to gravitate toward, and bid for, auction listing with one or more existing bids) Winners regret Sellers lament Losers lament
Markets fail to produce socially desirable outcomes in four situations: information asymmetry, monopoly power, public goods, and externalities.
Auction markets prone to fraud
Portals: most frequently visited sites on the Web Gateways to the 40 - 50 billion Web pages
Slide 11-234
Insight on Business
How many different kinds of portals are there? How do portals make money? What are the strengths of the top four portals: Yahoo, Google, MSN and AOL? Why did Google link up with AOL when AOL was losing audience share?
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 11-235
Attempt to attract very large general audience and then retain it on-site by providing in-depth vertical content channels E.g. Yahoo!, MSN
Community (affinity group); e.g. iVillage.com Copyright 2009 Pearson Slide 11-236 Education, Inc. Publishing as Focused content; e.g. ESPN.com Prentice Hall
Two General Types of Portals: General Purpose and Vertical Market Portals
Figure 11.7, Page 747
Slide 11-237
Tenancy deals
Commissions on sales
Subscription fees
Vision: Global Internet communications, commerce and media company Business model: Earns money from advertising, premium content sales, commissions and corporate services Financial analysis: Revenues continue to grow; operating margins positive but falling Strategic analysis
Growth through acquisition Competition: Google, Microsoft, Time Warner/AOL Outsources technology
SUMMARY
Social Networks General communities Practice networks Interest-based social networks Affinity communities Sponsored communities Online Auctions Dynamic pricing: Prices based on demand characteristics of customer and supply situation of seller Types of dynamic pricing 1. Bundling 2. Trigger pricing 3. Utilization pricing 4. Personalization pricing Types of Auctions English auctions Traditional Dutch auction Dutch Internet auction Name Your Own Price Auctions Group Buying Auctions (Demand Aggregators) Professional Service Auctions Auction Aggregator
Types of Portals General purpose portals Vertical market portals Community (affinity group) Focused content Portal Business Models ISP services General advertising revenue Tenancy deals Commissions on sales Subscription fees
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall
Slide 11-240
Chapter 1
Overview of Electronic Commerce
Learning Objectives
1.
2.
3.
4.
5.
Chapter 1
Define electronic commerce (EC) and describe its various categories. Describe and discuss the content and framework of EC. Describe the major types of EC transactions. Describe the digital revolution as a driver of EC. Describe the business environment as a driver of EC.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall
242
Learning Objectives
6.
7.
8. 9.
10.
Describe some EC business models. Describe the benefits of EC to organizations, consumers, and society. Describe the limitations of EC. Describe the contribution of EC to organizations responding to environmental pressures. Describe online social and business networks.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 243
Chapter 1
electronic commerce (EC) The process of buying, selling, transferring, or exchanging products, services, or information via computer networks.
Chapter 1
244
e-business A broader definition of EC that includes not just the buying and selling of goods and services, but also servicing customers, collaborating with business partners, and conducting electronic transactions within an organization.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 245
Chapter 1
EC Organizations
Chapter 1
brick-and-mortar (old economy) organizations Old-economy organizations (corporations) that perform their primary business off-line, selling physical products by means of physical agents. virtual (pure-play) organizations Organizations that conduct their business Copyright activities solely2009 Pearson Education, Inc. online. Publishing as Prentice Hall
246
click-and-mortar (click-and-brick) organizations Organizations that conduct some ecommerce activities, usually as an additional marketing channel.
Chapter 1
247
1.1
Chapter 1
248
intranet An internal corporate or government network that uses Internet tools, such as Web browsers, and Internet protocols. extranet A network that uses the Internet to link multiple intranets.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 249
Chapter 1
electronic market (e-marketplace) An online marketplace where buyers and sellers meet to exchange goods, services, money, or information.
Chapter 1
250
Interorganizational information systems (IOSs) Communications systems that allow routine transaction processing and information flow between two or more organizations. intraorganizational information systems Communication systems that enable e-commerce activities to go on within individual organizations.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 251
Chapter 1
Chapter 1
252
business-to-business (B2B) E-commerce model in which all of the participants are businesses or other organizations. business-to-consumer (B2C) E-commerce model in which businesses sell to individual shoppers.
Chapter 1
253
e-tailing Online retailing, usually B2C. business-to-business-to-consumer (B2B2C) E-commerce model in which a business provides some product or service to a client business that maintains its own customers.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 254
Chapter 1
consumer-to-business (C2B) E-commerce model in which individuals use the Internet to sell products or services to organizations or individuals who seek sellers to bid on products or services they need. mobile commerce (m-commerce) E-commerce transactions and activities conducted in a wireless environment.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 255
Chapter 1
Chapter 1
location-based commerce (lcommerce) M-commerce transactions targeted to individuals in specific locations, at specific times. intrabusiness EC E-commerce category that includes all internal organizational activities that involve the exchange of goods, services, or information among various units and individuals in an organization.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall
256
Chapter 1
business-to-employees (B2E) E-commerce model in which an organization delivers services, information, or products to its individual employees. collaborative commerce (c-commerce) E-commerce model in which individuals or groups communicate or collaborate online. consumer-to-consumer (C2C) E-commerce model in which consumers
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall
257
Chapter 1
peer-to-peer Technology that enables networked peer computers to share data and processing with each other directly; can be used in C2C, B2B, and B2C e-commerce. e-learning The online delivery of information for purposes of training or education. e-government E-commerce model in which a government entity buys or provides goods, services, or information from 2009to businesses or individual or Pearson Education, Inc. Copyright Publishing as Prentice Hall citizens.
258
exchange A public electronic market with many buyers and sellers. exchange-to-exchange (E2E) E-commerce model in which electronic exchanges formally connect to one another for the purpose of exchanging information.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 259
Chapter 1
Chapter 1
260
Web 2.0 The second-generation of Internetbased services that let people generate content, collaborate, and share information online in perceived new wayssuch as social networking sites, wikis, communication tools, and folksonomies.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 261
Chapter 1
Chapter 1
262
digital economy An economy that is based on digital technologies, including digital communication networks, computers, software, and other related information technologies; also called the Internet economy, the new economy, or the Web economy.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 263
Chapter 1
The digital revolution accelerates EC mainly by providing competitive advantage to organizations. The digital revolution enables many innovations
Chapter 1
264
The Business Environment Impact Model Business Pressures and Opportunities Organizational Response Strategies
Chapter 1
265
Chapter 1
266
EC BUSINESS MODELS
business model A method of doing business by which a company can generate revenue to sustain itself.
Chapter 1
267
EC BUSINESS MODELS
tendering (bidding) system Model in which a buyer requests would-be sellers to submit bids; the lowest cost or highest value bidder wins.
name-your-own-price model Model in which a buyer sets the price he or she is willing to pay and invites sellers to supply the good or service at that price.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 268
Chapter 1
EC BUSINESS MODELS
Chapter 1
affiliate marketing An arrangement whereby a marketing partner (a business, an organization, or even an individual) refers consumers to the selling companys Web site. viral marketing Word-of-mouth marketing in which customers promote a product or service to friends or others. Copyright 2009 Pearson Education, Inc. 269
Publishing as Prentice Hall
EC BUSINESS MODELS
group purchasing Quantity (aggregated) purchasing that enables groups of purchasers to obtain a discount price on the products purchased.
Chapter 1
SMEs Small-to-medium enterprises. e-co-ops Another name for online group purchasing organizations. 2009 Pearson Education, Inc. Copyright
Publishing as Prentice Hall
270
EC BUSINESS MODELS
customization Creation of a product or service according to the buyers specifications. personalization The creation of a service or information according to specific customer specifications.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 271
Chapter 1
EC BUSINESS MODELS
Chapter 1
Electronic marketplaces and exchanges Information brokers (infomediaries) Bartering Value-chain integrators Value-chain service providers Supply chain improvers Social networks, communities, and blogging Negotiation
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall
272
EC BUSINESS MODELS
virtual world A user-defined world in which people can interact, play, and do business. The most publicized virtual world is Second Life.
Chapter 1
273
THE BENEFITS OF EC
Chapter 1
274
Technological Limitations Nontechnological Limitations social networks Web sites that connect people with specified interests by providing free services such as photo presentation, e-mail, blogging, and so on. Business-Oriented Networks Revenue Models2009 Pearson Education, and Business of Social Inc. Copyright 275 Publishing as Prentice Hall Networks
Chapter 1
digital enterprise A new business model that uses IT in a fundamental way to accomplish one or more of three basic objectives: reach and engage customers more effectively, boost employee productivity, and improve operating efficiency. It uses converged communication and computing technology in a way that improves business processes.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 276
Chapter 1
corporate portal A major gateway through which employees, business partners, and the public can enter a corporate Web site.
Chapter 1
277
Managerial Issues
1.
2. 3.
4.
5.
6.
Is it real? Why is B2B e-commerce so attractive? There are so many EC failureshow can one avoid them? How can we exploit social/business networking? What should be my companys strategy toward EC? What are the top challenges of EC?
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 278
Chapter 1
Summary
1.
2. 3. 4. 5.
Definition of EC and description of its various categories. The content and framework of EC. The major types of EC transactions. The role of the digital revolution. The role of the business environment as an EC driver.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall 279
Chapter 1
Summary
6.
7.
8. 9.
The major EC business models. Benefits of EC to organizations, consumers, and society. Barriers to EC. Social and business online networks.
Chapter 1
280
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America.
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Copyright 2009 Pearson Education,
Slide 2-282
Inc.
Slide 2-282
Business model
Business plan
Slide 2-284
Slide 2-285
Slide 2-285
Value Proposition
Defines how a companys product or service fulfills the needs of customers Questions to ask:
Why will customers choose to do business with your firm instead of another? What will your firm provide that others do not or cannot?
Prentice Hall
Slide 2-286
Revenue Model
Describes how the firm will earn revenue, generate profits, and produce a superior return on invested capital
Major types:
Revenue Model
Revenue Model Examples Revenue source
Advertising
Subscription
Yahoo
WSJ.com Consumerreports.org
Transaction fee
Sales
eBay E*Trade
Affiliate
MyPoints
Slide 2-288
Market Opportunity
Refers to a companys intended marketspace and overall potential financial opportunities available to the firm in that marketspace
Marketspace
Defined by revenueSlide 2-291 potential in each of market niches in which company hopes to
Slide 2-291
Competitive Environment
Refers to the other companies selling similar products and operating in the same marketspace. Also refers to the presence of substitute products and potential new entrants, as well as power of customers and suppliers
Influenced by:
Number of active competitors Each competitors market share Competitors profitability Competitors pricing
Slide 2-292
Competitive Advantage
Achieved when a firm can produce a superior product and/or bring product to market at a lower price than most, or all, of competitors
Perfect market: No competitive advantages or asymmetries Leverage: When a company uses its competitive advantage to achieve more advantage in surrounding markets
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-293
Slide 2-293
Market Strategy
Plan that details how a company intends to enter a new market and attract customers
Best business concepts will fail if not properly marketed to potential customers
Slide 2-294
Slide 2-294
Organizational Development
Plan that describes how the company will organize the work that needs to be accomplished
Slide 2-295
Slide 2-295
Management Team
Employees of the company responsible for making the business model work Strong management team gives instant credibility to outside investors Strong management team may not be able to salvage a weak business model, but should be able to change the model and redefine the business as it becomes necessary
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-296
Slide 2-296
No one correct way We categorize business models according to e-commerce sector (B2C, B2B, C2C) Type of e-commerce technology used can also affect classification of a business model
i.e., m-commerce
Slide 2-297
Slide 2-297
Categories of B2C
1.
2. 3. 4. 5.
6.
7.
Portal E-tailer Content provider Transaction broker Market creator Service provider Community provider
Slide 2-298
Offers powerful search tools plus an integrated package of content and services
Typically utilizes a combined subscription/advertising revenues/transaction fee model Today, seen as destination site rather than gateway
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall
Slide 2-299
Slide 2-299
Slide 2-300
Variations:
Slide 2-301
Slide 2-301
Slide 2-302
Uses Internet technology to create markets that bring buyers and sellers together
Examples:
Priceline eBay
Slide 2-303
Value proposition
Revenue models
Slide 2-304
Creates online environment (social network) where people with similar interests can transact and communicate. Typical revenue model: Hybrid
Including advertising fees, subscription fees, sales revenues, transaction fees, affiliate fees
Examples:
MySpace Facebook Copyright 2009 Pearson Education, Inc. Publishing iVillage as Prentice Hall
Slide 2-305
Slide 2-305
Categories of B2B
1.
2. 3. 4. 5.
Slide 2-307
Supplies products and services directly to individual businesses Owned by one company seeking to serve many customers Example: Grainger.com
Slide 2-308
Slide 2-308
Includes B2B service providers, application service providers (ASPs) Transaction fees, usage fees, annual licensing fees Software that helps firms organize procurement process
Slide 2-309
Revenue models:
Ariba
Slide 2-309
Electronic digital marketplace where suppliers and commercial purchasers can conduct transactions Usually owned by independent firms whose business is making a market Revenue model: Transaction fees Usually serve a single vertical industry Number of exchanges has fallen dramatically
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-310
Slide 2-310
Industry-owned vertical marketplaces that serve specific industries (e.g. automobile, chemical, floral, logging)
Supply smaller number of companies with product and services relevant to industry Sponsored by powerful industry players Strengthen traditional purchasing behavior
Slide 2-312
Digital networks designed to coordinate the flow of communications among firms engaged in business together Single firm network: Most common form
Wal-Mart
Slide 2-313
Consumer-to-Consumer (C2C)
eBay, Half.com
Peer-to-Peer (P2P)
Kazaa, Cloudmark
M-commerce:
E-commerce models using wireless technologies PayPal Mobile Checkout, AOL MovieFone Technology platform continues to evolve
Slide 2-314
Slide 2-314
Slide 2-315
Slide 2-315
How the Internet and the Web Change Business: Strategy, Structure, and Process
E-commerce changes nature of players in an industry and their relative bargaining power by changing:
Basis of competition among rivals Barriers to entry Threat of new substitute products Strength of suppliers Bargaining power of buyers
Slide 2-317
Slide 2-317
Set of activities performed in an industry by suppliers, manufacturers, transporters, distributors, and retailers that transform raw inputs into final products and services Internet reduces cost of information and other transactional costs for manufacturers, distributors, customers Leads to greater operational efficiencies, lowering prices, adding value for
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-318
Slide 2-318
Slide 2-319
Slide 2-319
Set of activities that a firm engages in to create final products from raw inputs Internet effect:
Slide 2-320
Slide 2-320
Slide 2-321
Slide 2-321
Networked business ecosystem that uses Internet technology to coordinate the value chains of business partners within an industry, or within a group of firms Coordinates a firms suppliers with its own production needs using an Internet-based supply chain management system
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 2-322
Slide 2-322
Slide 2-323
Slide 2-323
Business Strategy
Set of plans for achieving superior long-term returns on the capital invested in a business firm (i.e., a plan for making a profit in a competitive environment) Four generic strategies
Slide 2-324
This strategy emphasizes efficiency by producing high volumes of standardized products. The product is often a basic no-frills product that is produced at a relatively low cost and made available to a very large customer base. Maintaining this strategy requires a continuous search for cost reductions
Slide 2-325
Differentiation is aimed at the broad market that involves the creation of a product or services that is perceived throughout its industry as unique. Charge a premium for its product design, brand image, technology, features, dealers, network, or customers service. Brand loyalty lowers customers'
Slide 2-326
In this strategy the firm concentrates on a select few target markets. It is also called a segmentation strategy or niche strategy. The firm typically looks to gain a competitive advantage through product innovation and/or brand marketing rather than efficiency.
Slide 2-327
Summary
Business model: Set of planned activities designed to result in a profit in a marketplace Business plan: Describes firms business model Elements of Business model 1. Value proposition 2. Revenue model ads, subscription fee, transaction fee, affiliates, sales 3. Market opportunity 4. Competitive environment 5. Competitive advantage 6. Market strategy 7. Organizational development 8. Management team E-Commerce Models 1. B2C Portal: Horizontal / vertical E-tailer: Virtual merchant / Brick and click / Catalog merchant / Manufacturer-direct 2. B2B e-distributor, e-procurement, Exhanges, Industry consortia, private industrial network 3. Others C2C, P2P,M-Commerce Impact: Basis of competition among rivals Barriers to entry Threat of new substitute products Strength of suppliers Bargaining power of buyers Business strategy:: Differentiation Cost Slide 2-328 Focus
Value chains Industry value chains Firm value chains Leads to greater operational efficiencies, lowering prices, adding value for customers
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Copyright 2009 Pearson Education,
Slide 9-329
Inc.
Social shopping Online retail increasingly profitable Buying online becomes normal, mainstream experience Selection of goods increases, including luxury and customized goods Average annual amount of purchases increases Specialty retail sites show most rapid growth
Slide 9-330
Increased use of interactive multimedia marketing Retail intermediaries strengthen in many areas Retailers increasingly efficient at integrating multiple channels Personalized goods, especially in apparel, become financially successful Online shopping becomes more multiseasonal
Slide 9-331
Retail industry divided into nine segments, each of which offers different opportunities for online retail
Informational opportunities
Consumer durables largest segment, then general merchandise Mail order/telephone order (MOTO) sector most similar to online retail sector
Sophisticated Copyright 2009 Pearson
Education, Inc. Publishing as Prentice Hall
Greatly reduced search and transaction costs would result in customers using Web to find lowest prices Market entry costs would be much lower than those for physical storefronts, and online merchants would be more efficient than offline competitors Traditional offline physical store merchants would be forced out of business Some industries would become disintermediated as manufacturers built direct relationship with consumer Few of these assumptions were correctstructure of retail marketplace has not been revolutionized Internet has created new venues for multichannel firms and supported a few pure-play merchants
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-335
Online retailing segment, although smallest segment of retail industry, is growing at exceptionally fast rate Online retail revenues: $146 billion in 2008 Primary beneficiaries of growing consumer support: Established offline retailers with an online presence as well as first mover dot-com companies Top online retailers: Amazon, Staples,
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-336
Multi-Channel Integration
Ability of offline traditional firms to integrate Web operations with physical store operations Provides integrated shopping experience Leverages value of physical store Examples: Wal-Mart, Target , JCPenney Types of integration
Slide 9-338
Economic viability: Ability of firms to survive as profitable business firms during a specified period (i.e. 1-3 years) Two business analysis approaches:
Strategic analysis
Financial analysis
How firm is performing Statement of operations: How much money (or loss) the firm is achieving based on current sales Copyright 2009 Pearson Slide 9-339 and costs. Education, Inc. Publishing as
Prentice Hall
Barriers to entry Power of suppliers Power of customers Existence of substitute products Industry value chain Nature of intra-industry competition Firm value chain Core competencies Synergies Technology Social and legal challenges
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-340
Revenues: Growing and at what rate? Cost of sales: Compared to revenues Gross margin: Gross profit divided by net sales Operating expenses Operating margin: Indication of companys ability to turn sales into pre-tax profit after operating expenses are deducted
Slide 9-341
Current assets Current liabilities Ratio of current assets to liabilities (working capital)
Long-term debt
Slide 9-342
Single channel Web firms that generate almost all revenues from online sales e.g. Amazon
Bricks-and-clicks
Companies with physical stores as primary retail channel, but also online offerings
Slide 9-343
Catalog merchant
Established companies that have national offline catalog operation as largest retail channel, but also have online capabilities e.g. Lands End, L.L. Bean, Victorias Secret
Manufacturer-direct
Single or multi-channel manufacturers who sell directly online to consumers without intervention of retailers
Slide 9-344
Vision: Earths biggest selection, most customer-centric Business Model: Amazon Retail and Amazon Services (merchant and developer services) Financial Analysis: Greatly improved, but not yet consistently profitable; still heavy long-term debt Strategic Analysis/Business strategy: Maximize revenue, cut costs Strategic Analysis/Competition: Online and offline general merchandisers Strategic Analysis/Technology: Largest, most sophisticated collection of online retailing technologies available Strategic Analysis/Social, Legal: Antitrust, sales tax, patent lawsuits; ToysRUs lawsuit Future Prospects: Long-term profitability still uncertain
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-345
Online retail fastest growing channel, has fastest growing consumer base, growing penetration rate across many categories of goods Many online retail firms have begun to raise prices Disintermediation has not occurred, and most manufacturers use Web primarily as an informational resource Most significant online growth has been that of offline general merchandiser giants who are focusing on extending brand to online channel Second area of rapid growth: specialty merchants
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-346
Insight on Technology
What do shopping bots and comparison sites offer consumers? Why are shopping bots more successful with hard goods than soft goods? How can shopping bots compare luxury goods? How will adding content to comparison sites help consumers?
Slide 9-347
Service sector: Largest and most rapidly expanding part of economies of advanced industrial nations In the United States, services employs about 76% of labor force; accounts for $7.7 trillion of GDP in 2008
Slide 9-348
Service occupations:
Concerned with performing tasks in and around households, business firms, and institutions
Provide services to consumers, businesses, governments, and other organizations
Service industries:
Prentice Hall
Transaction brokers Hands-on service provider Knowledge- and information-intense, which makes them uniquely suited to ecommerce applications Amount of personalization and customization required differs depending on type of service
Slide 9-350
Online financial services sector example of e-commerce success story, but success is somewhat different from what had been predicted Brokerage industry transformed Effects less powerful in banking, insurance, real estate Multi-channel established financial services firms are showing fastest growth
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-351
Financial Reform Act of 1998 amended GlassSteagall Act and allows banks, brokerages, and insurance firms to merge
Slide 9-352
Slide 9-353
Consumers attracted to online financial sites because of desire to save time and access information rather than save money Most online consumers use financial services firms for mundane financial management Greatest deterrents are fears about security and confidentiality
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-354
Online consumers prefer multi-channel firms with physical presence Multi-channel firms
Lower customer acquisition, conversion, and retention costs Rely on Web sites, advertising to acquire customers Users utilize services more intensively Users shop more, are more price-driven and
Slide 9-357
Financial portals
Provide comparison shopping services, independent financial advice and financial planning No financial services, revenues from advertising
Account aggregation
Early vision: The historically local, complex, and agentdriven real estate industry would be transformed into a disintermediated marketplace where buyers and sellers would transact directly However, major impact is influencing of purchases offline
Impossible to complete property transaction online Main services are online property listings, loan calculators, research and reference material
Despite revolution in available information, there has not been a revolution in the industry value chain
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-359
One of most successful B2C e-commerce segments; attracts largest audience and slice of B2C revenues Internet becoming most common channel used to research travel and book reservations 2007: First year online bookings greater than offline
2008: Online travel bookings $105 billion; expected to grow to $162 billion by 2012
Popular because they offer more convenience (onestop content, commerce, community, customer service) than traditional travel agents For suppliers, offers a singular, focused customer pool that can be efficiently reached
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-361
Information-intensive product Electronic producttravel arrangements can be accomplished for the most part online Does not require inventory
Airline tickets:
Leisure/unmanaged business travel Managed business travel expected to be a major growth area as corporations seek better control of corporate travel expenses
Slide 9-366
One of top players in online travel services, generating revenues of $2.7 billion in 2007 Vision: Create global travel marketplace Business model: Agency model and merchant model
Acquire complementary and competing travel companies, broaden scope of offerings, and expand into foreign markets, especially Asia
Slide 9-367
Strategic Analysis/Competition
Other online commercial travel Web sites (e.g. Travelocity) Direct suppliers of travel services Suppliers of inventory
Strategic Analysis/Technology
Developed a multi-layered platform capable of handling large transaction volumes, powerful search tools to assist consumers
Future Prospects
Challenges: Education, Inc. Publishing as
Prentice Hall Copyright 2009 Pearson
Next to travel services, one of Internets most successful online services. Dominated by CareerBuilder, Monster, and Yahoo HotJobs Online recruiting provides more efficient and costeffective method of linking employers and potential employees, while reducing total time-to-hire Enables job hunters to more easily build, update, and distribute resumes while gathering information about prospective employers and conducting job searches Ideally suited for Web due to information-intense nature of process
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall Slide 9-369
Saves time and money for both job hunters and employers For employers:
Expand geographic reach of search, lower cost, and result in faster hiring decisions Make resumes more widely available, and provides a variety of related job-hunting services
Slide 9-370
One of most important functions: Ability to establish market prices and terms
Copyright 2009 Pearson Education, Inc. Publishing as Prentice Hall
Executive search:
SHOPPING CART
Overview
A shopping cart is a software application that typically runs on the computer where your Web site is located (the Web server), and allows your customers to do things such as searching for a product in your store catalog, adding a selected product to a basket, and placing an order for it. The shopping cart "integrates" with the rest of your Web site. In other words, there are typically links on your Web pages that customers can click on, and which allow them to perform some of the functions described above.
Shopping carts are written in a variety of different programming languages. Some of them provide full access to the "source code", thus allowing experienced programmers to make modifications to the system features, some others don't. Some shopping carts run on Windows Web servers, some on Unix, others on both. In most cases, you can place the shopping cart on your Web server simply by transferring its files there using any FTP software.
Typically, all shopping carts share the following structure. A shopping cart normally includes:
a database that stores information such as product details, customer data, order information, etc. a storefront that displays this information to store visitors (e.g. product detail pages, search pages, checkout pages, etc.) an administration area that allows you, the store administrator, to manage your store. For example, this is where you add products, set up shipping & payment options, process orders, etc.
Because most of the information is contained in a database, the shopping cart creates pages in "real time" when a customer visits an ecommerce store and requests a specific page. The shopping cart pages don't exist until a customer requests one. The page is dynamically generated by the Web server by retrieving data from the database. So a store that has 4,000 products, does not actually store 4,000 product pages on the Web server. The pages are created on the fly when a customer visits the store and, for example, looks for a specific product.
ProductCart uses a technology called Active Server Pages to created the store pages from a database. Other shopping carts may use different technology, such as PHP, CGI, Ruby on Rails, or Cold Fusion. The process remains the same. Information is retrieved from a database, and displayed to the customer within the graphical interface that the store administrator has created for the store. Different shopping carts offer store administrators different levels of flexibility in setting up how these pages will look.
the storefront, which is what your customers will see (the catalog, the search pages, the checkout pages, etc.), the administration area, which is what you will use to manage the store.
Although you find both components in virtually all ecommerce applications available on the market, the features that each of them offers vary substantially.
Storefront
A store catalog that is easy to browse and that presents product information is a way that is both useful and graphically pleasing. A search feature that allows customers to quickly locate a specific product. The more filters are available on the search page, the better (e.g. price, part number, description, etc.) A customer service area where existing customers can change their account information, view previous orders, etc. There should also be a way for customers to retrieve a lost password. Special pages where customers can easily find products that are on sale, featured products, products that belong to the same brand, etc.
Administration area
A way to easily set general store settings such as the way products should be displayed (e.g. how many products will be shown on each catalog page), the currency and date format to be used, etc. A module to create and manage product categories, and order the way in which they are displayed on the storefront. A module to create and manage products, and assign them to categories. To improve productivity, there should be tools that allow you to change settings across multiple products at once (e.g. change the price for all products in the "tennis shoes" category).
A way to assign options to products (e.g. color and size), with the ability to set price changes that are dependent on the selected option (e.g. if you select an XXL size shirt, then you pay an extra $5). To improve productivity, there should be tools that allow you to assign the same options to multiple products at once. Flexible ways to set multiple shipping (e.g. UPS Ground is free for order over $100), and payment options (e.g. real time credit card processing, COD, and NET 30, but the last one only for wholesale customers). A module to manage orders effectively (pending, processed, shipped, returned, etc.).
How will your customers get to the product catalog? How can you make your home page link to the "Monthly Specials" page, created dynamically by the shopping cart? And how can you make the pages that the shopping cart creates look the same as your "About us" or "Contact us" page? The look and feel of your online store, and the way it merges with the rest of your Web site, are crucial elements of a successful ecommerce store.
Typically, you will be able to create HTML links that take a user for any HTML page that you may create for your Web site (e.g. the "about us" page), to a page generated dynamically by the shopping cart, which retrieves information in real time from the database that contains your store catalog and store settings. For example, the "About Us" page could contain a link to a page created by the shopping cart that shows products that are on sale in that particular month (assuming that the shopping cart does have the ability to do so).
How easy it is to place such links into your HTML pages varies however from application to application. Make sure to select a shopping cart that allows to do so quickly and easily. As for the graphical interface used by the shopping cart to display the store page, some shopping carts limit you to using pre-formatted templates. Stay away from that kind of ecommerce software. Choose a shopping cart that does not use templates, but rather allows you to use your own Web site design as the graphical interface for the store pages.
Checking Out
Once the shopper has filled his cart, he hits the "Checkout" button and is sent to this page. All of his "Shopping Cart" details (except for the product descriptions) are displayed here. There is also a form into which he enters his delivery details.
Lets take as our example a bookseller. They are not the beststocked bookseller in the world, having as they do only three titles in stock, but it is enough for our example. Lets create the database and add some stock:
The cart we are going to build should be pretty familiar to most internet users. It will provide a means of displaying a message on every page of the site (along the lines of You have 5 items in your shopping cart), which when clicked will take the customer to a list of the items in the cart; each item may be removed or have its quantity updated. As all of our stock details are stored in the database, the only piece of information that we need to store about each customer is the id of each product they have added to their cart. To do this, we are going to use PHPs built-in session handling capabilities.
The default behaviour of PHP sessions is to store the session ID (a long string of numbers and letters that identifies you to the server) as a cookie on your computer; however, even if you have cookies disabled this functionality will still work PHP will instead append the session ID to each link on the site (in the form mypage.php?PHPSESSID=) so that it can continue to accurately track visitors from page to page.
We will store the contents of the shopping cart as a comma-separated list of product ids in a session named (unsurprisingly) cart for example, a cart containing 1,1,3,1,2 has four items; three of product #1, and one each of products #2 and #3. Firstly, lets create the code to display the You have X items message on every page:
Function writeShoppingCart()
function writeShoppingCart() { $cart = $_SESSION['cart']; if (!$cart) { return '<p>You have no items in your shopping cart</p>'; } else { // Parse the cart session variable $items = explode(',',$cart); $s = (count($items) > 1) ? 's':''; return '<p>You have <a href="cart.php">'.count($items).' item'.$s.' in your shopping cart</a></p>'; } }
Function writeShoppingCart()
This function first gets the value of the cart session variable into a local variable, mainly to save on typing. If the cart is empty, we return an appropriate message; if not, we use the explode() function to create an array of all the products in the cart, and then count() them and display the result (the $s variable is there to make plurals display correctly). Now we can display the correct message anywhere on the site: echo writeShoppingCart();
The shopping cart page itself (cart.php) can be arrived at in a couple of ways. The user may have clicked on the link created by the writeShoppingCart() function above; or, they may have clicked an Add to cart link on a product page. If it was the latter, we need to intercept that click and update our cart contents before displaying the new list of products simple enough, as all we need to do is append the id of the clicked product to the cart session variable. Our product links are going to look like this: <a href="cart.php?action=add&id=1">Add to cart</a> Dont worry about the action=add bit, well get to that later. The id can now be extracted from $_GET[id] and added to our cart:
$cart = $_SESSION['cart']; if ($cart) { $cart .= ','.$_GET['id']; } else { $cart = $_GET['id']; } $_SESSION['cart'] = $cart;
As in our example above, it is entirely possible that a customer might have more than one of a certain product in their cart. As we dont want to list duplicate items when we display the contents, we need to figure out a way to combine any of the same product into one entry (with a corresponding quantity attached).
$cart = $_SESSION['cart']; if ($cart) { $items = explode(',',$cart); $contents = array(); foreach ($items as $item) { $contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1; }
This time, after exploding the list of product ids, we have iterated through them to create a new array named $contents, which consists of key=>value pairs where the key is the product id and the value is the quantity of that product in the shopping cart. So to take our example above, a cart containing 1,1,3,1,2 would become an array where 1=>3, 2=>1, 3=>1.
Now that we have an accurate count of unique products, lets query the product database for each one and output its details into a table:
$total = 0; 2. $output[] = '<table>'; 3. foreach ($contents as $id=>$qty) { 4. $sql = 'SELECT * FROM books WHERE id = '.$id; 5. $result = $db->query($sql); 6. $row = $result->fetch();
1.
1.
2. 3.
4.
5.
extract($row); $output[] = '<tr>'; $output[] = '<td><a href="cart.php?action=delete&id= '.$id.'" class="r">Remove</a></td>'; $output[] = '<td>'.$title.' by '.$author.'</td>'; $output[] = '<td>£'.$price.'</td>';
1.
2.
3.
4. 5. 6.
7.
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>'; $output[] = '<td>£'.($price * $qty).'</td>'; $total += $price * $qty; $output[] = '</tr>'; } $output[] = '</table>'; $output[] = '<p>Grand total: £'.$total.'</p>';
Pretty simple stuff we iterate through the new $contents array and query the database for each product id. Then we output the relevant details for each product; title, author and price, and at the bottom we show the grand total for the order. For each item, weve also included a link to remove the item from the cart, a textbox containing the current quantity of that item, and a total price (obviously this will only differ from the base price if the quantity is not 1). The reason Im using $output[] = ... is that I am buffering the output into an array to print to the screen later.
Deleting a product
As shown above, the link to delete a product from the cart follows the same format as the add a product link:
href="cart.php?action=delete&id=1 ">Remove</a> Lets expand on the code from earlier by adding a switch() statement to handle the different things that might happen to our cart: Download this code
<a
Updating a product
Lastly, we are going to allow customers to update the contents of their shopping cart by manually changing the value in the quantity box for each product. To make this work, well wrap the shopping cart table in a <form> so that the update cart button will submit the form: Download this code
Note that, even though the form uses the POST method, its action includes a GET variable, action=update. Again, we can expand our previous code to process any quantity updates: Download this code
This looks quite complicated, but its fairly straightforward; we interrogate the contents of the $_POST array (which holds all our quantity values) and extract the relevant id and value pairs. For each product, we then delete all the existing instances of it, and re-insert the new quantity. There are a number of ways this could have been done for example, by counting the existing number of each product present in the cart and figuring out whether we needed to add or remove items but this seemed the easiest way to process the quantity updates.
Final function
And thats about it! A functional and easy shopping cart script heres the final function to display the contents of the cart:
Summary
Definition of shopping cart Structure of shopping cart: database, storefront, administration area Storefront contains: search catalog, search feature, customer service area, special pages Administration area features: products display, create & manage products categories, assign options to products, set shipping, manage orders