Web Programming for Business - PHP Object-Oriented Programming with Oracle

1 Linux, HTML, PHP, and JavaScript Basics

Overview

The 2014 Fall semester marks my 18th year teaching PHP web scripting (programming) with Oracle as the back-end database. Over the years, many of my students have commented on programming skills developed, ability to secure a good job and discipline to help advance careers acquired by successfully completing the course. This book is based on what I have learned, how I have learned, continuous interactions with industry experts (web developers, database engineers, and application programmers), my experiences as a programmer, consultant, and analyst, and clear and concise programming fundamentals. Although technology changes rapidly, programming fundamentals remain relatively constant. The code included in these chapters has changed little over the years and still works even with new distributions of Linux, PHP, JavaScript, and Oracle. Of course, I tweak and add new code as I learn more.

In my technology teaching experiences, I have learned that clean, clear, concise, and systematic code examples with explanations go a long way in helping students learn, digest, and apply technologies, such as various types of programming and database activities. Also, teaching fundamentals has proven to be key in establishing a strong technological base in my students. Feedback from numerous industry employers who hire our students have indicated that my classes offer excellent and enduring technology fundamentals (which is one of the most important reasons why they hire our students).

So, this book strives to offer programming fundamentals presented in a clear, concise, and practical manner. In later chapters, I include applications using the fundamentals included in these chapters.

Web programming is only possible with an appropriate information technology (IT) platform. An IT platform can take many forms, but must include an operating system (OS), programming (or scripting) language, web browser, web server, and database management system (DBMS). The platform I use includes Linux as the OS, PHP as the scripting language, a web browser (Google Chrome is my preference), and Oracle as the DBMS.

I have an IT expert install and maintain Oracle, Linux, and PHP on a computer server. Our industry advisory board endorses the IT platform I have just described. My current platform includes Oracle 12c, Linux (Redhat Fedora), and PHP 5.3.14. My IT expert creates Linux and Oracle accounts on a server for each student. Students create and save PHP scripts on their Linux accounts using PuTTY (or MobaXterm), and use Oracle SQL Developer to interact with Oracle. When students need to securely transfer files, they use WinSCP.

Chapter 1 covers Linux, HTML, JavaScript, and PHP basics. Although basics are covered, I recommend visiting w3schools’ or other websites for tutorials to deepen knowledge of Linux, HTML, PHP, and JavaScript. The w3schools’ URL is www.w3schools.com/.

Learning Objectives

After completing this chapter, you will gain a fundamental understanding of Linux, HTML, PHP, and JavaScript through explanation and code examples. The following objectives summarize the skills the chapter will help you develop:

1.    Learn how to install and use ‘PuTTY’.

2.    Learn how to install and use ‘WinSCP’.

3.    Learn how to install and use ‘Oracle SQL Developer’.

4.    Learn the basics of Linux (as an end user).

5.    Learn the basics of HTML.

6.    Learn the basics of PHP.

7.    Learn the basics of JavaScript.

Install and Use PuTTY

‘PuTTY’ is a free and open-source terminal emulator application that can act as a client program for SSH, Telnet, and Rlogin network protocols. ‘PuTTY’ is used to connect to a user account on Linux. ‘PuTTY’ opens a window where anything typed is sent straight to the Linux machine and the response from Linux is sent back to the open window. So, you can work on the Linux machine as if you were sitting at its console, while actually sitting in a remote location. To download ‘PuTTY’, Google the keywords ‘putty download’ and choose the hyperlink ‘PuTTY Download Page’ (Figure 1.1). The version may change over time. Feel free to use another site if you wish. The site is only recommended because it is the one that I use.

Figure 1.1

Figure 1.1 PuTTY Download Page

On the ‘PuTTY Download Page’ (Figure 1.2), choose the ‘putty.exe’ link. This is the first link under ‘For Windows on Intel x86’. Click the down arrow (to the right of the downloaded file ‘putty.exe’) and choose ‘Show in folder’. Your computer automatically opens the ‘Downloads’ directory. Find the ‘putty’ icon in this directory and open it. Click ‘Run’ to open ‘PuTTY’.

Figure 1.2

Figure 1.2 Hyperlink to Putty Download Page (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html)

The ‘PuTTY Configuration’ window opens automatically. Type the name of the server for ‘Host Name’ and the ‘Port’ for the port where Linux is listening for requests. Your IT expert should provide this information. In my case, I use ‘SSH’ to enhance security, which is recommended. So, after you type in the host and port information be sure to click the ‘SSH’ button (if you use SSH). Click ‘Open’ to begin your session. Now, you should see the console. To access Linux account information, enter your ‘username’. When Linux prompts you for your password, enter it. Your IT expert will provide this information (Figure 1.3). If username and password are accepted, you are logged into Linux (Figure 1.4). Type ‘exit’ to close the session.

Figure 1.3

Figure 1.3 Username and Password to SSH into Linux Server

Figure 1.4

Figure 1.4 Command Prompt with Successful Login

Install and Use WinSCP

‘WinSCP’ is a free and open-source SFTP, SCP, and FTP client for Microsoft Windows. Its main function is secure file transfer between a local and a remote computer. To download ‘WinSCP’ onto your computer, Google the keywords ‘winscp download’ and choose the hyperlink ‘WinSCP Download’ (Figure 1.5). The version may change over time. Feel free to use another site if you wish. The site is only a recommendation because it is the one that I use.

Figure 1.5

