Top Banner
1 Basic Php Pengaturcaraan PHP What Is PHP? PHP originally stood for Personal Home Page as it was created in 1994 by Rasmus Lerdorf to track the visitors to his online résumé. As its usefulness and capabilities grew (and as it started being used in more professional situations), it came to mean "PHP: Hypertext Preprocessor." Pengaturcaraan PHP
46
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Basic php

1

Basic Php

Pengaturcaraan PHP

What Is PHP?

PHP originally stood for Personal Home Page as it was created in 1994 by Rasmus Lerdorf to track the visitors to his online résumé. As its usefulness and capabilities grew (and as it started being used in more professional situations), it came to mean "PHP: Hypertext Preprocessor."

Pengaturcaraan PHP

Page 2: Basic php

2

PHP is a server-side, cross-platform technology Its cross-platform naturemeans that PHP runs on most operating systems, including Windows, Unix

(and its many variants), and Macintosh

Pengaturcaraan PHP

Example

Server-Side ProgrammingPHP, ASP, JSP, Servlet, Perl, RXML, Python, CFML, Tcl, Miva, iHTML, RADpage, SSI, iPerFrom, ePerl, Ruby

Client-Side ProgrammingHTML, Javascript, VBscript, Java Applet, CSS, DHTML

Pengaturcaraan PHP

Page 3: Basic php

3

PHP is a scripting language, asopposed to a programminglanguage: PHP was designed towrite Web scripts, not stand-aloneapplications.

The scripts run only after an eventoccurs for example, when a usersubmits a form or

goes to a URL.

Pengaturcaraan PHP

Why Use PHP?

PHP is better, faster, and easier to learnThan the alternatives.

What you get with PHP is excellentperformance, A tight integration with nearlyevery database available, stability, portability,and a nearly limitless feature set due to itsextendibility. All of this comes at no cost(PHP is open source) and with a very manageable learning curve.

Pengaturcaraan PHP

Page 4: Basic php

4

Finally, the proof is in the pudding: PHP has seen an exponential growth in use since its inception, overtaking ASP as the most popular scripting language being used today. It's the most requested module for Apache (the most-used Web server), and by the time you read this, PHP will be on about 20 million domains.

Pengaturcaraan PHP

How PHP Works

PHP is a server-side language. This means that the code you write in PHP resides on a host computer called a server. The server sends Web pages to the requesting visitors (you, the client, with your Web browser). When a visitor goes to a Web site written in PHP, the server reads the PHP code and then processes it according to its scripted directions. The PHP code tells the server to send the appropriate data — HTML code — to the Web browser, which treats the received code as it would a standard HTML page.

Pengaturcaraan PHP

Page 5: Basic php

5

This differs from a static HTML site where, when a request is made, the server merely sends the HTML data to the Web browser and there is no server-side interpretation occurring. Hence, to the end user and the Web browser there is no perceptible difference between what home.html and home.php may look like, but how that page's content was created will be significantly different.

Pengaturcaraan PHP

Basic Syntax

Pengaturcaraan PHP

Page 6: Basic php

6

PHP is an HTML-embedded scripting language. What HTML-embeddedmeans is that you can intermingle PHP and HTML code within the same script.

Pengaturcaraan PHP

To place PHP code within this document, you surround the code with PHP tags, either the formal and preferred or the informal.

Anything placed within these PHP tagswill be treated by the Web server as PHP (meaning the PHP interpreter will process the code; text outside of the PHP tags is immediately sent to the Web browser).

Pengaturcaraan PHP

Page 7: Basic php

7

A final consideration for your PHP scripts is that the file must use the proper extension.

The extension tells the server to treat the script as a PHP page.

Most Web servers will use .html or .htmfor standard HTML pages, and normally, .php is preferred for your PHP scripts.

Pengaturcaraan PHP

Creating a Basic PHP Script

This first PHP script doesn't do anything, per se, but it will demonstrate the syntax to be used.

Step 1Create a new document in your text editor.

It generally does not matter what text editor you use, be it BBEdit on the Macintosh, the very basic Notepad or more advanced Dreamweaver on Windows, or vi on Linux.

Pengaturcaraan PHP

Page 8: Basic php

8

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 9: Basic php

9

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 10: Basic php

10

Sending Data

Pengaturcaraan PHP

To build dynamic Web sites with PHP, you must know how to send data to the Web browser. PHP has a number of built-in functions for this purpose, the most common being echo() and print().

