working with php

63
1 Working With PHP David Lash Module 1 Getting Started

Upload: kevork

Post on 15-Jan-2016

43 views

Category:

Documents


0 download

DESCRIPTION

Working With PHP. David Lash Module 1 Getting Started. Objectives. To understand what PHP is What is HTML How PHP compares with CGI Getting Started with PHP Your first script PHP syntax and embedding in HTML Finding out about your PHP configuration Using PHP variables - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Working With PHP

1

Working With PHP

David Lash

Module 1

Getting Started

Page 2: Working With PHP

2

Objectives To understand what PHP is

» What is HTML» How PHP compares with CGI

Getting Started with PHP» Your first script» PHP syntax and embedding in HTML» Finding out about your PHP configuration

Using PHP variables

» Numerical variables and operators

» String variables, operators and a few functions

Separating PHP from HTML using <?=

Page 3: Working With PHP

3

Competencies

At end of unit be able to » Understand how PHP compares with other

dynamic technologies» Create a Web Page with PHP embedded» Receive input into PHP script with variables

Competency Alert:You need to

know this!

Common Problem Area!

People seem to forget this

Page 4: Working With PHP

4

Ummm, What is HTML used for?

HTML primarily . . . » Provides instructions to browser on how file should display.

– Has a set of markup language commands

– Can include graphical image files

HTML documents are Static. » For example, cannot use HTML alone to:

– have a document display current time

– receive results of a form, query a database, and display the results

– Open an input file and based on its contents, display different document content

Page 5: Working With PHP

5

Accessing HTML FilesYour PC

(Internet connected)Web Server

(Internet connected)

URL:www.myserver.com/funstuff.html

Web browser

Find Web server at www.myserver.comWeb server receives

request

Sends file withfunstuff.html

The file funstuff.htmlHere are some funthings to do:

1. Play baseball.2. Go swimming.3. Go to a concert.

Web browser

Note: The file is just

retrieved no code is executed on server

Note2: HTML tags

interpreted on client by browser.

http protocol

Page 6: Working With PHP

6

HTTP, Web Servers, Clients …

Hyper Text Transport Protocol – The protocol used to move data between Web server and Web browser.

Web Server Machine: A machine that runs web server software that listens for incoming requests on a port.» They have Internet IP addresses (e.g., 192.33.23.191) and listen on a

specific ports– 193.22.12.191:80

Web Server Software - an application, that exchanges data between Web server and Web browser. » Uses HTTP » Excepts a requests (e.g., from browser) in a specific format. » Responds to browser in a specific format. » For example, a request consist of TOP LINE, HEADER and BODY

(BODY is sometimes absent).» HEADER and BODY are separated by an empty line.

Page 7: Working With PHP

7

HTML?

The Hypertext Markup Language (HTML)» used coded HTML tags » provide Web browsers display instructions.

HTML is» It is simple to use and understand» It provides ways to include things like text, graphics,

sounds, links.» It is STANDARD » Its creation (and use) is one of the big reasons the WWW

became popular

Page 8: Working With PHP

8

Major Server-Side Web Technologies

CGI - Computer Gateway Interface» Web Servers enable computer variety of computer

languages to dynamically generate HTML» E.g. Perl, C, Unix Shell, C++

Web Server add-on» Builds on to existing web servers – E.g., Cold Fusion

Embedded Web server» Web server has scripting language built into it.» Comprises most modern scripting technologies

– ASP, JSP, PHP

Competency Alert:You need to

know this!

Page 9: Working With PHP

9

Often the Choice Depends on Web Server

If running a Microsoft Web Server (e.g., IIS) » More likely to use ASP or ASP.net

If running UNIX/Linux (e.g., Apache) » more likely to use PHP, or JSP.

Source netscrat http://www.netscraft.com

Page 10: Working With PHP

10

What Is PHP?Advantages of Using PHP to enhance Web pages:

» Easy to use.» Open source.» Multiple platform.

Started around 1996 when » Rasmus Lerdorf (a consultant) wanted to know number of people viewing his on-

