Tải bản đầy đủ (.pdf) (10 trang)

Phát triển web với PHP và MySQL - p 40 potx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (549.6 KB, 10 trang )

Creating, Deleting, and Moving Files
You can use the file system functions to create, move, and delete files.
First, and most simply, you can create a file, or change the time it was last modified, using the
touch() function. This works similarly to the UNIX command touch. The function has the fol-
lowing prototype:
int touch (string file, [int time])
If the file already exists, its modification time will be changed either to the current time, or the
time given in the second parameter if it is specified. If you want to specify this, it should be
given in time stamp format. If the file doesn’t exist, it will be created.
You can also delete files using the
unlink() function. (Note that this function is not called
delete—there is no delete.) You use it like this:
unlink($filename);
This is one of the functions that doesn’t work with the Win32 build. However, you can delete a
file in Windows with
system(“del filename.ext”);
You can copy and move files with the copy() and rename() functions, as follows:
copy($source_path, $destination_path);
rename($oldfile, $newfile);
You might have noticed that we used copy() in Listing 16.2.
The rename() function does double duty as a function to move files from place to place
because PHP doesn’t have a move function. Whether you can move files from file system to
file system, and whether files are overwritten when rename() is used is operating system
dependent, so check the effects on your server. Also, be careful about the path you use to the
filename. If relative, this will be relative to the location of the script, not the original file.
Using Program Execution Functions
We’ll move away from the file system functions now, and look at the functions that are avail-
able for running commands on the server.
This is useful when you want to provide a Web-based front end to an existing command line-
based system. For example, we have used these commands to set up a front end for the mailing
list manager ezmlm. We will use these again when we come to the case studies later in this


book.
Interacting with the File System and the Server
C
HAPTER 16
16
INTERACTING WITH
THE
F
ILE SYSTEM
AND THE
SERVER
365
21 7842 CH16 3/6/01 3:40 PM Page 365
There are four techniques you can use to execute a command on the Web server. They are all
pretty similar, but there are some minor differences.
1. exec()
The exec() function has the following prototype:
string exec (string command [, array result [, int return_value]])
You pass in the command that you would like executed, for example,
exec(“ls -la”);
The exec() function has no direct output.
It returns the last line of the result of the command.
If you pass in a variable as
result, you will get back an array of strings representing
each line of the output. If you pass in a variable as
return_value, you will get the return
code.
2. passthru()
The passthru() function has the following prototype:
void passthru (string command [, int return_value])

The passthru() function directly echoes its output through to the browser. (This is use-
ful if the output is binary, for example, some kind of image data.)
It returns nothing.
The parameters work the same way as exec()’s parameters do.
3. system()
The system() function has the following prototype:
string system (string command [, int return_value])
The function echoes the output of the command to the browser. It tries to flush the output
after each line (assuming you are running PHP as a server module), which distinguishes
it from passthru().
It returns the last line of the output (upon success) or false (upon failure).
The parameters work the same way as in the other functions.
4. Backticks
We mentioned these briefly in Chapter 1, “PHP Crash Course.” These are actually an
execution operator.
They have no direct output. The result of executing the command is returned as a string,
which can then be echoed or whatever you like.
The script shown in Listing 16.5 illustrates how to use each of these in an equivalent fashion.
Advanced PHP Techniques
P
ART IV
366
21 7842 CH16 3/6/01 3:40 PM Page 366
LISTING 16.5 progex.php—File Status Functions and Their Results
<?
echo “<pre>”;
// exec version
exec(“ls -la”, $result);
foreach ($result as $line)
echo “$line\n”;

echo “<br><hr><br>”;
// passthru version
passthru(“ls -la”);
echo “<br><hr><br>”;
// system version
$result = system(“ls -la”);
echo “<br><hr><br>”;
//backticks version
$result = `ls -al`;
echo $result;
echo “</pre>”;
?>
We could have used one of these approaches as an alternative to the directory-browsing script
we wrote earlier.
If you plan to include user-submitted data as part of the command you’re going to execute, you
should always run it through the escapeshellcmd() function first. This stops users from mali-
ciously (or otherwise) executing commands on your system. You can call it like this, for example,
System(escapeshellcmd($command_with_user_data));
Interacting with the Environment: getenv() and
putenv()
Before we leave this section, we’ll look at how you can use environment variables from
within PHP. There are two functions for this purpose:
getenv(), which enables you to retrieve
environment variables, and putenv(), which enables you to set environment variables.
Interacting with the File System and the Server
C
HAPTER 16
16
INTERACTING WITH
THE