Either single or double quotation marks will work with either function. Also note that in PHP all statements (a line of executed code, in layman's terms) must end with a semicolon.

Pengaturcaraan PHP

Page 11: Basic php

11

Looking for an Escape

As you might discover, one of the complications with sending data to the Web involves printing single and double quotation marks. Either of the following will cause errors.

Pengaturcaraan PHP

There are two solutions to this problem. First, use single quotation marks when printing a double quotation mark and vice versa.

Pengaturcaraan PHP

Page 12: Basic php

12

Or, you can escape the problematic character by preceding it with a backslash.

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 13: Basic php

13

Pengaturcaraan PHP

If you see an entirely blank page, this is probably for one of two reasons:

-There is a problem with your HTML. Test this by viewing the source of your page and looking for HTML problems there.

- An error occurred, but display_errors is turned off in your PHP configuration, so nothing is shown. Review your PHP configuration documentation so that you can turn display_errors back on.

Pengaturcaraan PHP

Page 14: Basic php

14

Sending HTML codeYou can also use echo() and print() to send HTML code to the Web browser:

echo '<b>Hello, <font size="+2" >world</font>!</b>';

Sending multiple chunks of dataWith echo() but not print(), you can send multiple, separate chunks of data to the Web browser using commas:

echo 'Hello, ', 'world! ';

Printing over multiple linesEcho() and print() can both be used to print text over multiple lines.

Pengaturcaraan PHP

Understanding PHP, HTML, and White Space

Pengaturcaraan PHP

Page 15: Basic php

15

With this in mind, there are essentially three areas where you can affect spacing: in your PHP scripts, in your HTML source, and in the rendered Web page.

The extra spaces, tabs, and blank lines you create are generically known as white space.

Pengaturcaraan PHP

Creating White Space

To alter the spacing of the finished Web page, use the HTML tags <br/> (line break, <br> in older HTML standards) and <p></p>(paragraph).

To alter the spacing of the HTML source created with PHP, you can use echo() or print() over the course of several lines or use the newlinecharacter (\n) within double quotation marks.

Pengaturcaraan PHP

Page 16: Basic php

16

Writing Comments

Pengaturcaraan PHP

Writing the executed PHP code itself is only a part of the programming process. A secondary but still crucial aspect to dynamic Web site development involves documenting your code.

In HTML you can add comments using the following line:

Pengaturcaraan PHP

Page 17: Basic php

17

Pengaturcaraan PHP

PHP comments are different in that they aren't sent to the Web browser at all, meaning they won't be viewable to the end user, even when looking at the HTML source. PHP supports three comment types.

The first uses the pound or number symbol (#). The second uses two backslashes (//).

Both of these cause PHP to ignore everything that follows until the end of the line (when you press Return or Enter). Thus, these two comments are for single lines only. They are also commonly used to add a comment on the same line as some PHP code.

Pengaturcaraan PHP

Page 18: Basic php

18

A third style allows comments to run over multiple lines (/*...*/).

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 19: Basic php

19

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 20: Basic php

20

Pengaturcaraan PHP

Using Variables

Pengaturcaraan PHP

Page 21: Basic php

21

What Are Variables?

Variables, in short, are containersused to temporarily store values. These values can be numbers, text, or much more complex arrangements.

Variables exist at the heart of any programming language, and comprehending them is key to using PHP. According to the PHP manual, there are eight types of variables in the language.

Pengaturcaraan PHP

Regardless of what type you are creating, all variables in PHP follow certain syntactical rules:

- A variable's name — also called its identifier — must start with a dollar sign ($), for example, $name.

- The variable's name can contain a combination of strings, numbers, and the underscore, for example, $my_report1.

- The first character after the dollar sign must be either a letter or an underscore (it cannot be a number).

- Variable names in PHP are case-sensitive. This is a very important fact. It means that $name and $Name are entirely different variables.

- Variables can be assigned values using the equals sign (=), also called the assignment operator.

Pengaturcaraan PHP

Page 22: Basic php

22

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 23: Basic php

23

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 24: Basic php

24

Using Strings

Pengaturcaraan PHP

The first — arguably most important — variable type is strings. A string is merely a quoted chunk of letters, numbers, spaces, punctuation, and so forth. These are all strings:

- 'February 3, 2005‘

- '1,000‘

- "In watermelon sugar“

- 'Tobias'

Pengaturcaraan PHP

Page 25: Basic php

25

To make a string variable, assign a string value to a valid variable name.

Pengaturcaraan PHP

To print out the value of a string, use either echo() or print().

Pengaturcaraan PHP

Page 26: Basic php

26

To print the value of string within a context, use double quotation marks.

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 27: Basic php

27

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 28: Basic php

28

The $address variable now has the value SeattleWashington, which almost achieves the desired result (Seattle, Washington).

Concatenating Strings

Concatenation — an important tool when creating dynamic Web sites —is like addition for strings and is performed using the concatenation operator: the period (.).

Pengaturcaraan PHP

To improve upon this, I could write the following code so that aspace is added to the mix. The result would then be Seattle, Washington.

Pengaturcaraan PHP

Page 29: Basic php

29

Concatenation also works with strings or numbers. Either of these statements will produce the same result Seattle, Washington 98101.

Pengaturcaraan PHP

Concatenation is commonly used with string variables and can be used extensively when building databases.

Now, let's modify the strings.php script to use this new tool.

Pengaturcaraan PHP

Page 30: Basic php

30

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 31: Basic php

31

Pengaturcaraan PHP

Assigning new valuesIf you assign another value to an existing variable (say $book), the new value will overwrite the old one. For example:

$book = 'High Fidelity';

$book = 'The Corrections';

/* $book now has a value of 'The Corrections'. */

Converting the string caseYou can have PHP convert the case of your strings with: strtolower(), which makes it entirely lowercase; strtoupper(), which makes it entirely uppercase; ucfirst(), which capitalizes the first character; and ucwords(), which capitalizes the first character of every word.

Pengaturcaraan PHP

Page 32: Basic php

32

Others Concatenating formatsThe initial example in the concatenating section could be rewritten using either

$address = "$city, $state";or$address = $city;$address . = ', ';$address . = $state;

Using the concatenation operator with functionsThe concatenation operator can be used when calling functions, like so:

$num = strlen ($first_name . $last_name);

Pengaturcaraan PHP

Using Numbers

Pengaturcaraan PHP

Page 33: Basic php

33

PHP has both integer and floating-point (decimal) number types

4.4e2-

-4.2398508-

10980843985-

3.14-

8-

Pengaturcaraan PHP

Along with the standard arithmetic operators you can use on numbers, there are dozens of functions. Two I'll introduce in this lesson are round() and number_format().

Arithmetic Operators

Decrement --

Increment ++

Modulus %

Division /

Multiplication *

Subtraction -

Addition +

MeaningOperator

Pengaturcaraan PHP

Page 34: Basic php

34

The round() function rounds a decimal either to the nearest integer...

..or to a specified number of decimal places.

Pengaturcaraan PHP

The number_format() function turns a number into the more commonly written version, grouped into thousands using commas. For example:

Pengaturcaraan PHP

Page 35: Basic php

35

The number_format() function can also set a specified number of decimal points.

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 36: Basic php

36

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 37: Basic php

37

Corresponding assignment operators

Many of the mathematical operators also have a corresponding assignment operator, letting you create a shorthand for assigning values. This line

$total = $total + ($total * $taxrate);

could be rewritten as

$total += ($total * $taxrate);

Pengaturcaraan PHP

Using functions inline with the echo() statement

If you use concatenation, the number_format(), or any other function, can be used inline with an echo() statement:

echo 'You are purchasing <b>' . $quantity . '</b> widget(s) at acost of <b>$' . number_format ($price) . '</b> each. With tax, the total comes to<b>$' . number_format ($total) . '</b>.';

Pengaturcaraan PHP

Page 38: Basic php

38

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 39: Basic php

39

Constants are a specific data type in PHP that, unlike variables, retain their initial value throughout the course of a script.

In fact, you cannot 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.

Pengaturcaraan PHP

To create a constant, you use the define() function instead of the assignment operator (=) used for variables.

Notice that, as a rule of thumb, constants are named using all capitals, although this is not required. Most importantly, constants do not use the initial dollar sign as variables do (because, technically, constants are not variables).

Pengaturcaraan PHP

Page 40: Basic php

40

Printing constants requires special syntax as well.

You cannot print constants using echo "Hello, USERNAME", as PHP would just print Hello, USERNAME and not the value of the USERNAME constant (because there's no dollar sign telling PHP that USERNAME is anything other than literal text).

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 41: Basic php

41

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 42: Basic php

42

Using Single and Double Quotation Marks

Pengaturcaraan PHP

In PHP, values enclosed within single quotation marks will be treated literally, whereas those within double quotation marks will be interpreted. In other words, placing variables and special characters within double quotes will result in their represented values printed, not their literal values.

These characters have special meanings when used within double quotation marks.

Escaped Characters

Dollar sign \$

Tab \t

Carriage return \r

Newline\n

Backslash \\

Single quotation mark \'

Double quotation mark \"MeaningCode

Pengaturcaraan PHP

Page 43: Basic php

43

For example, assume that you have $var = 'test';

The code echo "var is equal to $var"; will print out var is equal to test, whereas the code echo 'var is equal to $var'; will print out var is equal to $var.

Using an escaped dollar sign, the code echo "\$var is equal to $var"; will print out $var is equal to test, whereas the code echo '\$var is equal to $var'; will print out \$var is equal to $var.

\$var is equal to $varecho '\$var is equal to $var';$var is equal to testecho "\$var is equal to $var";var is equal to $varecho 'var is equal to $var';var is equal to testecho "var is equal to $var";

...prints out...This code...

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 44: Basic php

44

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 45: Basic php

45

Pengaturcaraan PHP

Single quotes can be easier than double quotes

As valid HTML often includes a lot of double-quoted attributes, it's often easiest to use single quotation marks when printing HTML with PHP.

echo '<table width="80%" border="0"cellspacing="2" cellpadding="3"align="center">';

If you were to print out this HTML using double quotation marks, you would have to escape all of the double quotation marks in the string.

echo "<table width=\"80%\"border=\"0\" cellspacing=\"2\"cellpadding=\"3\" align= \"center\">";

Pengaturcaraan PHP

Page 46: Basic php

46

End

Pengaturcaraan PHP