You learned what a web server does and how to get one, how to organize your files and install them on the server, and how to find your URL and use it to test your pages.. LESSON 21 Takin
Trang 1Other numbers on the page provide insight into how users are interacting with your site
Bounce Rate shows the percentage of users who leave after visiting your landing page
instead of sticking around to visit more pages on your site The average pages per visit
and average time on site provide a further idea of the degree to which users are drilling
down on your site In some cases, low numbers here may be fine If your page is a set of
links to other sites, a high bounce rate and low time on the site may indicate that users
are finding what they’re looking for and following the links Your interpretation of the
statistics should be based on your goals
Each of the reports on the Dashboard links to a report with more detailed information
For example, if you click the report link for Traffic Sources, you’ll see a more detailed
breakdown of where your traffic originated, including which search terms people used to
find your site
One report shows which browsers and operating systems your visitors are using, so that
you can figure out which features your audiences will be able to take advantage of Other
reports show how many of your users visited for the first time and how many are repeat
visitors There are reports that show which sites link to yours Keeping a close eye on
your Analytics reports will enable you to figure out which parts of your site are working
and which aren’t, whether you use Google Analytics or some other analytics package
Summary
In this lesson, you published your site on the Web through the use of a web server, either
one installed by you or that of a network provider You learned what a web server does
and how to get one, how to organize your files and install them on the server, and how to
find your URL and use it to test your pages You also learned the many ways that you
can advertise and promote your site, and how to use log files and Google Analytics to
keep track of the number of visitors At last, you’re on the Web and people are coming
to visit!
Workshop
As always, we wrap up the lesson with a few questions, quizzes, and exercises Here are
some pointers and refreshers on how to promote your website
616 LESSON 20: Putting Your Site Online
Trang 2Q&A
Q I’ve published my pages at an ISP I really like The URL is something like
http://www.thebestisp.com/users/mypages/ Instead of this URL, I’d like to
have my own hostname, something like http://www.mypages.com/ How can I
do this?
A You have two choices The easiest way is to ask your ISP whether you’re allowed
to have your own domain name Many ISPs have a method for setting up your
domain so that you can still use their services and work with them—it’s only your
URL that changes Note that having your own hostname might cost more money,
but it’s the way to go if you really must have that URL Many web hosting services
have plans starting as low as $5 a month for this type of service, and it currently
costs as little as $16 to register your domain for two years
The other option is to set up your own server with your own domain name This
option could be significantly more expensive than working with an ISP, and it
requires at least some background in basic network administration
Q There are so many search engines! Do I have to add my URL to all of them?
A No, mainly because eventually they will find your site whether you add it to them
or not Adding your URL to a search engine may get it into the results more
quickly, so if you already know about a search engine and can submit your site, do
so Otherwise, don’t worry about it
Quiz
1 What’s the basic function of a web server?
2 What are default index files, and what’s the advantage of using them in all
directo-ries?
3 What are some things that you should check immediately after you upload your
web pages?
4 Name some of the ways that you can promote your website
5 What’s a hit?
Quiz Answers
1 A web server is a program that sits on a machine connected to the Internet (or an
intranet) It determines which resource is associated with a URL and delivers that
resource to the user
20
Trang 32 The default index file is loaded when a URL ends with a directory name rather
than a filename Typical examples of default index files are index.html,
index.htm, and default.htm If you use default filenames, you can use a URL
such as http://www.mysite.com/ rather than http://www.mysite.com/index.html to
get to the home page in the directory
3 Make sure that your browser can reach your web pages on the server, that you can
access the files on your website, and that your links and images work as expected
After you’ve determined that everything appears the way you think it should, have
your friends and family test your pages in other browsers
4 Some ways you can promote your site include major web directories and search
engines, listings on business cards and other promotional materials, and web rings
5 A hit is a request for any file from your website
Exercises
1 Start shopping around and consider where you want to host your website Find a
couple of web hosting firms that look like good options and do some research
online to see what their existing customers have to say about them
2 Upload and test a practice page to learn the process, even if it’s just a blank page
that you’ll add content to later You might work out a few kinks this way before
you actually upload all your hard work on the Web
3 Visit some of the search engines listed in this lesson to obtain a list of the sites
where you want to promote your web page Review each of the choices to see
whether there are special requirements for listing your page
4 Sign up for a Google Analytics account and install it on your site Explore the
reports to see what kind of information it provides about your site
618 LESSON 20: Putting Your Site Online
Trang 4LESSON 21
Taking Advantage of
the Server
At this point, you’ve learned how to publish websites using Hypertext
Markup Language (HTML) This lesson takes things a step further and
explains how to build dynamic websites using scripts on the server Most
websites utilize some kind of server-side processing Search engines take
the user’s request and search an index of web pages on the server
Online stores use server-side processing to look up items in the
inven-tory, keep track of the user’s shopping cart, and handle the checkout
process Newspaper websites keep articles in a database and use
server-side processing to generate the article pages This lesson
intro-duces server-side programming using the PHP language PHP is the most
common scripting platform provided by web hosts, can be easily installed
on your own computer, and is completely free It’s also easy to get
started with Even if you wind up developing your applications using some
other scripting language, you can apply the principles you’ll learn in this
lesson to those languages
In this lesson, you’ll learn the following:
n How PHP works
n How to set up a PHP development environment
n The basics of the PHP language
n How to process form input
n Using PHP includes
Trang 5How PHP Works
PHP enables programmers to include PHP code in their HTML documents, which is
processed on the server before the HTML is sent to the browser Normally, when a user
submits a request to the server for a web page, the server reads the HTML file and sends
its contents back in response If the request is for a PHP file and the server supports PHP,
the server looks for PHP code in the document, executes it, and includes the output of
that code in the page in place of the PHP code Here’s a simple example:
<!DOCTYPE html>
<html>
<head><title>A PHP Page</title</head>
<body>
<?php echo “Hello world!”; ?>
</body>
</html>
If this page is requested from a web server that supports PHP, the HTML sent to the
browser will look like this:
<!DOCTYPE html>
<html>
<head><title>A PHP Page</title</head>
<body>
Hello world!
</body>
</html>
When the user requests the page, the web server determines that it is a PHP page rather
than a regular HTML page If a web server supports PHP, it usually treats any files with
the extension .phpas PHP pages Assuming this page is called something like
hello.php, when the web server receives the request, it scans the page looking for PHP
code and then runs any code it finds PHP code is distinguished from the rest of a page
by PHP tags, which look like this:
<?php your code here ?>
Whenever the server finds those tags, it treats whatever is within them as PHP code
That’s not so different from the way things work with JavaScript, where anything inside
<script>tags is treated as JavaScript code
In the example, the PHP code contains a call to the echofunction This function prints
out the value of whatever is passed to it In this case, I passed the text “Hello world!” to
the function, so that text is included in the page The concept of functions should also be
620 LESSON 21: Taking Advantage of the Server
Trang 6Statements in PHP, as in JavaScript, are terminated with a semicolon (You can see the
semicolon at the end of the statement in the example.) There’s no reason why you can’t
include multiple statements within one PHP tag, like this:
<?php
echo “Hello “;
echo “world!”;
?>
PHP also provides a shortcut if all you want to do is print the value of something to a
page Instead of using the full PHP tag, you can use the expression tag, which just
echoes a value to the page Instead of using
<?php echo “Hello world!”; ?>
You can use this:
<?= “Hello world!” ?>
Replacingphpwith=enables you to leave out the call to the echofunction and the
semi-colon This style of tag is referred to as a short tag Not all PHP installations have short
tags enabled
Getting PHP to Run on Your Computer
Before you can start writing your own PHP scripts, you need to set up a PHP
environ-ment The easiest approach is probably to sign up for a web hosting account that
pro-vides PHP support Even if you do so, though, there are some advantages to getting PHP
to work on your own computer You can edit files with your favorite editor and then test
them right on your own computer rather than uploading them to see how they work
You’ll also be able to work on them even if you’re not online Finally, you can keep from
putting files on a server that your users see without your having tested them first
To process PHP pages, you need the PHP interpreter and a web server that works with
the PHP interpreter The good news is that PHP and the most popular web server,
Apache, are both free, open source software The bad news is that getting PHP up and
running can be a bit of a technical challenge
Fortunately, if you’re a Windows or Mac user, someone else has done this hard work for
you A tool called XAMPP, available for both Windows and OS X, bundles up versions
of Apache, PHP, and MySQL (a database useful for storing data associated with web
applications) that are already set up to work together (The last P is for Perl, another
script-ing language.) You can download it from http://www.apachefriends.org/en/xampp.html
Getting PHP to Run on Your Computer 621
21
Trang 7If you’re a Mac user, you also have the option of using MAMP, another free package that
combines Apache, PHP, and MySQL It can be downloaded from http://www.mamp.info
Mac users also have the option of using the version of Apache and PHP that are included
with OS X
After you’ve installed XAMPP (or MAMP), you just have to start the application to get a
web server up and running that you can use to develop your pages To test your PHP
pages, you can put them in the htdocsdirectory inside the XAMPP install directory For
example, if you want to test the hello.phppage I talked about earlier, you could put it in
thehtdocsdirectory To view it, just go to http://localhost/hello.php
If that doesn’t work, make sure that XAMPP has started the Apache server If you’re
using MAMP, the steps are basically the same Just put your pages in the htdocsfolder,
as with XAMPP
The PHP Language
When you think about the English language, you think about it in terms of parts of
speech Nouns name things, verbs explain what things do, adjectives describe things, and
so on Programming languages are similar A programming language is made up of
vari-ous “parts of speech,” too In this section, I explain the parts of speech that make up the
PHP language—comments, variables, conditional statements, and functions
It might be helpful to think back to the lesson on JavaScript as you read this lesson PHP
and JavaScript share a common ancestry, and many of the basic language features are
similar between the two If things such as the comment format, curly braces, and control
statements look similar from one to the other, it’s because they are
Comments
Like HTML and JavaScript, PHP supports comments PHP provides two comment
styles: one for single-line comments, and another for multiple comments (If you’re
familiar with comments in the C or Java programming language, you’ll notice that PHP’s
are the same.) First, single-line comments To start a single-line comment, use //or#
Everything that follows either on a line is treated as a comment Here are some
exam-ples:
// My function starts here.
$color = ‘red’; // Set the color for text on the page
# $color = ‘blue’;
$color = $old_color; # Sets the color to the old color.
622 LESSON 21: Taking Advantage of the Server
Trang 8The text that precedes //is processed by PHP, so the second line assigns the $color
variable On the third line, I’ve turned off the assignment by commenting it out PHP
also supports multiple-line comments, which begin with /*and end with */ If you want
to comment out several lines of code, you can do so like this:
/*
$color = ‘red’;
$count = 55; // Set the number of items on a page.
// $count = $count + 1;
*/
PHP ignores all the lines inside the comments Note that you can put the //style
com-ment inside the multiline comcom-ment with no ill effects You cannot, however, nest
multi-line comments This is illegal:
/*
$color = ‘red’;
$count = 55; // Set the number of items on a page.
/* $count = $count + 1; */
*/
The PHP Language 623
21
The generally accepted style for PHP code is to use // for single-line comments rather than #
Variables
Variables just provide a way for the programmers to assign a name to a piece of data In
PHP, these names are preceded by a dollar sign ($) Therefore, you might store a color in
a variable called $coloror a date in a variable named $last_published_at Here’s how
you assign values to those variables:
$color = “red”;
$last_published_at = time();
The first line assigns the value “red”to$color; the second returns the value returned by
the built-in PHP function time()to$last_published_at That function returns a
time-stamp represented as the number of seconds since the “UNIX epoch.”
One thing you should notice here is that you don’t have to indicate what kind of
item you’ll be storing in a variable when you declare it You can put a string in it,
as I did when I assigned “red”to$color You can put a number in it, as I did with
$last_published_at I know that the number is a timestamp, but as far as PHP is
NOTE
Trang 9concerned, it’s just a number What if I want a date that’s formatted to be displayed
rather than stored in seconds so that it can be used in calculations? I can use the PHP
date()function Here’s an example:
$last_published_at = date(“F j, Y, g:i a”);
This code formats the current date so that it looks something like “June 10, 2010, 8:47
pm.” As you can see, I can change what kind of information is stored in a variable
with-out doing anything special It just works The only catch is that you have to keep track of
what sort of thing you’ve stored in a variable when you use it For more information
about how PHP deals with variable types, see
http://www.php.net/manual/en/language.types.type-juggling.php
Despite the fact that variables don’t have to be declared as being associated with a
partic-ular type, PHP does support various data types, including string, integer, and float (for
numbers with decimal points) Not all variable types work in all contexts One data type
that requires additional explanation is the array data type
Arrays
The variables you’ve seen so far in this lesson have all been used to store single values
Arrays are data structures that can store multiple values You can think of them as lists of
values, and those values can be strings, numbers, or even other arrays To declare an
array, use the built-in arrayfunction:
$colors = array(‘red’, ‘green’, ‘blue’);
This declaration creates an array with three elements in it Each element in an array is
numbered, and that number is referred to as the index For historical reasons, array
indexes start at 0, so for the preceding array, the index of redis 0, the index of greenis
1, and the index of blueis 2 You can reference an element of an array using its index,
like this:
$color = $colors[1];
By the same token, you can assign values to specific elements of an array, too, like this:
$colors[2] = ‘purple’;
You can also use this method to grow an array, as follows:
$colors[3] = ‘orange’;
What happens if you skip a few elements when you assign an item to an array, as in the
following line?
624 LESSON 21: Taking Advantage of the Server
Trang 10In this case, not only will element 8 be created, but elements 4 through 7 will be created,
too If you want to add an element onto the end of an array, you just leave out the index
when you make the assignment, like this:
$colors[] = ‘yellow’;
In addition to arrays with numeric indexes, PHP supports associative arrays, which have
indexes supplied by the programmer These are sometimes referred to as dictionaries or
as hashes Here’s an example that shows how they are declared:
$state_capitals = array(
‘Texas’ => ‘Austin’,
‘Louisiana’ => ‘Baton Rouge’,
‘North Carolina’ => ‘Raleigh’,
‘South Dakota’ => ‘Pierre’
);
When you reference an associative array, you do so using the keys you supplied, as
fol-lows:
$capital_of_texas = $state_capitals[‘Texas’];
To add a new element to an associative array, you just supply the new key and value, like
this:
$state_capitals[‘Pennsylvania’] = ‘Harrisburg’;
If you need to remove an element from an array, just use the built-in unset()function,
like this:
unset($colors[1]);
The element with the index specified will be removed, and the array will decrease in size
by one element, too The indexes of the elements with larger indexes than the one that
was removed will be reduced by one You can also use unset()to remove elements from
associative arrays, like this:
unset($state_capitals[‘Texas’]);
Array indexes can be specified using variables You just put the variable reference inside
the square brackets, like this:
$i = 1;
$var = $my_array[$i];
This also works with associative arrays:
$str = ‘dog’;
$my_pet = $pets[$str];
The PHP Language 625
21