Dynamic Web Pages Ch 1 V1.0

Post on 18-Jan-2015

2067 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

 

Transcript

1

Chapter 1Chapter 1Chapter 1Chapter 1Site management Site management

&&Sending & Receiving data between pages.Sending & Receiving data between pages.

2

Dynamic web page decisions

• The first decision is to decide what scripting language you are going to write your dynamic pages in.– PHP: Generally uses an Apache

server with php. – ASP: Generally uses Microsoft

Internet Information Services (IIS), which has an asp engine incorporated.

3

How PHP Pages are Accessed and Interpreted

We will use WAMPS (Windows, apache, mysql, php server) and it will be locally installed on the lab machines.

2. Send Request for PHP file

6. Return Results

Please EnterAPhoneNumber

Submit Erase

1. Web Browser

Web Browser

Phone QueryResults:

That isJohn Doe'sPhoneNumber

7. Web Browser

Your PC(Internet connected)

WebServer(Internet connected)

Web ServerSoftware

3. Receiverequest, find

file and read it.

4. ExecutePHP

statements

5. Sendresultsback.

4

WAMPS• This web service has three servers;

– Apache– MYSQL – PHP

• Wamps will be located locally on the lab machines. So the lab machines will be a local and server machine.

5

Creating a PHP Script File and Saving It to a Local Disk

You can use a number of different editors to create your PHP script files. – The PHP script starts with a <?php tag and ends with

?>. – Between these tags is a single PHP print statement.

6

Alternative PHP Delimiters• You can alternatively start your PHP scripts

with the <script> tag as follows:<script language="PHP">

print ("A simple initial script");

</script>

• If have short_open_tag enabled in its configuration file, you can use <? and ?>.

• If asp_tags is enabled in the PHP configuration file, you can use <% and %> as delimiters.

A Little About PHP's Syntax

• Some PHP Syntax Issues: – Be careful to use quotation marks, parentheses,

and brackets in pairs. – Most PHP commands end with a semicolon (;).– Be careful of case.

– PHP ignores blank spaces.

7

Embedding PHP Statements Within HTML Documents

• One way to use PHP is to embed PHP scripts within HTML tags in an HTML document.

1.<html>2.<head> 3.<title>HTML With PHP Embedded</title> </head>4.<body> 5.<font size=5 color=”blue”>Welcome To My Page</font>6.<?php7. print ("<br> Using PHP is not hard<br>");8.?>9.and you can learn to use it quickly! 10. </body></html>

8

9

Using Backslash (\) to Generate HTML Tags with print()

• Sometimes you want to output an HTML tag that also requires double quotation marks. – Use the backslash (“\”) character to signal that

the double quotation marks themselves should beoutput:print ("<font color=\"blue\">");

– The above statement would output: <font color="blue">

10

Using Comments with PHP cripts

• Comments enable you to include descriptive text along with the PHP script.– Comment lines are ignored when the

script runs; they do not slow down the run-time.

– Comments have two common uses.• Describe the overall script purpose.• Describe particularly tricky script lines.

11

Using Comments with PHP Scripts

• Comment Syntax - Use //<?php

// This is a comment

?>

• Can place on Same line as a statement:<?php

print ("A simple initial script"); //Output a line

?>

12

Example Script with Comments

1. <html> <head>2. <title> Generating HTML From PHP</title> </head>3. <body> <h1> Generating HTML From PHP</h1>4. <?php5. //6. // Example script to output HTML tags7. //8. print ("Using PHP has <i>some advantages:</i>");9. print ("<ul><li>Speed</li><li>Ease of use</li><li>Functionality</li></ul>"); //Output bullet list10. print ("</body></html>");11. ?>

13

Alternative Comment Syntax

PHP allows a couple of additional ways to create comments.<?php

phpinfo(); # This is a built-in function

?>

• Multiple line comments. <?php/*

A script that gets information about the

PHP version being used.

*/

<? phpinfo(); ?>

14

Using PHP Variables• Variables are used to store and

access data in computer memory. • A variable name is a label used

within a script to refer to the data.

$cost = 4.25; $months = 12;

Name of variable Variables new value

15

Assigning New Values to Variables