F
ILE SYSTEM
AND THE
SERVER
367
21 7842 CH16 3/6/01 3:40 PM Page 367
Note that the environment we are talking about here is the environment in which PHP runs on
the server.
You can get a list of all PHP’s environment variables by running phpinfo(). Some are more
useful than others; for example,
getenv(“HTTP_REFERER”);
will return the URL of the page from which the user came to the current page.
You can also set environment variables as required with putenv(), for example,
$home = “/home/nobody”;
putenv (“ HOME=$home “);
If you would like more information about what some of the environment variables represent,
you can look at the CGI specification:
/>Further Reading
Most of the file system functions in PHP map to underlying operating system functions—try
reading the man pages if you’re using UNIX for more information.
Next
In Chapter 17, “Using Network and Protocol Functions,” we’ll use PHP’s network and protocol
functions to interact with systems other than our own Web server. This again expands the hori-
zons of what we can do with our scripts.
Advanced PHP Techniques
P
ART IV
368
21 7842 CH16 3/6/01 3:40 PM Page 368
CHAPTER

17
Using Network and Protocol
Functions
22 7842 CH17 3/6/01 3:39 PM Page 369
Advanced PHP Techniques
P
ART IV
370
In this chapter, we’ll look at the network-oriented functions in PHP that enable your scripts to
interact with the rest of the Internet. There’s a world of resources out there, and a wide variety
of protocols available for using them. In this section we’ll consider
• An overview of available protocols
• Sending and reading email
• Using other Web services via HTTP
• Using network lookup functions
• Using FTP
• Using generic network communications with cURL
Overview of Protocols
Protocols are the rules of communication for a given situation. For example, you know the pro-
tocol when meeting another person: You say hello, shake hands, communicate for a while, and
then say goodbye. Computer networking protocols are similar.
Like human protocols, different computer protocols are used for different situations and appli-
cations. We use HTTP, the Hypertext Transfer Protocol, for sending and receiving Web pages.
You will probably also have used FTP, file transfer protocol, for transferring files between
machines on a network. There are many others.
Protocols, and other Internet Standards, are described in documents called RFCs, or Requests
for Comments. These protocols are defined by the Internet Engineering Task Force (IETF). The
RFCs are widely available on the Internet. The base source is the RFC Editor at
/>If you have problems when working with a given protocol, the RFCs are the authoritative
source and are often useful for troubleshooting your code. They are, however, very detailed,

and often run to hundreds of pages.
Some examples of well-known RFCs are RFC2616, which describes the HTTP/1.1 protocol,
and RFC822, which describes the format of Internet email messages.
In this chapter, we will look at aspects of PHP that use some of these protocols. Specifically,
we will talk about sending mail with SMTP, reading mail with POP and IMAP, connecting to
other Web servers via HTTP and HTTPS, and transferring files with FTP.
22 7842 CH17 3/6/01 3:39 PM Page 370
Sending and Reading Email
The main way to send mail in PHP is to use the simple mail() function. We discussed the use
of this function in Chapter 4, “String Manipulation and Regular Expressions,” so we won’t
visit it again here. This function uses SMTP (Simple Mail Transfer Protocol) to send mail.
You can use a variety of freely available classes to add to the functionality of mail(). In
Chapter 27, “Building a Mailing List Manager,” we will use the HTML MIME mail class by
Richard Heyes to send HTML attachments with a piece of mail. SMTP is only for sending
mail. The IMAP (Internet Message Access Protocol, described in RFC2060) and POP (Post
Office Protocol, described in RFC1939 or STD0053) protocols are used to read mail from a
mail server. These protocols cannot send mail.
IMAP is used to read and manipulate mail messages stored on a server, and is more sophisti-
cated than POP which is generally used simply to download mail messages to a client and
delete them from the server.
PHP comes with an IMAP library. This can also be used to make POP and NNTP (Network
News Transfer Protocol) as well as IMAP connections.
We will look extensively at the use of the IMAP library in the project described in Chapter 26,
“Building a Web-Based Email Service.”
Using Other Web Services
One of the great things you can do with the Web is use, modify, and embed existing services
and information into your own pages. PHP makes this very easy. Let’s look at an example to
illustrate this.
Imagine that the company you work for would like a stock quote for your company displayed
on its homepage. This information is available out there on some stock exchange site