Figure 1.5 Hyperlink to WinSCP Download Page (http://winscp.net/eng/download.php)

On the ‘WinSCP Download’ page, choose ‘Installation package’ (Figure 1.6). This hyperlink is on the left of the page under ‘WinSCP 5.1.7’. This is the version as of writing this chapter; it may change over time.

Figure 1.6

Figure 1.6 WinSCP Installation Package

Click the down arrow (to the right of the downloaded file ‘winscp517setup.exe’) and choose ‘Show in folder’. Your computer automatically opens the ‘Downloads’ directory. Find the ‘winscp517setup’ icon in this directory and open it. Click ‘Run’ to open the program. Click ‘Yes’ to allow the program to make changes to your computer. Click ‘OK’ to select ‘English’. Click ‘Next’ to begin ‘WinSCP Setup Wizard’. Accept the agreement and click ‘Next’ (accept what is ‘recommended’). Click ‘Install’ and then click ‘Finish’. Keep in mind that minor changes may occur during the installation process with future versions of the software.

To launch ‘WinSCP’, choose ‘File protocol’ using the down arrow (I use ‘SCP’). Type in your Linux ‘Host name’, ‘port number’, ‘User name’, and ‘Password’, and click the ‘Login’ button (this information should be the same that was provided by your IT expert for using ‘PuTTY’). You have established a new session. The right panel contains your account information on the remote Linux server. The left panel contains your local computer information. The ‘WinSCP’ software works like ‘FTP’, but it is much more secure. Using the software is also easy because it works like a ‘Windows’ directory. Close the session by clicking on the ‘X’ on the top right of the window.

Install and Use Oracle SQL Developer

Oracle SQL Developer is a free integrated development environment that simplifies the development and management of the Oracle database. To download ‘Oracle SQL Developer’ onto your computer, Google the keywords ‘Oracle SQL Developer’ and choose hyperlink ‘Oracle SQL Developer Downloads’ (Figure 1.7). The version may change over time. Click the ‘Downloads’ tab to the right of the ‘Overview’ tab. Click the ‘Accept License Agreement’ button (Figure 1.8).

Figure 1.7

Figure 1.7 Hyperlink to Download Oracle SQL Developer

Figure 1.8

Figure 1.8 Oracle SQL Developer License Agreement Page (http://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/index.html)

Scroll down the page and choose the appropriate platform for your computer (Figure 1.9). The only version that I have experience with is the ‘Windows 32-bit’ version, which includes the ‘JDK’ (Java development kit).

Figure 1.9

Figure 1.9 Oracle SQL Developer Download Options

Oracle will ask you for a username and password. So, click the ‘Sign Up’ hyperlink to create a new account (unless you already have one). Fill out the online form completely and click the ‘Create Account’ button on the bottom of the form. On the ‘Account Verification’ page, click the ‘Continue’ button. Now, sign in with your new username and password. Wait for the download to complete, which may take some time (so be patient). Click the down arrow (to the right of the downloaded file) and choose ‘Show in folder’. Your computer automatically opens the ‘Downloads’ directory.

Find the ‘sqldeveloper’ icon in this directory and open it. Open the ‘sqldeveloper’ folder. Click on the ‘sqldeveloper’ icon. Click the ‘Extract all’ button. Click ‘Extract’ button to place software in the ‘Downloads’ directory. Be patient while the software is being downloaded because the process will take several minutes. Double click on the ‘sqldeveloper’ folder. Open the software with the ‘sqldeveloper’ icon. When prompted, click ‘Run’. Choose the first option ‘SQL Source (.sql)’ and click ‘OK’. Click the green ‘+’ button and enter the ‘Connection Name’, ‘Username’, ‘Password’, ‘Hostname’, ‘Port’, and ‘SID’ information. Ask your IT expert for this information.

Keep in mind that the ‘Username’ and ‘Password’ is for access to the Oracle database, not the Linux OS. To keep it simple for my students (and me), their Linux and Oracle accounts have identical usernames and passwords. Click ‘Test’ to see if you have a successful connection. If successful, click the ‘Connect’ button to establish a connection to the database. Close the connection by either closing the pop-up window or using ‘File’ and then ‘Exit’ on the menu. Once a connection has been established, the next time you open the software just click on the ‘+’ symbol to the left of the connection to open a session.

Linux Basics

This section explains and illustrates with examples how an end user works with Linux to display content on the Internet. To log into your Linux user account, open a ‘PuTTY’ session as demonstrated earlier in the ‘PuTTY’ section (Figures 1.3 and 1.4). Figure 1.10 illustrates a successful ‘SSH’ login with the cursor on the command line. The command line is where you tell Linux what is needed by typing commands at the cursor position.

Figure 1.10

Figure 1.10 Command Prompt with Successful Login

Let’s begin by creating a directory to display content. This directory is where all files that you wish to be displayed on the Internet must reside. Type the following on the command line and press ‘Enter’:

mkdir public_html

Command ‘mkdir’ tells Linux to create a new directory. In this case, the new directory is called ‘public_html’. Typically, ‘public_html’ is where Linux looks for information to display on the Internet. Now, set permissions for the directory (type the following on the command line and press ‘Enter’):

chmod 705 public_html

Command ‘chmod’ tells Linux to change permissions to ‘705’ for the directory listed. I will explain what ‘705’ means in a moment. To see what happened, type the following command:

ls-la

Command ‘ls’ lists the contents of a directory. In this case, you are at the highest level of your directory structure. With ‘ls’, two options are included – ‘l’ and ‘a’. Options are preceded by a hyphen ‘-’. Option ‘l’ tells the list command to use a long list format. Option ‘a’ tells it to not hide anything. Look to the left of directory ‘public_html’ to see its permissions.

drwx---r-x

Letter ‘d’ tells you that ‘public_html’ is a directory. The next three letters ‘rwx’ are permissions for the owner (you) of the directory. The following three ‘---’ are permissions for the group. Don’t worry about group permissions in this book, because we won’t discuss them. The final three ‘r-x’ are permissions for the world (Internet). Before explaining permissions more deeply, let’s look inside the ‘public_html’ directory. To do this, enter the following on the command line:

cd public_html

Command ‘cd’ changes directories to your choice. In this case, you are changing to ‘public_html’. Now, list contents with no options:

ls

You see nothing because you have yet to create content in ‘public_html’. Command ‘cd’ followed by a directory moves you down your directory tree. To move up your directory tree, type the following on the command line:

cd ..

You should now be back at the top of your directory tree. Type the following:

ls

You should see only the ‘public_html’ directory that you created. Earlier in this section, you typed ‘ls-la’ to see permissions of ‘public_html’. Permissions for your display directory are ‘drwx---r-x’. The first bit ‘d’ means directory. The next three bits ‘rwx’ mean that the owner (you) has read, write, and execute privileges. So, you can read from this directory, write to this directory, and execute from this directory. The next three bits ‘---’ are for group privileges. The hyphen ‘-’ means that no permissions are provided. The group therefore has no privileges on this directory. The final three bits ‘r-x’ mean that anyone on the Internet can read from the directory and execute from it, but cannot write to it. If you wish to secure a directory or file from the world, never provide ‘write’ privileges, otherwise anyone with access to the Internet can potentially write to your file or directory!

Table 1.1 Octal to Binary Conversion

Octal

Binary


0

000

1

001

2

010

3

011

4

100

5

101

6

110

7

111

Octal (Base Eight) Permissions

Linux permissions are based on octal numbering (or base eight). When you changed permissions to ‘705’, each number was in base eight. The reason Linux uses base eight is because it translates easily into binary, but represents more bits in less space than binary. Base eight number ‘7’ translates into binary ‘111’. A binary ‘1’ means on. A binary ‘0’ means off. Since all three binary numbers are ‘1’, read, write, and execute are on. The leftmost bit ‘1’ corresponds to ‘r’, the next bit ‘1’ corresponds to ‘w’, and the rightmost bit ‘1’ corresponds to ‘x’. Base eight number ‘0’ translates into binary ‘000’, which means that all permissions are off. Finally, base eight number ‘5’ translates into binary ‘101’. Since the leftmost bit represents ‘read’ and is on, the Internet can read. The rightmost bit represents ‘execute’ and is on, which means the Internet can execute. The middle bit represents ‘write’ and is off, which means the Internet cannot write. Notice that ‘r’, ‘w’, and ‘x’ are positional, which makes Linux permissions relatively easy to understand. Table 1.1 is provided to facilitate easy conversion from base eight to binary (and vice versa). Conversion is necessary because command ‘chmod’ accepts base eight numbers only, while Linux permissions are represented by binary numbers.

Two caveats are in order. First, be sure that all content (files and directories) that you wish to be displayed in a browser are located within the ‘public_html’ directory. Second, do not allow the Internet ‘write’ permissions. In most cases, you do not want the world to be able to ‘write’ to your directory or file. To close a remote connection to Linux, enter the ‘exit’ command (type ‘exit’ on the command line and press ‘Enter’).

Display Content

With a bit of Linux knowledge, you can create a PHP script that can display content on the Internet. Open a web browser of your choice. I use ‘Google Chrome’, so the examples will be from this browser. Use ‘PuTTY’ to open an SSH Linux session and change to the ‘public_html’ directory. Next, use command ‘vi’ to open a new file. Be sure to enter each command on a separate command line.

cd public_html
vi test.php

To enter command mode, press the escape key ‘Esc’. To enter commands, press the colon ‘:’ key. You should see a colon ‘:’ bottom left of the screen. Command mode is the command environment for Linux files. Turn on line numbering with the following command:

:set nu

Figure 1.11 shows that line numbering is turned on. If you wish, you can turn off line numbering with the following command:

:set nonu

Figure 1.11

Figure 1.11 Editing a New File with ‘vi’ Command and Turning Line Numbering On

To edit a file, press ‘Esc’ and change to input mode by typing the letter ‘i’. Input mode is the editing environment for Linux files. Enter the text shown in Figure 1.12 line by line (press ‘Enter’ after each line).

Figure 1.12

Figure 1.12 Input Mode with ‘vi’ Command

Be sure to start typing on the first line leftmost column to eliminate spurious errors. Begin every PHP script with beginning tag ‘<?php’ and end with ending tag ‘?>’. Remove any additional blank lines after ending tag ‘?>’. To exit insert mode, press the ‘Esc’ key. To save the file, enter colon ‘:’, ‘w’, and press ‘Enter’. To return to the directory structure, press ‘Esc’, enter ‘:q’, and press ‘Enter’. Enter ‘ls’ to see the file in ‘public_html’. To verify that the contents of ‘test.php’ are what you expect, enter ‘vi test.php’. To display ‘test.php’ on the Internet, enter the correct path:

servername/~username/test.php

The ‘servername’ is the name of the host computer where the PHP engine resides. Your IT expert can help you with this. The tilde ‘~’ must precede your Linux user account name. Do not include ‘public_html’ in the path because the PHP engine already knows that the file is within this directory. Figure 1.13 shows what should be displayed.

Figure 1.13

Figure 1.13 Displaying PHP Content on a Web Browser

Again, since Linux knows that ‘public_html’ is the display directory, do not include it in the path. To create a new file, use ‘vi filename’. The basic file commands are entered by preceding them with the colon ‘:’ key. However, edit commands are not preceded by the colon ‘:’ key. Edit commands are available when you first edit a file, but if the colon key has been pressed or you are in insert mode, press the ‘Esc’ key. Now, you can use edit commands such as copy, cut, and paste. To copy code, enter ‘vi test.php’, a colon ‘:’, command ‘set nu’, and move cursor to line 2 (if necessary). Moving to a line is easy in Linux because you can use the up, down, left, and right arrows on your keyboard. Type letters ‘yy’ (consecutively) and letter ‘p’. Letters ‘yy’ mean copy and letter ‘p’ means paste. Figure 1.14 shows that the line was copied.

Figure 1.14

Figure 1.14 Copying Lines in a File

To copy multiple lines of code, move the cursor to line ‘2’ and type ‘2yy’. Move the cursor to line ‘3’ and enter ‘p’ to copy two lines (Figure 1.15). Typing a number followed by ‘yy’ enables copying of any number of lines.

Figure 1.15

Figure 1.15 Copying Multiple Lines in a File

To cut (delete) a line of code, move the cursor to the line and enter ‘dd’. To delete multiple lines, type a number followed by ‘dd’. Let’s delete lines 3, 4, and 5. Move cursor to line ‘3’, and enter ‘3’ followed by ‘dd’ (Figure 1.16).

Figure 1.16

Figure 1.16 Deleting Lines from a File

Now, let’s copy, rename, and remove files. First, get out of ‘vi’ by pressing the ‘Esc’ key followed by the colon ‘:’ key and type ‘wq’ to save and then quit the file. Next, enter the following:

cp test.php new_test.php

The ‘cp’ command copies the first file to the name of the second file. Type ‘ls’ to see that the file was copied correctly. To view contents of the new file without editing, type the following:

cat new_test.php

To clean clutter from the screen, type the following:

clear

To rename a file, type the following:

mv new_test.php second_test.php

To verify, use the ‘ls’ command. To remove a file, type the following:

rm-rf second_test.php

Be careful when removing files because they cannot be recovered once the command is entered. Table 1.2 summarizes the basic Linux commands and Table 1.3 summarizes the basic ‘vi’ commands.

Table 1.2 Basic Linux Commands

mkdir

create new directory

chmod

change permissions

ls

list (files and directories)

ls-la

list with hidden content

cd

change directory

cd ..

move up tree structure

vi (vim)

create or edit new file

cp

copy file

mv

rename file

rm

remove file

clear

clear screen clutter

Table 1.3 Basic ‘vi’ Commands

:

change to file mode

:set nu

turn on line numbering

:set nonu

turn off line numbering

i

insert mode

esc

end insert mode

yy

copy (yank) line

#yy

copy (yank) # lines

p

paste yanked line(s)

dd

cut (delete) line

#dd

cut (delete) # lines

:w

write file

:wq

write file and quit

:q

quit (no changes)

:q!

forced quit

Linux is case sensitive. As such, ‘W’ and ‘Q’ do not work. To write (save) a file, use lowercase ‘w’. To quit, use lowercase ‘q’. I can’t tell you how many times I’ve typed ‘W’ only to have Linux not respond as I expect!

In the Linux sections, Linux basics to enable an end user to create, modify, and display PHP script content on the Internet were introduced. Linux permissions and how to modify them were also introduced. Finally, Linux and ‘vi’ basic commands were presented. The next section introduces HTML basics.

HTML Basics

This section introduces the HyperText Markup Language (HTML) used in this book. A more comprehensive introduction can be found at www.w3schools.com, which also includes tutorials for CSS, SQL, XML and other languages that might prove useful for students with little or no experience of web programming. Since this book teaches programming, not design, HTML5 and CSS3 are not covered. To program with PHP at a very high level, only basic HTML and CSS are required. HTML5 and CSS3 are essential for those with interest in web design.

Markup

Markup is additional text inserted into an HTML document. Inserted text has three characteristics. First, it is not usually visible to the reader. Second, it is not part of the document’s content. Third, it enhances the document in some manner.

An HTML document is a text file containing small markup tags. The file extension for an HTML document must be ‘htm’ or ‘html’, unless the markup is contained within a scripting language such as PHP. Markup text inserted into an HTML document has meaning to the HTML interpreter.

HTML Tags

HTML tags mark up the structure of a document and embed basic information that tells the web browser how to display content. HTML tags are always enclosed in angle brackets and are not case sensitive. (Linux commands are case sensitive.) HTML tags divide a web page into its basic sections, such as header and body. HTML tags generally have a beginning and matching ending tag. This matching tag strategy contains all document content between a set of tag pairs. As such, content within a container follows the rules of that container. The advantage is that containerization forces tags to be balanced and clearly delineates the rules applied to any given content within the HTML document.

Nesting tags is legal, but containers should always be nested within each other appropriately. White space in the document does not matter to the HTML interpreter. I do, however, recommend that you use whitespace to make the document look as clean as possible to the naked eye. Not every tag in HTML is paired (containerized). Some tags don’t require a closing tag. The break tag ‘<br />’ is one such example.

Markup Types

HTML uses two types of markup – tags and character entities. A character entity is a reference to a particular kind of character that has been predefined or explicitly declared in a document type definition. A document type definition (DTD) is a set of markup declarations that define a document type for HTML. The purpose of a character entity is to provide a way to refer to a universal character in a limited character encoding (e.g., ASCII). Character entities include international characters as well as characters usually included in tags as markup. A character entity begins with an ampersand, followed by the entity name, and ends with a semicolon. The character entity for an ampersand follows:

&

A useful character entity is the one for a nonbreaking space.

Three character entity references that deserve special attention are ‘<’ (less than), ‘>’ (greater than), and ‘"’ (double quote). To apply, replace ‘<’ with ‘<’, ‘>’ with ‘>’, and ‘"’ with ‘"’ when necessary. The availability of these three references is important because HTML uses ‘<’ and ‘>’ to enclose HTML tags, and ‘"’ to enclose strings. PHP also uses ‘"’ to enclose strings. You can therefore use a character entity reference instead of the actual character to mitigate confusion and errors. The character entity references are as follows:

<
>
"

HTML tags have four components – attributes, values assigned to attributes, contents, and end tags. Tags don’t necessarily have to have all four components because some tags lack content, attributes or even end tags. Attributes provide additional information about HTML elements. AnHTML element is an individual component of an HTML document. An HTML matched pair tag acts as a container for an HTML element. An example should help you understand. The ‘input’ tag is used for data input as follows:

<input type="text" name="username" />

The HTML element is ‘input’. The attributes are ‘type’ and ‘name’ with values of ‘text’ and ‘username’ respectively. The ‘input’ tag does not contain any content and does not require an end tag.

Document-Wide Tags

Document-wide tags are those that apply to the whole HTML document. Let’s discuss three of them now. All tags are elements of the ‘<html>’ tag. The first and last tags in a document should always be the HTML tags. The ‘<head>’ tag conveys header information for a document. The ‘<body>’ tag contains document text to be displayed in a browser.

A web page should include ‘<html>’, ‘<head>’, and ‘<body>’ tags as a minimum. The ‘<div>’ tag defines a division or section within an HTML document. Its purpose is to group HTML elements together. One use of ‘<div>’ is to format a block of HTML elements. Another use is to lay out a web page together with CSS. CSS is used to control the style and layout of multiple web pages all at once. The comment tag is used to insert comments into the source code. Comments are not displayed in the browser.

Load File in a Web Browser

To display content on the Internet, web browsers need to access the file by its URL. The appropriate URL consists of the name of the server (host server), followed by your Linux user name preceded by the ‘~’ (tilde) symbol, and ending with the path to the file preceded by the ‘/’ (forward slash) symbol. The path is pretty simple. It is the path to the file inside the ‘public_html’ directory. Do not include ‘public_html’ in the path.

servername/~username/test.php

As a hypothetical path, the following URL displays ‘one.htm’ located in ‘book’ directory (inside ‘public_html’ directory) within user ‘paper’ on server ‘http://dnet.brigham.usu.edu’.

<URL>
http://dnet.brigham.usu.edu/~paper/book/one.htm

The following HTML document includes document-wide tags, the ‘<div>’ tag, and a comment tag. Save the contents in a file and load the URL in a web browser.

1 <html>

2 <head><title>Minimal</title></head>

3 <body>

4 <div style="text-align:center;">

5 <!-- The remaining part is the body. -->

6 Nothing!

7 </div>

8 </body>

9 </html>

Figure 1.17

Figure 1.17 Displaying Different PHP Content on a Web Browser

Since the ‘attribute’ for the ‘<div>’ tag is ‘align:center’ (line 4), the word ‘Nothing!’ (line 6) is centered and displayed (Figure 1.17). Notice that the comment (line 5) was not displayed.

Various HTML Tags

The next HTML example illustrates ‘<body>’, ‘<h2>’, and ‘<p>’ tags. Tag ‘<h2>’ is for a second level heading and ‘<p>’ is the paragraph tag. Notice the use of the ‘style’ attribute (lines 3–6) for setting various background colors (Figure 1.18).

1 <html>

2 <head><title>Body Style Example 1</title></head>

3 <body style="background-color:yellow;">

4 <div style="text-align:center;">

5 <h2 style="background-color:red;">This is a heading</h2>

6 <p style="background-color:green;">This is a paragraph.</p>

7 </body>

8 </html>

Figure 1.18

Figure 1.18 HTML Display from a PHP File

Let’s look at one more example using various tags.

 1 <html>

 2 <head><title>Body Style Example 2</title></head>

 3 <body style="background-color:burlywood;">

 4 <div style="text-align:center;">

 5 <h2 style="background-color:indigo; font-family:arial;color:white;

 6 font-size:20px;"> If you click on the link, you see an alien</h2>

 7 <p style="background-color:coral;">

 8 <a href="alien.gif">Link</a>

 9 </p>

10 </div>

11 </body>

12 </html>

The anchor tag ‘<a href="alien.gif">’ in line 8 allows insertion of an image (in this case a gif image). ‘WinSCP’ can be used to move a downloaded image into the ‘public_html’ directory. Figure 1.19 shows the page. Assuming the image is located in ‘public_html’, clicking on the link displays it. Notice how the ‘<h2>’ tag is split on two separate lines (lines 5 and 6). This is perfectly fine because whitespace doesn’t matter.

Figure 1.19

Figure 1.19 HTML Display with a Hyperlink

Heading tags emphasize text in the body of an HTML document. The second level heading ‘<h2>’ was introduced earlier. Heading tags have nothing to do with the ‘<head>’ tag structure. HTML supports six levels of headings. This code example demonstrates all six heading levels (Figure 1.20).

 1 <html>

 2 <head><title>Heading Levels</title></head>

 3 <body style="background-color:burlywood;">

 4 <div style="text-align:center;">

 5 <h1>Heading 1</h1>

 6 <h2>Heading 2</h2>

 7 <h3>Heading 3</h3>

 8 <h4>Heading 4</h4>

 9 <h5>Heading 5</h5>

10 <h6>Heading 6</h6>

11 </div>

12 </body>

13 </html>

Figure 1.20

Figure 1.20 HTML Display of Headers

Paragraph tags separate blocks of text in a meaningful manner. Notice that the ‘<div>’ tag contains the style for centering text (lines 4 and 15). As a result, all HTML between the ‘<div>’ tags centers text when displayed in a web browser. This code example illustrates usage of the ‘<p>’ tag (Figure 1.21).

 1 <html>

 2 <head><title>Paragraphs</title></head>

 3 <body style="background-color:burlywood;">

 4 <div style="text-align:center;">

 5 <p>

 6 Paragraphs can be any length.<br />

 7 They contain blocks of text.<br />

 8 </p>

 9 <p>

10 This is the second paragraph.

11 </p>

12 <p>

13 This is the third paragraph.

14 </p>

15 </div>

16 </body>

17 </html>

Figure 1.21

Figure 1.21 HTML Display of Paragraphs

The next example again uses the ‘style’ attribute within a ‘<div>’ tag (line 4) to center content (Figure 1.22).

 1 <html>

 2 <head><title>Center Content</title></head>

 3 <body style="background-color:burlywood;">

 4 <div style="text-align:center;">

 5 <p>

 6 Center within 'div' tags

 7 </p>

 8 </div>

 9 </body>

10 </html>

Figure 1.22

Figure 1.22 HTML Display of Centered Text

Line break tags ‘<br />’ force a line break in the browser (lines 5–7). The code example uses this tag (Figure 1.23).

 1 <html>

 2 <head><title>Line Break Example</title></head>

 3 <body style="background-color:burlywood;">

 4 <div style="text-align:center;">

 5 Here is one line of text.<br />

 6 Here is another line of text.<br />

 7 Here is yet another line of text.<br />

 8 </div>

 9 </body>

10 </html>

Figure 1.23

Figure 1.23 HTML Display of Multi-Line Centered Text

In the next example (Figure 1.24), the preformatted tag ‘<pre>’ (lines 5 and 10) generates text in a fixed-width font. This tag displays text information as typed in the document. Notice how its style attribute overrides the centering style defined by the ‘<div>’ tag.

 1 <html>

 2 <head><title>Preformatted Tag</title></head>

 3 <body style="background-color:burlywood;">

 4 <div style="text-align:center;">

 5 <pre style="text-align:left;">

 6 some commands

 7 some more commands

 8 even a few more commands

 9 fin

10 </pre>

11 </div>

12 </body>

13 </html>

Figure 1.24

Figure 1.24 HTML Display Using ‘<pre>’ Tag

Logical style tags define the relative appearance of text. They allow the browser to define how to display information. All browsers are able to interpret logical style tags correctly because the associated logical function provides meaning for the tag. The next code example demonstrates emphasis ‘<em>’, strong ‘<strong>’, and cite ‘<cite>’ (lines 5 and 8) logical style tags (Figure 1.25).

 1 <html>

 2 <head><title>Logical Style Tags</title></head>

 3 <body style="background-color:burlywood;">

 4 <div style="text-align:center;">

 5 This <em>silly</em> sentence <strong>shows</strong> <br />

 6 how logical style tags operate.<br />

 7 <p>

 8 <cite>Paper, D. (2003) How to Fly. Journal, 1, 1, 20-30.</cite>

 9 </div>

10 </body>

11 </html>

Figure 1.25

Figure 1.25 HTML Display of Logical Style Tags

Physical style tags define the precise appearance of text. They do not allow the browser to define how to display information because no logical functions are associated with them. Browsers may interpret differently, so use logical style tags whenever possible. The code example illustrates use of italics ‘<i>’, bold ‘<b>’, and citation ‘<tt>’ (lines 5 and 8) physical style tags (Figure 1.26).

 1 <html>

 2 <head><title>Physical Style Tags</title></head>

 3 <body style="background-color:burlywood;">

 4 <div style="text-align:center;">

 5 This <i>silly</i> sentence <b>shows</b> <br />

 6 how physical style tags operate.<br />

 7 <p>

 8 <tt>Paper, D. (2003) How to Fly. Journal, 1, 1, 20-30.</tt>

 9 </div>

10 </body>

11 </html>

Figure 1.26

Figure 1.26 HTML Display of Physical Style Tags

Although italics and bold worked as expected, the citation did not. Images can be clip art, icons, animated art or pictures in one of the following formats – jpeg, xbm, gif, and png. The image ‘<img>’ tag (line 5) is used to display images. In the code example, a gif is displayed as an image rather than as part of an anchor tag. (Note: I used ‘WinSCP’ to copy ‘alien.gif’ to my Linux account.)

1 <html>

2 <head><title>Image Example</title></head>

3 <body style="background-color:burlywood;">

4 <div style="text-align:center;">

5 <img src="alien.gif" title="Gnome" />

6 </div>

7 </body>

8 </html>

HTML tables are defined with the ‘<table>’ tag. A table is divided into rows (with the ‘<tr>’ tag), and each row is divided into data cells (with the ‘<td>’ tag). The letters ‘td’ stand for table data and the <td> tag holds the content of a data cell. A ‘<td>’ tag can contain text, links, images, lists, forms, and other tables. The following example creates a simple table. The ‘<style>’ tag contained in the ‘<head>’ tag includes CSS (lines 4–7) to center the table and create good margins. The ‘class’ attribute in the ‘<table>’ tag (line 12) makes use of the CSS style (Figure 1.27).

 1 <html>

 2 <head>

 3 <style type="text/css">

 4 table.center {

 5 margin-left:auto;

 6 margin-right:auto;

 7 }

 8 </style>

 9 </head>

10 <body style="background-color:burlywood;">

11 <div>

12 <table class="center" border="2">

13 <caption>Simple Table</caption>

14 <tr><th>Heading 1</th><th>Heading 2</th><th>

15 Heading 3</th></tr>

16 <tr><td>100</td><td>200</td><td>300</td></tr>

17 <tr><td>150</td><td>250</td><td>100</td></tr>

18 </table>

19 </div>

20 </body>

21 </html>

Figure 1.27

Figure 1.27 HTML Display of Simple Table

HTML Forms

HTML forms are used to select different kinds of user input. A form requests input from a user. It contains normal content and controls. Controls allow users to interact with forms. The input tag ‘<input>’ specifies simple input inside a form. The ‘<form>’ tag specifies a fill-out form. You can use attributes of both tags (‘<form>’ and ‘<input>’) to customize the displayed form.

Multiple forms can exist within a single document, but cannot be nested. Forms use two attributes – ‘action’ and ‘method’. ‘Action’ specifies the URL to which the form’s contents will be submitted. If this attribute is absent, the web browser will use the current URL. ‘Method’ is the means by which form data are sent between web pages.

Two types of methods can be used – ‘get’ and ‘post’ – to pass data between web pages. Both methods are discussed next.

Get and Post

The default is ‘get’. The ‘get’ method causes the fill-out form contents to be appended to the URL as if they were a normal query. This makes the ‘get’ less secure because users can see the data appended to the URL. The ‘post’ method causes the fill-out form contents to be sent to the server in a data body rather than as part of the URL, which makes it more secure than ‘get’.

Input Tag

The ‘<input>’ tag is standalone, which means that no closing tag is needed. The more useful attributes of this tag include ‘type’, ‘name’, ‘value’, ‘checked’, ‘size’, and ‘maxlength’.

The ‘type’ attribute is the type of input and can be ‘text’, ‘password’, ‘checkbox’, ‘radio’, ‘submit’ or ‘reset’. The ‘name’ attribute is the symbolic name of the input field. The ‘value’ attribute is the value based on the type of input from the ‘type’ attribute. The ‘checked’ attribute is for a ‘checkbox’ or ‘radio’ type of input. The ‘size’ attribute indicates the size of the input field in characters. The ‘maxlength’ attribute indicates the maximum number of characters that are acceptable. The code example illustrates how to implement a checkbox (lines 12 and 15). Output is shown in Figure 1.28.

 1 <html><head>

 2 <style type="text/css">

 3 table.center {

 4 margin-left:auto;

 5 margin-right:auto;

 6 }

 7 </style></head>

 8 <body style="background-color:burlywood;">

 9 <div style="text-align:center;">

10 <form>Please make your choice:<br/>

11 <table class="center"><tr>

12 <td><input type="checkbox" name="apples" /></td>

13 <td>I like fruit!</td>

14 </tr><tr>

15 <td><input type="checkbox" name="carrot" /></td>

16 <td>I like veggies!</td>

17 </tr></table>

18 </form>

19 </div></body></html>

Figure 1.28

Figure 1.28 HTML Display of Checkbox

The following code illustrates how to implement a drop-down menu (lines 12–16). Output is shown in Figure 1.29.

 1 <html><head>

 2 <style type="text/css">

 3 table.center {

 4 margin-left:auto;

 5 margin-right:auto;

 6 }

 7 </style></head>

 8 <body style="background-color:burlywood;">

 9 <div style="text-align:center;">

10 <form method="post" action="next_page.html">

11 <table class="center"><tr>

12 <td><select name="menu1">

13 <option selected>Choice one</option>

14 <option>Choice two</option>

15 <option>Choice three</option>

16 </td></select></tr>

17 </table>

18 <table class="center"><tr>

19 <td><input style="text-align:center;" type="submit"

20 value="Submit" /></td>

21 <td><input style="text-align:center;" type="reset"

22 value="Reset" /></td>

23 </tr></table></form>

24 </div></body></html>

Figure 1.29

Figure 1.29 HTML Display of Drop-Down List

Drop-down menus are very useful when working with data from a database. The following code illustrates how to implement a radio button (lines 12–17). Output is displayed in Figure 1.30.

 1 <html><head>

 2 <style type="text/css">

 3 table.center {

 4 margin-left:auto;

 5 margin-right:auto;

 6 }

 7 </style></head>

 8 <body style="background-color:burlywood;">

 9 <div style="text-align:center;">

10 <form method="post" action="handle_card.php">

11 <table class="center"><tr>

12 <td>Visa:</td><td><input type="radio" checked name="card"

13 size=4 /></td></tr><tr>

14 <td>Mastercard:</td><td><input type="radio" name="card"

15 size=20 /></td></tr><tr>

16 <td>Discover:</td><td><input type="radio" name="card"

17 size=20 /></td></tr>

18 </table>

19 <table class="center"><tr>

20 <td><input align="text-align:center;" type="submit" name="submit"

21 value="Submit" /></td>

22 <td><input align="text-align:center;" type="reset" name="reset"

23 value="Reset" /></td></tr>

24 </table></form>

25 </div></body></html>

Figure 1.30

Figure 1.30 HTML Display of Radio Button

In this section, HTML was introduced with examples to help you understand how it works. Website www.w3schools.com offers a more comprehensive introduction to HTML as well as other technologies like PHP, JavaScript, CSS, SQL, and XML. The next section introduces the basics of PHP. With PHP, you will learn how to make use of HTML forms and the data that are passed to them.

PHP Basics

PHP is a server-side scripting language, which means that PHP scripts are run on the server. The file extension for a PHP script must be ‘php’. In my experience of teaching PHP, students who have a basic understanding of HTML and JavaScript fare much better. However, knowledge of HTML is more critical.

PHP works very well with Oracle. Oracle has committed significant resources in developing, testing, optimizing, and supporting open-source technologies such as PHP. Actually, PHP is Oracle’s web scripting language of choice.

PHP files can contain text, HTML tags, and scripts. PHP can run on different platforms, but I only have experience working with the language on Linux. So, the book assumes you are running PHP on Linux. However, all PHP scripts provided in this book should run on any platform.

Syntax

A PHP file must begin with ‘<?php’ and end with ‘?>’. To reduce spurious errors, be sure to place the beginning ‘<?php’ tag on the first line, first (leftmost) column of the file. Also, be sure to leave no blanks or lines after the ending ‘?>’ tag.

A PHP file typically contains HTML tags and PHP scripting code. In later chapters, I add SQL and JavaScript to PHP files. Each code line in PHP must end with a semicolon ‘;’. To display text on a web browser, two statements can be used – ‘echo’ and ‘print’. I prefer using ‘echo’ because it is a bit shorter in length. PHP comments include ‘//’ for a single-line comment and a matching pair of ‘/*’ and ‘*/’ to enclose a comment block. PHP file ‘first.php’ includes comments and displays some text (Figure 1.31). The file contains no HTML.

1 <?php

2 // File first.php

3 /* This file uses an 'echo' statement to display

4 simple output to the browser

5 */

6 echo "Hello World";

7 ?>

Figure 1.31

Figure 1.31 PHP Display of Simple Text

I like to begin each PHP file with a single-line comment that contains the name of the file (line 2). In this case, the file is named ‘first.php’. Although not required, I explicitly name each PHP file with a single-line comment to avoid confusion as I build multiple PHP files throughout the course of this book. I used blocked commenting to add multi-line comments (lines 3–5). Finally, I used ‘echo’ to display some simple text (line 6).

Variables

Variables are containers for storing information. PHP variables start with a ‘$’ sign followed by the name of the variable. A variable must begin with a letter or the underscore character and can only contain alphanumeric characters and underscores. A variable name cannot contain spaces. Finally, variable names in PHP are case sensitive. A PHP variable is created the moment you first assign it a value. PHP file ‘variable.php’ shows how variables work.

1 <?php

2 // File variable.php

3 $username = 'dave';

4 $password = 'paper';

5 echo "The username is: $username<br />";

6 echo "The password is: $password";

7 ?>

Figure 1.32

Figure 1.32 PHP Display Variables Interpreted

The variable ‘$username’ and ‘$password’ are assigned ‘dave’ and ‘paper’, respectively (lines 3 and 4). The strings are displayed with two ‘echo’ statements (lines 5 and 6). Figure 1.32 shows what is displayed by loading the URL for the PHP code in a browser.

Be careful with quotation marks because single and double quotes are interpreted differently in ‘echo’ statements. In the next example, single quotes are used instead of double quotes.

1 <?php

2 // File variable.php

3 $username = 'dave';

4 $password = 'paper';

5 echo 'The username is: $username<br />';

6 echo 'The password is: $password';

7 ?>

Figure 1.33

Figure 1.33 PHP Display with Variables Not Interpreted

Figure 1.33 shows that variables are not interpreted by the PHP engine when single quotes are used (lines 5 and 6). So, use double quotes if you want the PHP engine to interpret variable values. However, you can use either single or double quotes when assigning a string to a variable.

Concatenation

The concatenation operator ‘.’ is used to put two string values together. PHP file ‘concatenate.php’ uses concatenation to join strings ‘dave’ and ‘paper’ (line 5). Notice that in line 5, I place a space between first and last names to improve what is displayed (Figure 1.34).

1 <?php

2 // File concatenate.php

3 $fname = 'dave';

4 $lname = 'paper';

5 echo "The name is: " . $fname . " " . $lname;

6 ?>

Figure 1.34

Figure 1.34 PHP Display with Concatenated Variable

Functions

PHP supports two types of function – built-in and custom. Built-in functions provide a simple way to use functionality without having to build your own code. PHP file ‘function.php’ introduces three useful functions – ‘strlen()’, ‘strpos()’, and ‘substr()’.

The ‘strlen()’ function returns the length of a string and accepts one parameter (the string). The ‘strpos()’ function searches for a character or text within a string and accepts two parameters (the string and a string to search for within it). The ‘substr()’ function returns part of a string and accepts either two or three parameters (the string, starting position (within the string), and length (characters beginning from the starting position). If the length parameter is omitted, the substring starting from the starting position until the end of the string is returned. A parameter is used in a function to refer to one of the pieces of data provided as input to the function. Parameters can also be referred to as arguments.

 1 <?php

 2 // File function.php

 3 $db = "Oracle 12c";

 4 $search1 = "Oracle";

 5 $search2 = "12c";

 6 echo strlen($db) . '<br />';

 7 echo strpos($db,$search1) . '<br />';

 8 echo substr($db,0) . '<br />';

 9 echo substr($db,1) . '<br />';

10 echo substr($db,7,3) . '<br />';

11 echo substr($db,0,3) . '<br />';

12 echo substr($db,0,-4) . '<br />';

13 ?>

Figure 1.35

Figure 1.35 PHP Display with String Functions

As shown in Figure 1.35, ‘Oracle 12c’ has a length of ‘10’ (line 6) and position of ‘Oracle’ in ‘Oracle 12c’ begins at ‘0’ (line 7). In PHP, strings begin at index ‘0’ rather than index ‘1’. The substring of ‘Oracle 12c’ starting at position ‘0’ (line 8) is ‘Oracle 12c’. The substring of ‘Oracle 12c’ starting a position ‘1’ is ‘racle 12c’ (line 9). The substring of ‘Oracle 12c’ starting at position ‘7’ and going forward three characters is ‘12c’ (line 10). The substring of ‘Oracle 12’ starting at position ‘0’ and going forward three characters is ‘Ora’ (line 11). Finally, the substring of ‘Oracle 12c’ starting at position ‘0’ while removing the last four characters is ‘Oracle’ (line 12). Using a negative number as the third parameter in a ‘substr()’ function indicates the number of characters to omit from the end of the string.

custom function is one that is built by the programmer to automate a set of tasks. A custom function can also be referred to as a user-defined function. The following example creates a custom function that returns the average of the elements in an array. An array is a variable that holds multiple values of the same type. I put ‘custom.php’ in one file and ‘invoke_custom.php’ in another file to enhance modularity. To display results, load ‘invoke_custom.php’ (URL pointing to the file) in a web browser (Figure 1.36).

1 <?php

2 // File custom.php

3 function calc_avg_array($arr)

4 {

5 $avg = array_sum($arr)/count($arr);

6 return $avg;

7 }

8 ?>

1 <?php

2 // File invoke_custom.php

3 require_once('custom.php');

4 $array = array(10,20,30,40,50);

5 $result = calc_avg_array($array);

6 echo "Average is: " . $result;

7 ?>

Figure 1.36

Figure 1.36 PHP Display with Calculated Average

PHP file ‘custom.php’ includes function ‘calc_avg_array’ (lines 3–7), which accepts a parameter assumed to be an array (line 3), calculates the average of the array elements (line 5) and returns the result to the calling environment (line 6). Built-in function ‘array_sum()’ (line 5) returns the sum of array elements and built-in function ‘count()’ (line 5) returns the number of array elements. Using these two built-in functions, it is easy to calculate the average.

PHP file ‘invoke_custom.php’ includes the contents of ‘custom.php’ with the ‘require_once()’ function (line 3) so that the custom function is within scope of the invoking program. That is, to use code from another file you must include the contents of the other file in the calling program. Variable ‘$array’ holds the array contents (line 4). Variable ‘$result’ invokes function ‘calc_avg_array()’ with the array ‘$array’ as parameter (line 5). The ‘echo’ displays results (line 6).

Arrays

A PHP array is actually an ordered map that associates values to keys. A key points to an array element (value). Keys can be named or numbered. Numbered keys are the default and begin with index ‘0’, so you need not define numbered keys explicitly. PHP file ‘simple_array.php’ illustrates how array keys map to array elements (values). Figure 1.37 displays the results.

 1 <?php

 2 // File simple_array.php

 3 $arr1 = array

 4 (

 5 "dog" => "dalmation",

 6 "cat" => "persian",

 7 "bird" => "cockatoo"

 8 );

 9 $arr2 = array

10 (

11 "dalmation",

12 "persian",

13 "cockatoo"

14 );

15 echo "<strong>named key</strong><br />";

16 echo "My new cat is a: " . $arr1["cat"] . '<br />';

17 echo "<strong>number key</strong><br />";

18 echo "My new cat is a: " . $arr2[1];

19 ?>

Figure 1.37

Figure 1.37 PHP Display with Arrays

The first array ‘$arr1’ (lines 3–8) uses ‘named’ keys, while the second array ‘$arr2’ (lines 9–14) uses ‘numbered’ keys. You don’t need to provide keys explicitly when using the ‘numbered’ (default) option. Keep in mind that numbered keys start with index ‘0’, so the key to access the ‘cat’ element (line 18) is index ‘1’(second position in the array). The key to access ‘cat’ element using a named key is "cat" (line 16).

Conditional Statements

Conditional statements are used to perform different actions based on different conditions. PHP uses ‘if’, ‘else’, and ‘elseif’ statements to perform conditional branches. PHP file ‘if_else.php’ illustrates how to use conditional branching (Figure 1.38).

 1 <?php

 2 // File if_else.php

 3 $val = 10;

 4 if($val < 10)

 5 {

 6 echo "Value less than 10";

 7 }

 8 elseif($val > 10)

 9 {

10 echo "Value greater than 10";

11 }

12 elseif($val == 10)

13 {

14 echo "Value equal to 10";

15 }

16 else

17 {}

18 ?>

Figure 1.38

Figure 1.38 PHP Display with Conditional Statements

The first condition (lines 4–7) tests whether ‘$val’ is less than ‘10’. Since it is not, PHP moves to the second condition (lines 8–11), which tests whether ‘$val’ is greater than ‘10’. Since it is not, PHP moves to the third condition (lines 12–15), which tests whether ‘$val’ is equal to ‘10’. Notice in line 12 that two consecutive equal symbols ‘==’ are required to test for equivalency. Since ‘$val’ is equal to ‘10’, the condition is true and the echo is executed.

Be very careful with equivalency because two consecutive equal symbols ‘==’ are required. Using only one equal sign actually assigns the value to the variable, which means that the condition will always be true! Notice that the last condition ‘else’ (lines 16 and 17) includes empty curly brackets ‘{}’, which means that no action is taken if this condition is true.

PHP Iteration

PHP supports three types of iteration (looping) – ‘while’, ‘for’, and ‘foreach’. Loops execute a block of code a specified number of times, or while a specified condition is true.

A ‘while’ loop iterates through a block of code while a specified condition is true. A ‘for’ loop iterates through a block of code a specified number of times. A ‘foreach’ loop iterates through a block of code for each element in an array or object. PHP file ‘loop.php’ illustrates each type of loop.

 1 <?php

 2 // File loop.php

 3 $i = 1;

 4 echo "<strong>while loop</strong><br />";

 5 while($i <= 2)

 6 { echo "The number is " . $i . '<br />';

 7 $i++; }

 8 echo "<strong>for loop</strong><br />";

 9 for($i=1; $i<=2; $i++)

10 { echo "The number is " . $i . '<br />'; }

11 $array = array

12 ( "ford" => "mustang",

13 "chevrolet" => "camaro",

14 "mazda" => "miata" );

15 echo "<strong>foreach loop</strong><br />";

16 foreach($array as $key=>$value)

17 { echo $key . ' => ' . "$value<br />"; }

18 ?>

Figure 1.39

Figure 1.39 PHP Display with Loops

The ‘while’ and ‘for’ loop are very similar, except ‘while’ continues as long as the value meets the condition, but ‘for’ knows in advance how many times the script should run. The ‘while’ loop continues as long as variable ‘$i’ is less than or equal to 2 (line 5). Variable ‘$i’ is incremented by one with ‘$i++’ (line 7). The ‘for’ loop begins with value of ‘1’, continues until it is less than or equal to ‘2’, and is incremented by one (line 9). The ‘foreach’ loop is designed to work with arrays and objects. The ‘foreach’ loop (line 16) displays the ‘key’ and ‘value’ pairs (line 17). Run the code to see what is displayed (Figure 1.39).

PHP ‘$_GET’ Variable

The predefined ‘$_GET’ variable is used to collect values in a form where information sent is displayed in the address bar of the browser. There is a limit on the amount of information that can be sent.

The following example illustrates how this variable is used. There are two files. The first file contains the HTML form, but is named ‘get.php’ to adhere to the naming convention I use in this book. A comment to name the file is the only logic contained between the PHP tags (lines 1–3). The form’s ‘method’ and ‘action’ are defined in line 13. So, the form uses ‘get’ to send data to the file ‘handle_get.php’ (identified with the ‘action’ attribute) upon submission. User inputs are defined in lines 15 through 18 with ‘input’ tags. The ‘input’ tags define data to be passed with ‘type’ as text and ‘name’ as "username" and "password", respectively. Form submission is defined in lines 21 and 22 with an ‘input’ tag.

 1 <?php

 2 // File get.php

 3 ?>

 4 <html><head>

 5 <style type="text/css">

 6 table.center {

 7 margin-left:auto;

 8 margin-right:auto;

 9 }

10 </style></head>

11 <body style="background-color:burlywood;">

12 <div style="text-align:center;">

13 <form method="get" action="handle_get.php">

14 <table class="center"><tr>

15 <td>User:</td><td><input type="text"

16 name="username" /></td></tr><tr>

17 <td>Password:</td><td><input type="text"

18 name="password" /></td></tr><tr>

19 </table>

20 <table class="center"><tr>

21 <td><input align="text-align:center;" type="submit"

22 name="submit" value="Submit" /></td>

23 <td><input align="text-align:center;" type="reset"

24 name="reset" value="Reset" /></td></tr>

25 </table></form>

26 </div></body></html>

The second file contains logic to handle the information sent with the form and is named ‘handle_get.php’. Lines 3 and 4 set ‘get’ input from the form to variables with ‘$_GET’, which holds key–value pairs (where keys are the names of the form controls and values are the input data from the user).

1 <?php

2 // File handle_get.php

3 $username = $_GET["username"];

4 $password = $_GET["password"];

5 echo "The username is: " . $username;

6 echo "<br />The password is: " . $password;

7 ?>

Load ‘get.php’ in a browser, enter a ‘username’ and ‘password’, and click the ‘submit’ button. Figure 1.40 shows the form with data entered just prior to submission. Figure 1.41 shows the data passed by the form. Notice that the values of ‘username’ and ‘password’ are visible within the URL in the browser bar.

Figure 1.40

Figure 1.40 PHP Display with ‘GET’ Form

Figure 1.41

Figure 1.41 PHP Display with ‘GET’ Form Result

PHP ‘$_POST’ Variable

The predefined ‘$_POST’ variable is used to collect values in a form where information sent is invisible to others. There are no limits on the amount of data that can be sent.

The following example illustrates how this variable is used. There are two files. The first file contains the HTML form and is named ‘post.php’. A comment to name the file is the only logic contained between the PHP tags (lines 1–3). The form’s ‘method’ and ‘action’ are defined in line 13. So, the form uses ‘post’ to post data to ‘handle_post.php’ (identified with the ‘action’ attribute) when the form is submitted. User inputs are defined in lines 15 through 18 with ‘input’ tags. The ‘input’ tags define data to be passed with ‘type’ as text and ‘name’ as "username" and "password", respectively. Form submission is defined in lines 21 and 22 with an ‘input’ tag.

 1 <?php

 2 // File post.php

 3 ?>

 4 <html><head>

 5 <style type="text/css">

 6 table.center {

 7 margin-left:auto;

 8 margin-right:auto;

 9 }

10 </style></head>

11 <body style="background-color:burlywood;">

12 <div style="text-align:center;">

13 <form method="post" action="handle_post.php">

14 <table class="center"><tr>

15 <td>User:</td><td><input type="text"

16 name="username" /></td></tr><tr>

17 <td>Password:</td><td><input type="text"

18 name="password" /></td></tr><tr>

19 </table>

20 <table class="center"><tr>

21 <td><input align="text-align:center;" type="submit"

22 name="submit" value="Submit" /></td>

23 <td><input align="text-align:center;" type="reset"

24 name="reset" value="Reset" /></td></tr>

25 </table></form>

26 </div></body></html>

The second file contains logic to handle the information sent with the form and is named ‘handle_post.php’. Lines 3 and 4 set ‘post’ input from the form to variables with ‘$_POST’, which holds key–value pairs (where keys are the names of the form controls and values are the input data from the user).

1 <?php

2 // File handle_post.php

3 $username = $_POST["username"];

4 $password = $_POST["password"];

5 echo "The username is: " . $username;

6 echo "<br />The password is: " . $password;

7 ?>

Load ‘post.php’ in a browser, enter a ‘username’ and ‘password’, and click the ‘submit’ button. Figure 1.42 shows the form with data entered just prior to submission. Figure 1.43 shows the data passed by the form. Notice that values of "username" and "password" are not visible within the URL in the browser bar.

Figure 1.42

Figure 1.42 PHP Display with ‘POST’ Form

Figure 1.43

Figure 1.43 PHP Display with ‘POST’ Form Result

JavaScript Basics

JavaScript is the most popular object-oriented programming language in the world. It allows developers to control the behavior of web pages. In this section, I will cover JavaScript basics. A more comprehensive coverage can be found at www.w3schools.com/js/default.asp.

HTML Document Object Model (DOM)

The HTML DOM is the W3C standard for accessing HTML elements. JavaScript can change HTML content by manipulating the DOM. The first example demonstrates how JavaScript can change the value of the source attribute (src) of an HTML ‘image’ element.

The first file is ‘light.js’. It contains a function defining an ‘image’ variable that points to a location within an HTML document, uses two ‘gif’ files (one image is an ‘on’ light, the other is an ‘off’ light), and runs an ‘if-else’ branch to control processing. Line 1 uses a comment to identify the file name as ‘light.js’. Line 2 uses the ‘function’ keyword to define the function name ‘light’. The variable ‘image’ (line 4) points to ‘myImage’ inside an HTML document. The ‘if’ condition ‘image.src.match("bulbon")’ (line 5) uses method ‘match’ on the ‘src’ attribute (within the ‘image’ tag of the HTML document) to check if the bulb is on or off. If true, the ‘off’ light image is displayed (line 6). The ‘else’ condition (line 7) runs if the bulb is ‘off’ and displays the ‘on’ light (line 8).

1 // File light.js

2 function light()

3 {

4 var image = document.getElementById('myImage');

5 if(image.src.match("bulbon"))

6 { image.src = "pic_bulboff.gif"; }

7 else

8 { image.src = "pic_bulbon.gif"; }

9 }

The second file ‘on_off.php’ uses the ‘script’ tag to identify the external file ‘light.js’ (line 7). The image tag (line 8) use attribute ‘id’ to define the image, the ‘onclick()’ event handler (line 8) to identify the function to be run when the image is clicked, and the source file of the ‘off’ image (line 9).

 1 <?php

 2 // File on_off.php

 3 ?>

 4 <html>

 5 <body>

 6 <div style="text-align:center">

 7 <script src="light.js"></script>

 8 <img id="myImage" onclick="light()"

 9 src="pic_bulboff.gif" width="50" height="50">

10 <p>Click to turn on/off</p>

11 </div>

12 </body>

13 </html>

The ‘gif’ images are included on the companion website (Chapter 1 folder). Both ‘gif’ images must be copied to your Linux account for the scripts to work. Be careful to use the ‘.js’ file extension for external JavaScript files.

Load the ‘on_off.php’ URL in a web browser. Figure 1.44 shows the light bulb in the ‘off’ state. Click the image. Figure 1.45 shows the bulb in the ‘on’ state.

Figure 1.44

Figure 1.44 Light Bulb ‘Off’ Using JavaScript

Figure 1.45

Figure 1.45 Light Bulb ‘On’ Using JavaScript

Validate Data

JavaScript can validate input data. To demonstrate, two files are used for this example – ‘validate.php’ and ‘validate.js’.

The ‘validate.js’ file checks whether a number is between 1 and 10 or whether it is an illegal number with function ‘isNaN()’. Specifically, line 4 defines variables ‘x’ and ‘text’. Line 5 assigns the value of the input field with id="number" in the HTML document to ‘x’. The ‘if’ condition (lines 6 and 7) checks whether the number is less than 1 or greater than 10 (that is, whether it is an illegal number). If true, "Input not valid" is assigned to ‘text’. Otherwise (lines 8 and 9), "Input OK" is assigned to ‘text’. Finally, the ‘text’ value is placed in the HTML document where id="doit", which is the second paragraph tag (<p>).

 1 // File validate.js

 2 function validate()

 3 {

 4 var x, text;

 5 x = document.getElementById("number").value;

 6 if(isNaN(x) || x < 1 || x > 10)

 7 { text = "Input not valid"; }

 8 else

 9 { text = "Input OK"; }

10 document.getElementById("doit").innerHTML = text;

11 }

The ‘validate.php’ file includes ‘validate.js’ (line 7) and a button tag with the ‘onclick()’ event handler (line 10). The ‘input’ tag (line 9) enables user input and the paragraph with id="doit" (line 12) is where output is directed from the JavaScript function ‘validate()’.

 1 <?php

 2 // File validate.php

 3 ?>

 4 <html>

 5 <body>

 6 <div style="text-align:center">

 7 <script src="validate.js"></script>

 8 <p>Input a number between 1 and 10:</p>

 9 <input id="number" type="text">

10 <button type="button" onclick="validate()">

11 Submit</button>

12 <p id="doit"></p>

13 </div>

14 </body>

15 </html>

Load the ‘validate.php’ URL in a web browser. Figure 1.46 shows the initial state. Figure 1.47 shows what happens when a valid number is entered.

Figure 1.46

Figure 1.46 Initial State Using JavaScript

Figure 1.47

Figure 1.47 After Valid Number Entered Using JavaScript

JavaScript is case sensitive, so ‘x’ and ‘X’ are two different variables. The same is true with function names. Functions ‘light()’ and ‘Light()’ are two different functions.

JavaScript Statements

In HTML, JavaScript statements are ‘commands’ to the web browser. That is, they tell the browser what to do. The following example takes a number as user input and returns the number squared to the browser. It also includes a means to clear the returned number from the browser.

The ‘square.js’ file contains two functions. The ‘square()’ function assigns the value of the input field with id="in" in the HTML document to ‘x’ (line 5). It then squares the value of ‘x’ (line 6) and places the result in the HTML document paragraph tag (<p>) with id="out" (line 7). The ‘clr()’ function places an empty string in the HTML document where id="out" (the paragraph tag), which clears the result from the browser (lines 11 and 12).

 1 // square.js

 2 function square()

 3 {

 4 var x;

 5 x = document.getElementById("in").value;

 6 x = x * x;

 7 document.getElementById("out").innerHTML = x;

 8 }

 9 function clr()

10 {

11 var p = document.getElementById("out");

12 p.innerHTML= "";

13 }

The ‘square.php’ file includes ‘square.js’ (line 7), a button tag for handling the ‘square()’ function (lines 9 and 10), and a button tag for handling the ‘clr()’ function (lines 11 and 12). User input is handled by the ‘input’ tag (line 8) with id="in". The result is handled by the ‘paragraph’ tag (line 13) with id="out".

 1 <?php

 2 // File square.php

 3 ?>

 4 <html>

 5 <body>

 6 <div id="all" style="text-align:center">

 7 <script src="square.js"></script>

 8 <input id="in" type="text">

 9 <button type="button" onclick="square()">

10 Submit</button>

11 <button type="button" onclick="clr()">

12 Clear</button>

13 <p id="out"></p>

14 </div>

15 </body>

16 </html>

Load the ‘square.php’ URL in a web browser. Figure 1.48 shows the initial state. Enter ‘7’ and click on ‘Submit’. Figure 1.49 shows what happens when a number is entered. Click on ‘Clear’ to remove what is displayed (Figure 1.50).

Figure 1.48

Figure 1.48 Initial State Using JavaScript

Figure 1.49

Figure 1.49 After Number Entered Using JavaScript

Figure 1.50

Figure 1.50 Clear Screen Using JavaScript

Summary

The goal of this chapter was to facilitate a fundamental understanding of Linux, HTML, PHP, and JavaScript. I defined concepts as they were discussed in the chapter. Code examples with explanations were used throughout to reinforce learning.