• You can assign new values to variables:

$days = 3;

$newdays = 100;

$days = $newdays;

• At the end of these three lines, $days and $newdays both have values of 100.

16

Selecting Variable Names• You can select just about any set of

characters for a variable name in PHP, but they must:– Use a dollar sign ($) as the first character– Use a letter or an underscore character (_) as the

second character.

• Note:Try to select variable names that help describe their function. For example $counter is more descriptive than $c or $ctr.

17

Combining Variables and the print Statement

• That is, to print out the value of $x, write the following PHP statement:– print ("$x");

• The following code will output “Bryant is 6 years old”.$age=6;

print ("Bryant is $age years old.");

18

A Full Example ...

1. <html>2. <head> <title>Variable Example </title> </head>3. <body>4. <?php5. $first_num = 12;6. $second_num = 356;7. $temp = $first_num;8. $first_num = $second_num;9. $second_num = $temp;10. print ("first_num= $first_num <br>second_num=$second_num");11. ?> </body> </html>

19

Using Arithmetic Operators• You can use operators such as a plus sign (+)

for addition and a minus sign (–) for subtraction to build mathematical expressions.

• For example<?php

$apples = 12;

$oranges = 14;

$total_fruit = $apples + $oranges;

print ("The total number of fruit is $total_fruit");

?>

• These PHP statements would output “The total number of fruit is 26.”

20

Common PHP Numeric Operators

Table 2.1 Common PHP Numeric Operators

Operator Effect Example Result

+ Addition $x = 2 + 2; $x is assigned 4.

- Subtraction $y = 3; $y = $y – 1;

$y is assigned 2.

/ Division $y = 14 / 2;

$y is assigned 7.

* Multiplication $z = 4; $y = $z * 4;

$y is assigned 16.

% Remainder $y = 14 % 3; $y is assigned 2.

21

A Full Example1. <html>2. <head> <title>Variable Example </title> </head>3. <body>4. <?php5. $columns = 20;6. $rows = 12;7. $total_seats = $rows * $columns;8.9. $ticket_cost = 3.75;10. $total_revenue = $total_seats * $ticket_cost;11.12. $building_cost = 300;13. $profit = $total_revenue - $building_cost;14.15. print ("Total Seats are $total_seats <br>");16. print ("Total Revenue is $total_revenue <br>");17. print ("Total Profit is $profit");18. ?> </body> </html>

22

WARNING: Using Variables with Undefined Values

If you accidentally use a variable that does not have a value assigned to it will have no value (called a null value).When a variable with a null value is used in an expression PHP, PHP may not generatean error and may complete the expression evaluation. For example, the following PHP script will output x= y=4.

<?php$y = 3;$y=$y + $x + 1; // $x has a null valueprint ("x=$x y=$y");?>

23

Writing Complex Expressions

• Operator precedence rules define the order in which the operators are evaluated. For example,

$x = 5 + 2 * 6;

• The value of $x is either 42 or 17 depending on order of evaluation.

• Since multiplication evaluated before addition operations, this expression evaluates to 17.

24

PHP Precedence Rules

• PHP follows the precedence rules listed below.– First it evaluates operators within

parentheses.– Next it evaluates multiplication and

division operators.– Finally it evaluates addition and

subtraction operators.

25

PHP Precedence Rules• For example, the first 2

statements evaluate to 80 while the last to 180. – $x = 100 - 10 * 2;– $y = 100 - (10 * 2);– $z = (100 - 10) * 2;

26

A Full Example

1. <html>2. <head> <title>Expression Example </title> </head>

3. <body>4. <?php5. $grade1 = 50;6. $grade2 = 100;7. $grade3 = 75;8. $average = ($grade1 + $grade2 + $grade3) / 3;

9. print ("The average is $average");10. ?> </body> </html>

27

Working with PHP String Variables

• Character strings are used in scripts to hold data such as customer names, addresses, product names, and descriptions.

• Consider the following example.– $name="Christopher";– $preference="Milk Shake";

• $name is assigned “Christopher” and the variable $preference is assigned “Milk Shake”.

28

WARNING: Be Careful Not to Mix Variable Types

• Be careful not to mix string and numeric variable types.