line resume. » Developed a CGI/Perl script that counted visitors and logged some visitor

information.» He received many inquires for his CGI/Perl toolset so started giving it away for

free (and called it Personal Home Page).» Got so many requests for additions, developed a next release of toolset (called

PHP 2.0)» PHP 2.0 became popular and PHP moved to open source model.

Page 11: Working With PHP

11

How PHP Pages are Accessed and Interpreted

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.

Page 12: Working With PHP

12

Compare with CGI

2. Send Request for CGI program

3. Rece ive re qu est

7. Forward R esu lts

8. Return Resu lts

Please EnterAPho neNumber

Submit Erase

1. W eb Browser

4. Use CG I

6. Use CG I

W eb Browser

Pho ne QueryResul ts:

That isJohn Doe'sPho neNumber

9. We b Browse r

Your PC(In tern et con ne cted)

WebServer(Internet conn ected )

5 . Executep ro gram

Se nd b ackresu lts

Web ServerSoftw are

Perl

ProgramSoftw are

Note this can be shell script, perl script, C program or whatever.

On a UNIX server this is a fork operation

Page 13: Working With PHP

13

Objectives

To understand what PHP is » What is HTML» How PHP compares with CGI

Getting Started with PHP» Your first script» PHP syntax and embedding in HTML» Finding out about your PHP configuration

Using PHP variables

» Numerical variables and operators

» String variables, operators and a few functions

Separating PHP from HTML using <?=

Page 14: Working With PHP

14

Getting Started with PHP

To develop and publish PHP scripts you need:

» A Web server with PHP built into it» A client machine with a basic text editor and

Internet connection» FTP or Telnet software

Its worth noting:There are a couple good IDEs for PHP. They basically allow you create PHP scripts on PC, syntax check them, see output, and then copy to Web server

Page 15: Working With PHP

15

Common PHP Development Configurations

Linux/Apache

FTP or telnet

Development PC

Development PC

Windows/Apache/IIS

PC RunningWindows

Apache/IIS

PC RunningLinux Apache

Page 16: Working With PHP

16

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.

Page 17: Working With PHP

17

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.

Page 18: Working With PHP

18

On a Linux/Apache Web Server

Typically you:

1. Save files with a .php suffix (myfile.php).