somewhere—but how do we get at it?
Start by finding an original source URL for the information. When you know this, every time
someone goes to your homepage, you can open a connection to that URL, retrieve the page,
and pull out the information you require.
As an example, we’ve put together a script that retrieves and reformats a stock quote from the
NASDAQ. For the purpose of the example, we’ve retrieved the current stock price of
Amazon.com. (The information you want to include on your page might differ, but the princi-
ples are the same.) This script is shown in Listing 17.1.
Using Network and Protocol Functions
C
HAPTER 17
17
USING NETWORK
AND
PROTOCOL
FUNCTIONS
371
22 7842 CH17 3/6/01 3:39 PM Page 371
LISTING 17.1 lookup.php—Script Retrieves a Stock Quote from the NASDAQ for the
Stock with the Ticker Symbol Listed in $symbol
<html>
<head>
<title>Stock Quote from NASDAQ</title>
</head>
<body>
<?
// choose stock to look at
$symbol=”AMZN”;
echo “<h1>Stock Quote for $symbol</h1>”;
// connect to URL and read information

$theurl = “ />.”page=multi&mode=Stock&symbol=”.$symbol;
if (!($fp = fopen($theurl, “r”)))
{
echo “Could not open URL”;
exit;
}
$contents = fread($fp, 1000000);
fclose($fp);
// find the part of the page we want and output it
$pattern = “(\\\$[0-9 ]+\\.[0-9]+)”;
if (eregi($pattern, $contents, $quote))
{
echo “$symbol was last sold at: “;
echo $quote[1];
} else
{
echo “No quote available”;
};
// acknowledge source
echo “<br>”
.”This information retrieved from <br>”
.”<a href=\”$theurl\”>$theurl</a><br>”
.”on “.(date(“l jS F Y g:i a T”));
?>
</body>
</html>
The output from one sample run of Listing 17.1 is shown in Figure 17.1.
Advanced PHP Techniques
P
ART IV

372
22 7842 CH17 3/6/01 3:39 PM Page 372
FIGURE 17.1
The script uses a regular expression to pull out the stock quote from information retrieved from NASDAQ.
The script itself is pretty straightforward—in fact, it doesn’t use any functions we haven’t seen
before, just new applications of those functions.
You might recall that when we discussed reading from files in Chapter 2, “Storing and
Retrieving Data,” we mentioned that you could use the file functions to read from an URL.
That’s what we have done in this case. The call to fopen()
$fp = fopen($theurl, “r”)
returns a pointer to the start of the page at the URL we supply. Then it’s just a question of
reading from the page at that URL and closing it again:
$contents = fread($fp, 1000000);
fclose($fp);
You’ll notice that we used a really large number to tell PHP how much to read from the file.
With a file on the server, you’d normally use filesize($file), but this doesn’t work with
an URL.
When we’ve done this, we have the entire text of the Web page at that URL stored in
$contents. We can then use a regular expression and the eregi() function to find the part
of the page that we want:
$pattern = “(\\\$[0-9 ]+\\.[0-9]+)”;
if (eregi($pattern, $contents, $quote))
{
echo “$symbol was last sold at: “;
echo $quote[1];
}
That’s it!
Using Network and Protocol Functions
C
HAPTER 17

17
USING NETWORK
AND
PROTOCOL
FUNCTIONS
373
22 7842 CH17 3/6/01 3:39 PM Page 373
You can use this approach for a variety of purposes. Another good example is retrieving local
weather information and embedding it in your page.
The best use of this approach is to combine information from different sources to add some
value. One good example of this approach can be seen in Philip Greenspun’s infamous script
that produces the Bill Gates Wealth Clock:
/>This page takes information from two sources. It obtains the current U.S. population from the
U.S. Census Bureau’s site. It looks up the current value of a Microsoft share and combines
these two pieces of information, adds a healthy dose of the author’s opinion, and produces new
information—an estimate of Bill Gates’ current worth.
One side note: If you’re using an outside information source such as this for a commercial pur-
pose, it’s a good idea to check with the source first. There are intellectual property issues to
consider in some cases.
If you’re building a script like this, you might want to pass through some data. For example, if
you’re connecting to an outside URL, you might like to pass some parameters typed in by the
user. If you’re doing this, it’s a good idea to use the url_encode() function. This will take a
string and convert it to the proper format for an URL, for example, transforming spaces into
plus signs. You can call it like this:
$encodedparameter = url_encode($parameter);
Using Network Lookup Functions
PHP offers a set of “lookup” functions that can be used to check information about hostnames,
IP addresses, and mail exchanges. For example, if you were setting up a directory site such as
Yahoo! when new URLs were submitted, you might like to automatically check that the host of
an URL and the contact information for that site are valid. This way, you can save some over-

head further down the track when a reviewer comes to look at a site and finds that it doesn’t
exist, or that the email address isn’t valid.
Listing 17.2 shows the HTML for a submission form for a directory like this.
LISTING 17.2 directory_submit.html—HTML for the Submission Form
<head>
<title>Submit your site</title>
</head>
<body>
<h1>Submit site</h1>
Advanced PHP Techniques
P
ART IV
374
22 7842 CH17 3/6/01 3:39 PM Page 374

×