• For example, you might expect the following statements to generate an error message, but they will not. Instead, they will output “y=1”.<?php

$x ="banana";

$sum = 1 + $x;

print ("y=$sum");

?>

29

Using the Concatenate Operator

• The concatenate operator combines two separate string variables into one.

• For example, – $fullname = $firstname . $lastname;

• $fullname will receive the string values of $firstname and $lastname connected together.

• For example, $firstname = "John";

$lastname = "Smith";

$fullname = $firstname . $lastname;

print ("Fullname=$fullname");

30

TIP; An Easier Way to Concatenate Strings

• You can also use double quotation marks to create

• concatenation directly, • For example,

• $Fullname2 = "$FirstName $LastName";• This statement has the same effect as• $Fullname2 = $FirstName . " " . $LastName;

31

The strlen() Function

• Most string functions require you to send them one or more arguments.

• Arguments are input values that functions use in the processing they do.

• Often functions return a value to the script based on the input arguments. For example$len = strlen($name);

Variable or value to work with

Name of functionReceives the number of

characters in $name

32

The strlen() Function Example

<?php $comments = "Good Job"; $len = strlen($comments); print ("Length=$len");

?>This PHP script would output “Length=8”.

33

The trim() Function

• This function removes any blank characters from the beginning and end of a string. For example, consider the following script:– <?php– $in_name = " Joe Jackson ";– $name = trim($in_name);– print ("name=$name$name");– ?>

34

The strtolower() and strtoupper() Functions

• These functions return the input string in all uppercase or all lowercase letters, respectively.

• For example, <?php$inquote = "Now Is The Time";$lower = strtolower($inquote);$upper = strtoupper($inquote);print ("upper=$upper lower=$lower");?>

• The above would output “upper=NOW IS THE TIME lower=now is the time”.

35

The substr() Function

$part = substr( $name, 0, 5);

Assign theextracted sub-string into thisvariable.

Extract from thisstring variable.

Starting position tostart extraction from.

Number of charactersto extract. (If omitted it willcontinue to extract until the endof the string.)

– Substr has the following general format:

36

The substr() Function• The substr() function enumerates character

positions starting with 0 (not 1), – For example, in the string “Homer”, the “H” would be

position 0, the “o” would be position 1, the “m” position 2, and so on.

• For example, the following would output “Month=12 Day=25”.

<?php

$date = "12/25/2002";

$month = substr($date, 0, 2);

$day = substr($date, 3, 2);

print ("Month=$month Day=$day");

?>

37

The substr() Function• As another example, consider the

following use of the substr() function– It does not include the third argument (and

thus returns a substring from the starting position to the end of the search string).<?php

$date = "12/25/2002";

$year = substr($date, 6);

print ("Year=$year");

?>

• The above script segment would output “Year=2002”.

38

Servers and files• The php files need to be located

on the server.• The location for wamps is C:\wamps\www\• All files must be place here.• In dreamweaver you will work on

files that are local on your storage space: f, h etc.

• When these local files are save they will automatically be uploaded to the server.

39

Dynamic Web pages requirements

• Create a local site: shown on the next slide.

• Check WAMPS is running. – On the lab machines sometimes the

IIS starts first and blocks the port. If this happens you must stop the IIS.

• Create a dynamic and testing site: shown on the following slides.

40

Creating a local site

Local folder is your H or F drive etc.

41

Creating a remote site

Note: You will have to create this folders, newlandStart. This can be done using the browse button. wamp\www\ is the default directory.

42

Creating a Testing Server

43

Transferring to the Remote server

• Click on the “expand show local & remote sites” button.

• Click on the “put files” button; the blue arrow.

44

Changing htm to php• Change all the htm &

html pages to php. • This is done by click

on the name in the file panel and changing the extension. (same as renaming in windows).

• An update screen will appear.

• Click ok.

45

Check the pages• Open each page one at a time

followed by the “f12” key to execute the page in the browser.

• Once all pages have been executed you should be able to test the links on each page.

• If the links are not working, check they are to the asp extension pages.

46

Using forms to send data.

• Overview: – In this section you will create pages

with embedded forms.– The forms will have objects, such as