2. Place files under public_html (e.g., /home/dlash/public_html/

Its worth noting: Some web hosts allow direct access to servers with SSH telnet. Others only allow you to use FTP to copy files over.

Page 19: Working With PHP

19

PHP Proper Syntax Need to be syntactically correct. For example, the print statement syntax:

print ( "Your message to print" );

Enclose messagein quotation

marks

Message to Output

End in asemi-colon

Parenthesis areoptional

Page 20: Working With PHP

20

If Use Improper Syntax

Suppose you use the wrong syntax:

1. <?php2. print ( “A simple initial script);

3. ?>

Page 21: Working With PHP

21

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.

Page 22: Working With PHP

22

Embedding PHP Statements Within HTML

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

Page 23: Working With PHP

23

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 be

output:

print ("<font color=\"blue\">");» The above statement would output: <font color="blue">

Note! . . . You could also output the above line using the following PHP line:print (‘<font color="blue">“’);We will examine the meaning between “ and ‘ later.

Page 24: Working With PHP

24

Using Comments with PHP Scripts

Comment Syntax - Use //<?php// This is a comment?>

Can place on Same line as a statement:<?phpprint ("A simple initial script"); //Output a line?>

Note: Comment lines are ignored when the script runs. They do not slow down the run-time

Page 25: Working With PHP

25

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(); ?>

Page 26: Working With PHP

26

More on phpinfo()

Use a script with the following to find out about your PHP installation:» <? phpinfo(); ?>

This build does NOT have mysql!

Location of PHP main config file

The php version

Other interesting items:Apache version & configuration, php config variables, environment.

Page 27: Working With PHP

27

More on phpinfo()

Manual strongly recommends setting to off

Allow ASP style tages

Value constant

1 E_ERROR

2 E_WARNING

4 E_PARSE

8 E_NOTICE

16 E_CORE_ERROR

32 E_CORE_WARNING

64 E_COMPILE_ERROR

128 E_COMPILE_WARNING

256 E_USER_ERROR

512 E_USER_WARNING

1024 E_USER_NOTICE

2047 E_ALL

2048 E_STRICT

Flag values indicates which errors to display/log

Page 28: Working With PHP

28

Error Definitions . . . Value Constant Description Note

1 E_ERROR (integer) Fatal run-time errors. These indicate errors that can not be recovered from, such as a

memory allocation problem. Execution of the script is halted.  

2 E_WARNING (integer) Run-time warnings (non-fatal errors). Execution of the script is not halted.  

4 E_PARSE (integer) Compile-time parse errors. Parse errors should only be generated by the parser.  

8 E_NOTICE (integer) Run-time notices. Indicate that the script encountered something that could indicate an

error, but could also happen in the normal course of running a script.  

16 E_CORE_ERROR (integer) Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is

generated by the core of PHP. since PHP 4

32E_CORE_WARNING (

integer) Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an

E_WARNING, except it is generated by the core of PHP. since PHP 4

64E_COMPILE_ERROR (

integer) Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend

Scripting Engine. since PHP 4

128E_COMPILE_WARNING (

integer) Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is

generated by the Zend Scripting Engine. since PHP 4

256 E_USER_ERROR (integer) User-generated error message. This is like an E_ERROR, except it is generated in PHP

code by using the PHP function trigger_error(). since PHP 4

512E_USER_WARNING (

integer) User-generated warning message. This is like an E_WARNING, except it is generated in

PHP code by using the PHP function trigger_error(). since PHP 4

1024E_USER_NOTICE

(integer) User-generated notice message. This is like an E_NOTICE, except it is generated in PHP

code by using the PHP function trigger_error(). since PHP 4

2047 E_ALL (integer) All errors and warnings, as supported, except of level E_STRICT.  

2048 E_STRICT (integer) Run-time notices. Enable to have PHP suggest changes to your code which will ensure

the best interoperability and forward compatibility of your code. since PHP

Page 29: Working With PHP

29

‘Overriding’ php.ini settings

<?php

ini_set('error_reporting', 2047);

phpinfo();

?>

Global is ’85’ Local is 2047.

Page 30: Working With PHP

30

Apache2triad provide config administrator

Show errors in browser

Include HTML errors

Note: Has option at bottom to save configuration. Also must restart apache for changes to take effect.

Page 31: Working With PHP

31

Setting Your own Configuration Options

<?php

ini_set('error_reporting', E_ALL);

$x = $y + 1;

print " x=$x $y=$y"

?>

2047 E_ALL (integer)

All errors and warnings, as supported, except of level E_STRICT.

2048 E_STRICT (integer)

Run-time notices. Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.

since PHP

Page 32: Working With PHP

32

How to read ‘Error_reporting’ variable

How did ‘get’ error_reporting = 85 ?» Answer: php.ini has the following line:

error_reporting = E_COMPILE_ERROR|E_PARSE|E_ERROR|E_CORE_ERROR

1 E_ERROR (integer)

2 E_WARNING (integer)

4 E_PARSE (integer)

8 E_NOTICE (integer)

16 E_CORE_ERROR (integer)

32 E_CORE_WARNING (integer)

64 E_COMPILE_ERROR (integer)

128 E_COMPILE_WARNING (integer)

256 E_USER_ERROR (integer)

512 E_USER_WARNING (integer)

1 + 4 + 16 + + 64 = 85.

Page 33: Working With PHP

33

Even more phpinfo()

Send errors to logfile

Require input variables to use super-global array

Enable scripts to upload to server

Defines where to look for includes. (This can be set dynamically in scripts.)

Page 34: Working With PHP

34

Visit www.php.net

Quick function search

Function manual

Page 35: Working With PHP

35

Objectives

To understand what PHP is » What is HTML» How PHP compares with CGI

Getting Started with PHP» Your first script» PHP syntax and embedding in HTML» Finding out about your PHP configuration

Using PHP variables

» Numerical variables and operators

» String variables, operators and a few functions

Separating PHP from HTML using <?=

Page 36: Working With PHP

36

PHP allows creating variables on the fly

For example, <?php $days = 3; $newdays = 100; $days = $newdays;?>

A PHP variable names must:» Use a dollar sign ($) as the first character» Use a letter or an underscore character (_) as the

second character.

Page 37: Working With PHP

37

Combining Variables and the print Statement

Use print statement with double quotes:

$age=6;

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

print (‘but george is $age years old.’);

Would output: Bryant is 6 years old but george is $age years old.

Double quotes output any variable’s value

Single quotes output any variable’s name.

Page 38: Working With PHP

38

Using Arithmetic Operators

PHP supports various arithmetic operators. 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.

Page 39: Working With PHP

39

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.

% Remainde (modulus)

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

Page 40: Working With PHP

40

Common PHP Combined Assignment Operators

Operator Effect Example Result

+= Addition and assignment

$y += 3; $y = $y + 3;

-= Subtraction and assignment

$y -= 3; $y = $y – 3;

*= Multiplcation and assignment

$y *= $x; $y = $y * $x ;

/= Division and assignment

$y /= 12; $y = $y / 12;

%= Modulus and assignment

$z %= $x; $z = $z % %x;

.= Catenation and assignment

$happy .= ‘hello’ ;

$happy = $happy . ‘hello’;

Page 41: Working With PHP

41

A Full Example1. <html>

2. <head> <title>Variable Example </title> </head>

3. <body>

4. <?php

5. $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>

Page 42: Working With PHP

42

WARNING: Using Variables with Undefined Values

Use a variable without a value assigned will have no value (called a null value).

PHP will NOT generate an error and will complete the expression.

For example,

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

Will output x= y=4.

Page 43: Working With PHP

43

PHP Precedence Rules PHP follows the precedence rules listed

below.» First it evaluates operators within parentheses.» Next it evaluates multiplication and division» Finally it evaluates addition and subtraction

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;

Page 44: Working With PHP

44

Objectives

To understand what PHP is » What is HTML» How PHP compares with CGI

Getting Started with PHP» Your first script» PHP syntax and embedding in HTML» Finding out about your PHP configuration

Using PHP variables

» Numerical variables and operators

» String variables, operators and a few functions

Separating PHP from HTML using <?=

Page 45: Working With PHP

45

Working with PHP String Variables

Use character strings for data such as customer names, addresses, product names, and descriptions.

E.g.,» $name="Christopher";» $preference="Milk Shake";

Note: Technically it is more correct to write: $name=‘Christopher’;$preference=‘Milk Shake’;Since there are no variable values to evaluate.

Page 46: Working With PHP

46

WARNING: Be Careful Not to

Mix Variable Types Be careful not to mix string and numeric

variable types. <?php

$x ="banana";

$sum = 1 + $x;

print ("y=$sum");

?>

No error will occur instead will output:y=1

Page 47: Working With PHP

47

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");

Page 48: Working With PHP

48

TIP: Different ways to concatenate strings.

A couple different ways to concatenate strings:» Concatenation operator

$Fullname2 = $FirstName . " " . $LastName;

» Double quotes $Fullname2 = "$FirstName $LastName";

» Concatenation combination operator $comment = ‘I love this job’;

$comment .= ‘but the hours and not that good’;

» Mix and match: $name = ‘George’;

$comment = “$name said: I love this job”;

$comment .= ‘but the hours and not that good’;

Page 49: Working With PHP

49

The strlen() Function Usually use one or more arguments with

» Arguments are input values that functions » Often functions return a value » For example<?php

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

?>Would output Length=8

Note: Function output would be one reason to use the concatenate operator

<?php$First = 'George';print "$First has " . strlen($First ) . ' characters';?>

Would output: George has 6 characters

Page 50: Working With PHP

50

The trim() 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");» ?>

Would output Lname=“Joe JacksonJoe Jackson”

Page 51: Working With PHP

51

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");

?>

Would output “upper=NOW IS THE TIME lower=now is the time”.

Page 52: Working With PHP

52

The substr() Function

» Substr has the following general format:

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

Extract from here.

Assign results into here

Position to start extracting from.

Number of characters to extract (If omitted will continue to end of string.)For example:

<?php$date = "12/25/2002";$month = substr($date, 0, 2);$day = substr($date, 3, 2);print ("Month=$month Day=$day");?>

Would output

“Month=12 Day=25”.

Page 53: Working With PHP

53

Objectives

To understand what PHP is » What is HTML» How PHP compares with CGI

Getting Started with PHP» Your first script» PHP syntax and embedding in HTML» Finding out about your PHP configuration

Using PHP variables

» Numerical variables and operators

» String variables, operators and a few functions

Separating PHP from HTML using <?=

Page 54: Working With PHP

54

Evaluation delimiters1 <?php23 $url = '<a href=http://mysite.com> mysite.com </a>';4 $store = '<font color=red> toy store </font>';5 $special = 'boxed block sets';6 ?>7 <html>8 <head> <title> this is a title </title> </head>9 <body> <font color=blue size=4>10 Welcome to the <?= $store ?>11 our special today is <i> <?= $special ?> </i>12 <br> Visit our home page at <?= $url ?>13 </font> </body> </html>

Can separate PHP from HTML and use <?= delimiter. It automatically outputs any PHP variables found.

Page 55: Working With PHP

55

Getting input data

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

» $mynm = $_GET[“name”];Enclose in squarebracket and then quotes

Name of HTML form CGI 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.

Page 56: Working With PHP

56

Sending Input From URL

You can send data to your application by: » http://www.indelible-learning.com/php/module1/input.php?special=Baseball Bats

If needed to send multiple input variables could:» http://www.indelible-learning.com/php/module1/input.php?special=Baseball Bats&myname=Dave

Use & sign

Page 57: Working With PHP

57

Objectives

To understand what PHP is » What is HTML» How PHP compares with CGI

Getting Started with PHP» Your first script» PHP syntax and embedding in HTML» Finding out about your PHP configuration

Using PHP variables

» Numerical variables and operators

» String variables, operators and a few functions

Separating PHP from HTML using <?=

Page 58: Working With PHP

58

Module 1 Hands on Assignment

Create a php script that calculates the total possible revenue of a theater. Suppose that:» The theater charges $5 per seat» The theater has with 10 rows and 8 seats per row. » Output the total possible revenue.» Set the seat cost, rows and seats per row at top of script

and separate PHP from HTML code.

Page 59: Working With PHP

59

One possible solution

1 <?php 2 $cost = 5; $rows = 10; 3 $cols = 8; $total = $rows * $cols; 4 $rev = $cost * $total; 5 ?> 6 <html> 7 <head> <title> Theater Calculation </title> </head> 8 <body> <font color=blue size=4> 9 We have <?= $total ?> seats in the house 10 <br> 11 At a costs of $<?=$cost ?> our total possible revenue is 12 <?= $rev ?>. 13 </font> </body> </html>

Page 60: Working With PHP

60

Lab 1 Extension Exercise

Modify that same script to receive the values of $rows and $cols from the Web URL. » Send different input values from the web

Page 61: Working With PHP

61

One Possible Solution <?php $cost = 5; $rows = $_GET[rows]; $cols = $_GET[cols]; $total = $rows * $cols; $rev = $cost * $total; ?> <html> <head> <title> Theater Calculation </title> </head> <body> <font color=blue size=4> We have <?= $total ?> seats in the house <br> At a costs of $<?=$cost ?> our total possible revenue is <?= $rev ?>. </font> </body> </html>

Page 62: Working With PHP

62

Module 1 Hands on assignment

Write a simple script that outputs the configuration of PHP

What are compilation settings of our PHP» What version?» What apache version?» Other interesting settings?

Page 63: Working With PHP

63

One possible solution<? phpinfo() ?>