Professional PHP Programming phần 6

Chia sẻ: Hà Nguyễn Thúy Quỳnh | Ngày: | Loại File: PDF | Số trang:86

lượt xem

Professional PHP Programming phần 6

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Chúng tôi có thể giới thiệu khách truy cập bây giờ là một cách để truy vấn cơ sở dữ liệu whois. Nhưng những gì, nếu chúng ta muốn để cho phép khách truy cập để truy vấn cơ sở dữ liệu nhân? Ví dụ, nếu chúng ta muốn thực hiện các truy vấn cơ sở dữ liệu RIPE và cơ sở dữ liệu InterNIC.

Chủ đề:

Nội dung Text: Professional PHP Programming phần 6

  1. Simpo PDF Merge and Split Unregistered Version - $data .= fread($fp, 1000); } fclose($fp); } return $data; } ?>
  2. Simpo PDF Merge and Split Unregistered Version - W e use the < SELECT> t ag to build up a select box which shows several whois servers. We store the hostname as an option value in the HTML part. This helps us to keep the effort minimal to add new servers. Once the user hits the submit button, the hostname of the server of his or her choice will be send to the server. PHP makes the data available as $server variable. Thus we change our code to reflect this: Y ou see, this part became even simpler! In the next step we will enhance the frontend more and build new functionality into it. Is my domain still available? T oday, a popular way to utilize whois is to offer potential customers the ability to quickly lookup whether specific domains are still available. We will build such a script now. We reuse our w hois_request() f unction from the previous sections. Recall that this function queries a specific whois server for specific information and returns the raw information from the server. It does not perform any analyzing, so we need some additional logic to produce useful output. Up to now, we built a simple query interface for a whois server. Now we add more logic to it. Our design goal is simple. The user enters a domain name and we find out whether the domain is still available or not. If you have examined the previous examples, you will notice that on some queries you get useful replies with real data and that some fail, returning a message like "No entries found for the selected source(s)." We will use this to make the decision whether a specific domain is available. To increase the value of our script, we enable the user to query for different TLDs (top level domains, like COM, NET, GB). To do that, we have to determine the chosen top-level domain. function domain_tld($domain) { $ret = ""; if(ereg("\.([^\.]+)$", $domain, $answer)) $ret = strtolower($answer[1]); TEAM FLY PRESENTS
  3. Simpo PDF Merge and Split Unregistered Version - return $ret; } T he function domain_tld() r eturns the TLD of the domain name passed to it. It uses a regular expression to determine the last part of the domain, which can be found after the last ".". Note that we do not validate the TLD. You can use the validator class to validate all top-level domains (including all Top 7 and ISO domains). We use the TLD to determine which whois server we have to query for a specific domain. In order to do this quickly, we use an associative array with the TLD as index. For each TLD we save the hostname of the whois server and the answer we expect, if the record does not exist. Y ou can easily support more TLDs by including the necessary information into the array. The IANA (The Internet Assigned Numbers Authority) maintains a database of contact information for all countries. If a domain registry runs a whois server, it is often mentioned on the homepage of the respective organization ( ). Note that running a whois server is not a requirement, but a voluntary service. This section finishes with our working horse, a function to determine whether a specific domain is still available. The function uses only well-known elements, which we discussed earlier, so it should be easy to understand. The function returns false or true, depending on whether the specified function is used or available.
  4. Simpo PDF Merge and Split Unregistered Version - return $ret; } ?> A web client T he break-through of the Internet was based upon one network protocol: HTTP (the Hypertext Transfer Protocol, the last version is HTTP/1.1). HTTP is the protocol your web browser users when you access web sites. We will present a simple class now, which makes it possible to access HTTP resources transparently, even if you need to use a HTTP proxy. A HTTP proxy is a service most ISPs (Internet Service Providers) and companies deploy to accelerate web access and to reduce network traffic. Proxies cache data to achieve these goals. Proxies are protocol dependent and exist for a number of services, including HTTP. Network-wise, proxies sit between the client (web browser) and the server. The client sends a request to the proxy, which either returns a cached copy, or forwards the request to the web server. In PHP, you can use web resources like local files. The so-called fopen-wrappers allow you to use PHP's standard I/O functions (i.e. f open() , f read() , f close() ) as if the files were stored on the local file system. T he lack of HTTP proxy support renders f open -wrappers unusable for many purposes. For example, an Intranet web server might not be able to access an external web site by using fopen-wrappers, because it has no direct Internet direction and must send HTTP requests through a proxy. Hopefully, HTTP proxy support will be added in the final version of PHP 4.0. Since we want the class to be as simple as possible, we define it to be a HTTP/1.0 client performing only GET requests. It should return a file pointer, so that you could easily replace PHP's f open() f unction for URLs with our self-developed class. We use a class here, since we want to be able to store certain preferences within the class without using global variables. Our framework looks like this:
  5. Simpo PDF Merge and Split Unregistered Version - function http_fopen($host, $url, $port = 80) { } } O ur "http" named class contains two variables, called $proxy_host and $proxy_port which you can set to the respective values which are valid in your environment. The class will make use of the proxy, if these variables are set. Otherwise, it accesses the HTTP server directly. The key difference here is that we simply change the f sockopen() p arameter. To request a resource, our PHP scripts opens a TCP connection to the web server or the HTTP proxy, sends the HTTP request, reads the reply, and closes the connection. (Note that we only implement HTTP/1.0. HTTP/1.1 can be much more complex in this regard.) B elow is the full code for the http class:
  6. Simpo PDF Merge and Split Unregistered Version - # discard the HTTP header while(trim(fgets($fp, 1024)) != ""); # return the active file pointer return $fp; } } ?> O ur h ttp_fopen() f unction takes two parameters and an optional third one. The first parameter is the hostname or IP address of the server the data shall be retrieved from (e.g. "" or ""). The second one is the URI of the resource on that server (for example, "/icons/directory.gif"). The optional third parameter is the TCP port number (e.g. port 8080). The well- known port number for HTTP is 80, which is also our default port number. The next step is to determine whether the user has set the proxy variables. We test whether the $proxy_host variable is empty and based on that test we set two variables. The first identifier ($conn_host) is the hostname of the server we connect to, $conn_port is its port number. If $proxy_host is empty, we assign these variables the hostname and port number of the web server, otherwise we assign the configured proxy hostname and proxy port. $conn_url is set to include the name of the protocol (http), the host name or IP number of the web server, its port number, and the path of the resource. Note that there is no delimiter between the port number and the path, because the path should start with "/". We construct the HTTP request by specifying GET as the method (it retrieves whatever information is stored on the server), concatenating $conn_url and attaching the HTTP version that we are using. We add a "Host" header, which tells the server the hostname we want to access. Today, many HTTP servers do not have their own IP addresses anymore, they rely on HTTP clients sending them the server name so that the server software must distinguish between the virtual hosts it serves. These virtual hosts are virtual, because they appear to be a real host, but in fact the web server only simulates them. The web server maintains a list of available virtual hosts, and delivers different data to clients, depending on the virtual hosts they specify. Finally, we give ourselves a name by specifying it in the "User-agent" message-header. The end of the HTTP request is marked by an empty line. The line ending is CRLF (hexadecimal 0x13 and 0x10, can also be written as "\r\n" in PHP). After our request is constructed now, we open the TCP connection to the server (either to the web server or to the HTTP proxy, depending on our previous test). If the connection attempt does not succeed, we return false, so that the caller can easily test for a failed connection attempt. The next few lines read the HTTP response header, which is thrown away (we do this, because our design target was simplicity). When we see an empty line, the body of the HTTP response begins. This body contains the data the caller wants. Therefore, we stop the loop here, and return the file pointer. If the caller reads from this file pointer, the requested resource is directly accessible. The next example demonstrates the use of the http class. It fetches the specified web site, and passes it through to the client requesting our example script. U sing the http class TEAM FLY PRESENTS
  7. Simpo PDF Merge and Split Unregistered Version - T he first action is to include the file that contains the http class. Then we create a new instance of the http class. We use the member function h ttp_fopen() o f that class to access the Wrox Conferences web server. If the result of h ttp_fopen() i s false, the connection attempt to the web server failed. Otherwise, we can manipulate the file pointer. In our example, we choose to pass through all available data on the file pointer to the current client. That means the client sees the Wrox Conferences homepage, as if w w ould have been accessed directly. Note the < BASE> t ag. It is used to tell the client that all relative links in the page shall be relative to the specified URL. The following screenshot shows how the output of the script looks like. Summary I n this chapter we have shown how to build clients for TCP-based Internet protocols in PHP. We have TEAM FLY PRESENTS
  8. Simpo PDF Merge and Split Unregistered Version - p rovided examples for accessing Whois database servers as well as HTTP servers and proxies. This knowledge helps you to understand information flow on the Internet and implement protocols that use TCP as their transport layer. TEAM FLY PRESENTS
  9. Simpo PDF Merge and Split Unregistered Version - 17 Sending and Receiving E-mail E -mail is the most used Internet service today. Billions of e-mails are delivered each day. PHP integrates techniques to handle e-mail. There are many different ways in which they can be applied: Sending invoices to a customer; informing your customers about the latest news from your business; encouraging people to join your interest group. In this chapter, we focus on how to generate and send e-mails in PHP. Sending E-mail The mail() command Y ou use the built-in m ail() c ommand to send simple text messages. m ail() r elies on the local mail system to deliver e-mails. So, if your program cannot rely on the local mail system, you shouldn't use m ail() . We present an alternative later in this chapter. The prototype of the function: b ool mail(string to, string subject, string message[, string additional_headers]); T he function returns true, if the e-mail was correctly submitted to the local mail system. It does not imply that the e-mail was delivered. The fourth parameter is optional. An explanation of the parameters follows. P arameter Meaning Example R ecipient addresses, to "" or TEAM FLY PRESENTS
  10. Simpo PDF Merge and Split Unregistered Version - m ust be separated by "," comma T he subject of the e- s ubject " user registration" mail T he body of the m essage " Hi,\r\nthis is the second line message of text\r\nthis is the third line of text" a dditional_headers This string is " From: ( optional) appended to the end\r\nReply-to:" of the e-mail header. Multiple header lines can be specified by separating them with " \r\n" T he next example sends an e-mail to a single recipient: T he third parameter contains the body of the message. If you want to embed the e-mail text in the PHP code, the text can span over multiple lines: T o address multiple recipients, you separate each e-mail address by a comma. TEAM FLY PRESENTS
  11. Simpo PDF Merge and Split Unregistered Version - To construct the recipient string out of an array, you use the implode() function. class mime_mail T he m ail() c ommand can be used to send a simple, self-contained e-mail. This is enough for most applications. But sometimes you need something more complex. Your web site might offer to send a Wordprocessor document to a e-mail address. This requires the use of MIME, the Multipurpose Internet Mail Extensions. We have developed a PHP class which provides an easy interface to MIME. The class hides all the difficult aspects of MIME, and builds the foundation for the SMTP class which we will present later. The class follows:
  12. Simpo PDF Merge and Split Unregistered Version - $this->body = ""; $this->headers = ""; } /* * void add_attachment(string message, [string name], [string ctype]) * Add an attachment to the mail object */ function add_attachment($message, $name = "", $ctype = "application/octet- stream") { $this->parts[] = array ( "ctype" => $ctype, "message" => $message, "encode" => $encode, "name" => $name ); } /* * void build_message(array part= * Build message parts of an multipart mail */ function build_message($part) { $message = $part[ "message"]; $message = chunk_split(base64_encode($message)); $encoding = "base64"; return "Content-Type: ".$part[ "ctype"]. ($part[ "name"]? "; name = \"".$part[ "name"]. "\"" : ""). "\nContent-Transfer-Encoding: $encoding\n\n$message\n"; } /* * void build_multipart() * Build a multipart mail */ function build_multipart() { $boundary = "b".md5(uniqid(time())); $multipart = "Content-Type: multipart/mixed; boundary = $boundary\n\nThis is a MIME encoded message.\n\n--$boundary"; for($i = sizeof($this->parts)-1; $i >= 0; $i--) { $multipart .= "\n".$this->build_message($this->parts[$i]). "--$boundary"; } return $multipart.= "--\n"; } TEAM FLY PRESENTS
  13. Simpo PDF Merge and Split Unregistered Version - /* * string get_mail() * returns the constructed mail */ function get_mail($complete = true) { $mime = ""; if (!empty($this->from)) $mime .= "From: ".$this->from. "\n"; if (!empty($this->headers)) $mime .= $this->headers. "\n"; if ($complete) { if (!empty($this->to)) { $mime .= "To: $this->to\n"; } if (!empty($this->subject)) { $mime .= "Subject: $this->subject\n"; } } if (!empty($this->body)) $this->add_attachment($this->body, "", "text/plain"); $mime .= "MIME-Version: 1.0\n".$this->build_multipart(); return $mime; } /* * void send() * Send the mail (last class-function to be called) */ function send() { $mime = $this->get_mail(false); mail($this->to, $this->subject, "", $mime); } }; // end of class ?> T he next example demonstrates how to send a simple e-mail using class mime_mail.
  14. Simpo PDF Merge and Split Unregistered Version - $mail->body = "Here goes the real text of the e-mail. You can write over multiple lines, of course."; # send e-mail $mail->send(); ?> T hat was easy. The following script shows how to read a file from the local file system and how to attach it to an e-mail. Note that you can attach multiple files to an e-mail. T he last example for class mime_mail displays an input form for an e-mail address. The next step is to read multiple files from the local file system, and send these files to the specified e-mail address.
  15. Simpo PDF Merge and Split Unregistered Version - if (empty($recipient)) { ?> Please enter your e-mail address to receive the files:
  16. Simpo PDF Merge and Split Unregistered Version - Using SMTP S MTP (Simple Mail Transfer Protocol) is the protocol used for exchanging e-mails on the Internet. Your e-mail client uses the protocol to communicate with an SMTP server (sometimes simply referred to as "e-mail server"). If you use the built-in m ail() f unction of PHP, your application then depends on a local mail delivery system. Since this dependency might not always be satisfied, you can alternatively access an SMTP server directly. The following class demonstrates the use of a relaying SMTP server to deliver e-mails. What is a relaying SMTP server? The term relaying means that the SMTP server accepts e-mail for every recipient and goes through the trouble of delivering the e-mail. Imagine that in real-life you throw mail into a postbox (the relaying SMTP server), so that the postal service will deliver it to the address specified on the envelope of the mail (the recipient of the e-mail). Internet Service Providers often allow their customers to use the ISP's SMTP servers as relays. So-called "open relays," which do not restrict who uses them hardly exist anymore, because some people abused this service by sending large quantities of e-mail (spam). This led to the deprecation of open relays. Let us have a look at the class s mtp_mail .
  17. Simpo PDF Merge and Split Unregistered Version - * we expect ($code). */ function dialogue($code, $cmd) { $ret = true; fwrite($this->fp, $cmd."\r\n"); $line = $this->read_line($this->fp); if($line == false) { $ret = false; $this->lastmsg = ""; } else { $this->lastmsg = "$line[0] $line[1]"; if($line[0] != $code) { $ret = false; } } return $ret; } /* * error_message() prints out an error message, * including the last message received from the SMTP server. */ function error_message() { echo "SMTP protocol failure (".$this->lastmsg.")."; } /* * crlf_encode() fixes line endings * RFC 788 specifies CRLF (hex 0x13 0x10) as line endings */ function crlf_encode($data) { # make sure that the data ends with a newline character $data .= "\n"; # remove all CRs and replace single LFs with CRLFs $data = str_replace("\n", "\r\n", str_replace("\r", "", $data)); # in the SMTP protocol a line consisting of a single "." has # a special meaning. We therefore escape it by appending one space. $data = str_replace("\n.\r\n", "\n. \r\n", $data); return $data; } /* TEAM FLY PRESENTS
  18. Simpo PDF Merge and Split Unregistered Version - * handle_e-mail() talks to the SMTP server */ function handle_e-mail($from, $to, $data) { # split recipient list $rcpts = explode(",", $to); $err = false; if(!$this->dialogue(250, "HELO phpclient") || !$this->dialogue(250, "MAIL FROM:$from")) { $err = true; } for($i = 0; !$err && $i < count($rcpts); $i++) { if(!$this->dialogue(250, "RCPT TO:$rcpts[$i]")) { $err = true; } } if($err || !$this->dialogue(354, "DATA") || !fwrite($this->fp, $data) || !$this->dialogue(250, ".") || !$this->dialogue(221, "QUIT")) { $err = true; } if($err) { $this->error_message(); } return !$err; } /* * connect() connects to an SMTP server on the well-known port 25 */ function connect($hostname) { $ret = false; $this->fp = fsockopen($hostname, 25); if($this->fp) { $ret = true; } return $ret; } /* * send_e-mail() connects to an SMTP server, encodes the message TEAM FLY PRESENTS
  19. Simpo PDF Merge and Split Unregistered Version - * optionally, and sends $data. The envelope sender address * is $from. A comma-separated list of recipients is expected in $to. */ function send_e-mail($hostname, $from, $to, $data, $crlf_encode = 0) { if(!$this->connect($hostname)) { echo "cannot open socket\n"; return false; } $line = $this->read_line(); $ret = false; if($line && $line[0] == "220") { if($crlf_encode) { $data = $this->crlf_encode($data); } $ret = $this->handle_e-mail($from, $to, $data); } else { $this->error_message(); } fclose($this->fp); return $ret; } } ?> T o understand all the details, you should read Chapter 16 (PHP Connectivity), which provides insight into the world of developing networking applications. However, you have not been told how the class works, if you just want to use it to send e-mails. We will show now how you can combine class mime_mail and class smtp_mail to deliver complex e-mails using direct SMTP access.
  20. Simpo PDF Merge and Split Unregistered Version - # create mime_mail instance $mail = new mime_mail; $mail->from = $from; $mail->to = $to; $mail->subject = $subject; $mail->body = $body; # get the constructed e-mail data $data = $mail->get_mail(); # create smtp_mail instance $smtp = new smtp_mail; # send e-mail $smtp->send_e-mail($smtp_server, $from, $to, $data); ?> I n the example, we used class mime_mail to construct a complete e-mail and used class smtp_mail to send it to the specified relaying SMTP server. This allows us to combine the flexibility of the MIME mail class with our networking SMTP class. Receiving E-mail I MAP, Internet Message Access Protocol, has made a strong introduction to the commercial market after years of existence as only freeware. IMAP makes some general improvements over POP by first providing a reliable transport of mail, regardless of connection and timeout conditions. With POP’s singular mission to dump all email messages to a requesting authenticated client, IMAP brings the control of email, in storing as well as fetching, to the server. The extra features, like manipulation of status flags (read, unread, etc) make IMAP a very attractive solution. IMAP’s system has also proven to be very effective over low-speed connections where downloading an entire mailbox might take hours. IMAP also supports multiple, simultaneous access to a single mailbox, which can prove useful in some circumstances. In return for these added benefits, IMAP requires more attention by administrators and needs precise scaling. Beefier hardware, improved processors, and storage space will also be a requirement since messages will now remain on the server. A benefit of this setup is that the system can be backed up on an enterprise scale instead of on a personal scale. Since email can be considered mission critical, or at least contain mission essential information, this type of backup can prove to be beneficial over time. The standard IMAP protocol is well supported by PHP, and when the two are combined produce a very suitable programming environment for creating e-mail facilities Powerful and versatile results can be accomplished quickly, by the combination of multiple PHP IMAP functions. Some of these are listed below. TEAM FLY PRESENTS



Đồng bộ tài khoản