text fields, submit buttons, radio buttons etc.

– The data in the form objects will be sent to the server and be displayed on another page.

47

Retrieving data• Overview:

– The are four ways of transferring data from one page to another.• Through a form with the post method.• Through a form with the get method.• Through a URL link• Through a cookie.

48

• HTML Forms are not part of PHP language but important way to send data to scripts

Creating HTML Input Forms

Text BoxRadio Buttons

Check Box

Select Box

Text Area

Submit/Reset button

49

Starting And Ending HTML Forms

<form action="http://webwizard.aw.com/~phppgm/program.php" method="post">

Program to start when form is submitted.

Place form elements between<form> and </form> tags.

.

.

.</form>

Format tosend data.

Forms end with </form>

• You can create HTML forms by using the HTML <form> and </form> tags.

50

Creating Form Buttons• You can create submit and reset buttons

by placing the following within <form> & </form> tags.

• The submit button will be labeled “Click To Submit”. The reset button will be labeled “Erase and Restart”.

<input type=”submit” value=”Click To Submit”> <input type=”reset” value=”Erase and Restart”>

Type ofbutton to create Button Label

51

Another Full Script Example1.<html>2.<head> <title> A Simple Form </title> </head>3.<body>4.<form action="http://webwizard.aw.com/~phppgm/First.php"

method="post" >5. Click submit to start our initial PHP program.

6. <br> <input type="submit" value="Click To Submit">

7. <input type="reset" value="Erase and Restart">

8. </form>

9. </body> </html>

52

Receiving Form Input into PHP Scripts

• To receive HTML form input into a PHP script:

– Use a PHP var name that matches the variable defined in the form element’s name argument.

• For example, if form uses the following: – <input type="radio" name="contact" value="Yes">

• Then form-handling PHP script could use a variable called $contact.

– If the user clicks the radio button, then $contact would = Yes

53

Full Example• Suppose your HTML form uses the

following: – Enter email address: <input type="text" size="16" maxlength="20" name="email">

• Then can receive input as follows:1.<html>2.<head><title> Receiving Input </title> </head>3.<body>4.<font size=5>Thank You: Got Your Input.</font>5.<?php6. print ("<br>Your email address is $email");7.8. print ("<br> Contact preference is $contact");

9. ?>

54

Register_Globals?• Since PHP 4.2.1, the default PHP configuration is

requiring a different mechanism to receive input for security reasons (than the one just shown).– Technical details: it is a PHP configuration option to

turn REGISTER_GLOBALS OFF (new default) or ON in the php.ini configuration file.

• If your site has REGISTER_GLOBALS OFF you must use a different mechanism to receive HTML Form Variables.

55

How can you tell if Register_Globals is OFF?

• Enter the following PHP script and run it. – <?PHP phpinfo(); ?>

• Search through the output for REGISTER_GLOBALS and see if it is set to OFF or ON.

• If it is off you must use the following way to receive input data.

56

Getting input data with Register_Globals OFF?

• To receive data with REGISTER_GOBALS OFF you use a special variable called $POST.

– $name $_POST[“name”];

Enclose in squarebracket and then quotes

Name of HTML form variable (note do not use $)

Special PHP Global variable. Technically it is an associative array (covered in chptr 5.)

PHP variable name that you want to receive the HTML form input.

57

Full Example, when REGISTER_GLOBALS is OFF.• Suppose your HTML form uses the

following: – Enter email address: <input type="text" size="16"

maxlength="20" name="email">

• Then can receive input as follows:1. <html>2. <head><title> Receiving Input </title> </head>3. <body>4. <font size=5>Thank You: Got Your Input.</font>5. <?php6. $email = $_POST[“email”];7. $contact = $_POST[“contact”];8. print ("<br>Your email address is $email");9. print ("<br> Contact preference is $contact");

10. ?>

58

Forms sending & retrieving 1

• Create a new page and save as test_form.php.

• Title : Using a form.• Add a form, 2 textfield and a

submit button.• The page should look like;

59

Forms sending & retrieving 2

• Properties of objects • Textfield 1:

– Name= firstName

• Textfield 2:– Name=lastName

• Form– Name=frmName– Action=test_form_processor.php– method-=POST.

60

Forms sending & retrieving 3

• Create another page called test_form_processor.php.

• Title: Displaying form data.• Create the page as shown and

select the plus to bind the form data.

61

Forms sending & retrieving 4

• Select the form variable.

• Select the Request.Form type.

• The name should be the same as the name on the page the data is coming from.

In this case the data is coming from test_form.php

62

Forms sending & retrieving 5

• Place the cursor after the comer after the “Thank you ”.

• Click on the binding firstName and then click on the insert button. This inserts the request variable into that space on the page.

• To insert the binding you can also drag and drop as another method.

• Repeat this for the lastName variable.

63

Forms sending & retrieving 6

• Your page should look like this.

• Now execute the test_form.php page.

Note: You will need to put a non breaking space (&nbsp;) between the two form bindings

64

Looking at the code.• Normally php code is embedded with

<?php ?>

• Echo is the command to display information. There are two other commands: print() and printf().

• The two print command allow formatting of text.

65

Retrieving data via URL 1• Open test_form.php and save as

test_form_get.php.• Change the form method to GET.• Open test_form_processor.php file and

save as test_form_processor_get.php.• Delete the bindings.• Insert 2 new bindings:

– the URLVariable. – Next slide shows how.

66

Retrieving data via URL 2Select the URL Variable and the screen below will appear. Put the name of the variable from the page calling this one, as shown; firstName

The new binding as shown will appear. Drag it to where the variable should be shown. The next slide shows this.

67

Looking at the code• This code is similar to the form

request, except the form has change to GET.

68

Sending data with Hyperlinks.

• When you send data with forms and a method of GET, information is sent in the URL.

• Another method of sending the info in the URL is in a Hyperlink.

• To do this you can just add the information in a name and info pair to the url of the link. eg:– ?firstName=Larry

69

Sending data with Hyperlinks 2.

• 1st page.

• Click on a link, eg cat and the page appears like.

• Click on dog and the page appears like.

70

Sending data with Hyperlinks 3

• Create a page and save it as animal_question.php and create it to look like this.

• The links are to the page animal_home_page.php

71

Sending data with Hyperlinks 4

• The links on the animal_question.php page should look like..

• Cat

• Dog

72

Sending data with Hyperlinks 5

• Another way to set the link with parameters is, click on the browse icon select the file and click on the parameters buttons as shown.

73

Sending data with Hyperlinks 6

• The animal_home_page.php should look like.

• Create the URL Variable as before with the binding panels.

74

Cookies - 1• The form and querystring request are

stateless variables. Once the server has passed them onto the client the server has no memory of them.

• Cookies are tiny text files that are written onto the user’s hard drive.

• Cookies help to maintain state over coming the stateless HTTP protocol.

75

Cookies - 2• Cookies and security

– Cookies can’t be used to infect computer with a virus.

– Cookies can only be read by the site that sent them.

– Cookies should never contain credit card details, password, etc.

76

Cookies - 3• Open the test_form_processor_get.php file .• Create a new page

test_form_processor_cookies.php• Add the following to the

test_form_processor_get.php file.

This code must be place before the html tag

Cookie variable name

77

Cookies - 4• Create the bindings and place

them in the design view of the test_form_processor_cookies.php file.

• As shown, then save and preview.

78

Lab 1• Objectives • After completing this lab, you

should be able to: – Create URL variables in the Bindings

panel. – Display URL variables on a page. – Create FORM variables in the

Bindings panel. – Display FORM variables on a page.

79

Lab 1 cont-2• Copy the folder lab_start from the x

drive to your working drive.• Create a new site called lab• Setup the folders on the IIS root folder

and the remote and testing servers.

80

unit2sendingpage.php

When you click on the “Display Home “ Button the next page appears showing the city that was typed in on this page.

If you click on the link “Click Here” then it takes you to the “unit2urlactionpage.php”.The link passes your name in the URL.

81

unit2formactionpage.php Notice, the word “Frankston” has appeared. This was a form variable from the previous page.

82

unit2urlactionpage.php?firstname=Larry

Notice “Larry” was sent in the URL and it is displayed on this page. Put your name there instead.

top related