Chapter 23 . Filesystem and (Web hosting control panel) System Functions 441

June 10th, 2008

Chapter 23 . Filesystem and System Functions 441 The effect of this particular example will be to double the file in other words, the end result will be a file with the original contents of the file written out twice. This function will not overwrite the file, as you might expect. In the following sections, we walk you through this archetypal file manipulation session, step by step. File open It s essentially mandatory to assign the result of fopen() to a variable (traditionally $fd for file descriptor, or $fp for file pointer). Note that fopen() does not return an integer on success. In fact, it returns a string that says Resource id #n, where n is the number of the currently opened stream. Do not attempt to test the success of your file open by using is_int() or is_numeric(). Use die() instead. If it s successful in opening the file, PHP will return a resource ID, which it requires for further operations such as fread or fwrite. Otherwise, the value will be false. The system makes only a certain number of file descriptors available, which is a good argument for closing files as soon as you can. If you anticipate a large demand and have access to system settings, you may increase the number. However, if you fail to close a file descriptor, PHP will do it for you when the script ends. Files may be opened in any of six modes (similar to permissions levels). If you try to do mode-inappropriate things, you will be denied. The modes are: . Read-only ( r ). . Read and write if the file exists already ( r+ ): will write to the beginning of the file, doubling original contents of the file if you read the file in as a string, edit it, and then write the string out to the file. . Write-only ( w ) will create a file of this name, if one doesn t already exist, and will erase the contents of any file of this name before writing! You cannot use this mode to read a file, only to write one. . Write and read even if the file doesn t exist already ( w+ ) will create a file of this name, if one doesn t already exist, and will erase the contents of any file of this name before writing! . Write-only to the end of a file whether it exists or not ( a ). . Read and write to the end of a file whether it exists or not ( a+ ), doubling original contents of the file if you read the file in as a string, edit it, and then write the string out to the file. You need to be very sure you have read in the contents of any pre-existing file before using w or w+ on it. Your chance of losing data with the other modes is much less. Since version 4.3.2 of PHP, a formerly optional parameter, b, has been made the default operating mode for fopen(). This means all files, on platforms where the distinction is supported, are opened as binary. The result is that (among other, finer points) no translation of the line-ending characters occurs between Windows and Unix-like platforms. You can still circumvent this measure by making the letter t the last character of your permissions, in effect forcing the translation to occur. Tip Caution Caution
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

440 Part (Web host forum) III . Advanced Features and Techniques

June 10th, 2008

440 Part III . Advanced Features and Techniques need to be readable by the Web server user (usually Nobody, or some other user with very limited permissions). It s rather inconvenient to make the files not writable by you, which is why our default recommendation is 644 (rw-r–r–) rather than 444 (r–r–r–), but this is a matter of convenience only on a production system, where you shouldn t be altering code anyway, you might very well want to set them to 444. Your PHP scripts will run perfectly fine at 444 (read-only). Directory permissions are also very often misunderstood. Many users seem to believe that directories need to be readable for files to run. Actually the read directory permission means a user can list the contents of that directory (via the ls command, for instance). The execute directory permission is closer to what we think of as readable. For your PHP scripts to run, the directory needs only to be world-executable (751 or rwxr-x–x). Do not make the directory writable by others unless you know what you re doing. This Web page gives a good short explanation of Unix file permissions: www.freeos.com/articles/3127/. File Reading and Writing Functions This is a supremely useful set of functions, particularly for data sets too small or scattered to merit the use of a database. File reading is pretty safe unless you keep unencrypted passwords lying around, but file writing can be quite unsafe. Remember that although the Web server (and client-side languages such as JavaScript) can only act on files located under the document root, PHP can access files at any location in the file system including those above or entirely outside the Web server document root as long as the file permissions and include_path are set correctly. For instance, if your Web server document root is located at /usr/local/apache/htdocs, Apache will be able to serve only files from this directory and its subdirectories, but PHP can open, read, and write to files in /usr/local, /home/php, /export/home/httpd, or any other directory that you make readable and includable by the PHP and/or Web server user. A file manipulation session might involve the following steps: 1. Open the file for read/write. 2. Read in the file. 3. Close the file (may happen later). 4. Perform operations on the file contents. 5. Write results out. Each step has a corresponding PHP filesystem function. This archetypal example illustrates some subtleties of the syntax for manipulating file contents: $fd = fopen($filename, r+ ) or die( Can t open file $filename ); $fstring = fread($fd, filesize($filename)); $fout = fwrite($fd, $fstring); fclose($fd); Tip
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

Dedicated web hosting - Filesystem and System Functions This chapter contains information

June 9th, 2008

Filesystem and System Functions This chapter contains information on the multiplicity of system functions built into PHP. Many of these functions duplicate system functions via HTTP. Among the most useful are file-reading and writing functions and those that return dates or times. Many of the functions in this chapter have serious security implications. You are inviting bad news if you use them without thinking pretty hard about the consequences! We ll try to point out the scariest ones as we go, but nothing that allows the system to be altered via HTTP should be undertaken lightly. Some of these functions are Unix-only. The Windows system is deliberately made less available to users, especially to non- Administrator users, and lacks many utilities that Unix-heads take for granted. If you re having problems and you run on Windows, make sure the function is enabled on your platform. Understanding PHP File Permissions Many PHP users, who have a developer orientation rather than any sysadmin experience, unfortunately do not take the time to understand Unix filesystem permissions. You really need to have a firm grasp of the basics to make good decisions about using many of the functions in this section. If you already do, feel free to skip the rest of this section. Unfortunately, most explanations of the subject are quite general and user s eyes can easily glaze over in a hail of rwxes and three-digit numbers. So we re going to break it down for you into two simple default rules specifically for PHP users. . Unless you have a good reason to do otherwise, your PHP files should all be set to 644 (rw-r–r–). . Unless you have a good reason to do otherwise, your PHPenabled directories should all be set to 751 (rwxr-x–x). For some reason, many users seem to believe that PHP files need to be executable. This is only true for files that you write with the intention of their being called on the command line (for example, ./myscript.php). Files that will be run through a Web server only Caution 2C H A3P3T E R . . . . In This Chapter Understanding PHP file permissions File reading and writing functions Filesystem and directory functions Network functions Date and time functions Calendar conversion functions . . . .
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

438 Part III . Advanced Features and Techniques (Cheapest web hosting)

June 9th, 2008

438 Part III . Advanced Features and Techniques String similarity functions How similar is this string to that string? Well, it depends what you mean by similar, right? If the kind of similarity you want is similarity of spelling, consider the Levenshtein metric. The levenshtein() function takes two strings and returns the minimum number of additions, deletions, and replacements of letters needed to transform one into the other. For example: . levenshtein( Tim , Time ) returns 1 . levenshtein( boy , chefboyardee ) returns 9 . levenshtein( never , clever ) returns 2 If the similarity you are interested in is phonetic, consider the functions soundex() and metaphone(). Both of them take an input string and return a key string representing the pronunciation category of the word (in English). If two input word strings map to exactly the same output key, they most likely have a similar pronunciation. Summary PHP has a wealth of built-in functions for handling strings functions to create them, stick them together, chop them up, and do various kinds of analysis. The simplest of these were covered in Chapter 8, and in this chapter we saw functions for tokenizing, hashing, charactercounting, and determining similarity, as well as HTML-specific functions. Simple string matching is all very well, but when you need industrial-strength pattern matching, nothing less than regex will do. PHP offers not only full regular-expression functionality, but two flavors of it to choose from. Our personal preference is for the Perl-compatible regex functions, but you can use whichever flavor suits you best. . . .
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.

Web site traffic - Chapter 22 . String and Regular Expression Functions

June 8th, 2008

Chapter 22 . String and Regular Expression Functions 437 $letter = chr($cell[ key ]); $frequency = $cell[ value ]; print( Character: $letter ; frequency: $frequency
); } This gives the browser output: Peter Piper picked a peck of pickled peppers Character: ; frequency: 7 Character: P ; frequency: 2 Character: a ; frequency: 1 Character: c ; frequency: 3 Character: d ; frequency: 2 Character: e ; frequency: 8 Character: f ; frequency: 1 Character: i ; frequency: 3 Character: k ; frequency: 3 Character: l ; frequency: 1 Character: o ; frequency: 1 Character: p ; frequency: 7 Character: r ; frequency: 3 Character: s ; frequency: 1 Character: t ; frequency: 1 The count_chars() function returns a report on the occurrences of characters in its string argument, packaged up as an array where the keys are the ASCII values of characters, and the values are the frequencies of those characters in the string. The second argument to count_chars() is an integer that determines which of several modes the results should be returned in. In mode 0, an array of key/value pairs is returned, where the keys are every ASCII value from 0 to 255, and the corresponding values are the frequencies of each character in the string. Modes 1 and 2 are variants that include only ASCII values that occurred in the string (mode 1) or that did not occur (mode 2). Finally, modes 3 and 4 return a string instead of an array, where the string contains all characters that occur (mode 3) or do not occur (mode 4). These functions are summarized in Table 22-5. For an explanation of how to take apart array formats like that returned by count_chars(), see Chapter 9. The chr() function used in the preceding example, which maps from ASCII numbers to the corresponding characters, is covered in Chapter 5. Table 22-5: Functions for Examining Character Contents Function Behavior count_chars() Takes a single string argument and an integer mode argument from 0 to 4. Returns a report about frequencies of characters in the string argument, as either an array or a string. (See the preceding text for more detail.) strspn() Takes two string arguments and returns the length of the initial substring of the first argument that is composed entirely of characters found in its second argument. strcspn() Takes two string arguments and returns the length of the initial substring of the first argument that is composed entirely of characters that are not found in its second argument. Cross- Reference
Please visit our professional web hosting services to find out about cheap and reliable webhost service that will surely answer all your demands.

436 Part III . Advanced Features and Techniques (Web hosting solutions)

June 8th, 2008

436 Part III . Advanced Features and Techniques The characteristics of MD5 make it useful for a wide variety of tasks, including: . Checksumming a message or file. If you are worried about errors that might happen in transfer, you can transmit an MD5 digest, along with the message, and run the message through MD5 again after transfer. If the two versions of the digest do not match, then something is amiss. . Detecting if a file s contents have changed. Similar to checksumming, MD5 is often used in this way by search engines as a check on whether a Web page has changed, making re-indexing necessary. It is cheaper to store the MD5 digest than the entire original file. . Encrypting passwords. You might store an MD5 ed password in your database, and compare the result of MD5 ing an entered password against that entry. . Splitting strings or files into buckets. If you want to divide a set of strings into N randomly dispersed sets, you can MD5 the strings, take the first few hex characters, translate them into a number, and take that number modulo the number of bins you want. In addition to the md5() function, PHP offers md5_file(), which takes a filename as argument and returns an MD5 hash of the file s contents. Strings as character collections PHP offers some pretty specialized functions that treat strings more as collections of characters than as sequences. The first is strspn(), which you can use to see what portion of a string is composed only of a given set of characters. For example: $twister = Peter Piper picked a peck of pickled peppers ; $charset = Peter picked a ; print( The segment matching $charset is . strspn($twister, $charset) . characters long ); gives us: The segment matching Peter picked a is 26 characters long because the first character not found in $charset is the o in of, and there are 26 characters that precede it. The strcspn() function (where that internal c stands for complement) does the same thing, except that it accepts characters that are not in the character set argument. For example, the statement: echo(strcspn($twister, abcd )); prints the number 14, because it accepts a 14-character sequence with the last character being the c in picked. Finally, hark back to Chapter 9 on arrays and check out the following for an acute analysis of alliteration: $twister = Peter Piper picked a peck of pickled peppers ; print( $twister
); $letter_array = count_chars($twister, 1); while ($cell = each($letter_array)){
From our experience, we can recommend PHP5 Web Hosting services, if you need affordable webhost to host and run your web application.

Business web site - Chapter 22 . String and Regular Expression Functions

June 5th, 2008

Chapter 22 . String and Regular Expression Functions 435 Function Behavior htmlentities() Goes further than htmlspecialchars(), in that it replaces all characters that have a corresponding HTML entity with that HTML entity. get_html_translation_table() Takes one of two special constants (HTML_SPECIAL_CHARS and HTML_ENTITIES), and returns the translation table used by htmlspecialchars() and htmlentities(), respectively. The translation table is an array where keys are the character strings and the corresponding values are their replacements. nl2br() Takes a string as argument and returns that string with
inserted before all new lines (\n). This is helpful, for example, in maintaining the apparent line length of text paragraphs when they are displayed in a browser. strip_tags() Takes a string as argument and does its best to return that string stripped of all HTML tags and all PHP tags. Hashing using MD5 MD5 is a string-processing algorithm that is used to produce a digest or signature of whatever string it is given. The algorithm boils its input string down into a fixed-length string of 32 hexadecimal values (0,1,2, . . . 9,a,b, . . . f). MD5 has some very useful properties: . MD5 always produces the same output string for any given input string. . The fixed-length results of applying MD5 are very evenly spread over the range of possible values. . There is no known way to efficiently produce an input string corresponding to a given MD5 output string or to produce two inputs that yield the same output. PHP s implementation of MD5 is available in the function md5(), which takes a string as input and produces the 32-character digest as output. For example, evaluating this: print( md5 of Tim is . md5( Tim ) .
); print( md5 of tim is . md5( tim ) .
); print( md5 of time is . md5( time ) .
); gives us the browser output: md5 of Tim is dc2054afd537ddc98afd9347136494ac md5 of tim is b15d47e99831ee63e3f47cf3d4478e9a md5 of time is 07cc694b9b3fc636710fa08b6922c42b Although the input strings seem close to each other in some sense, there is no apparent similarity in the output strings. And since the range of possible output values is so huge (16 to the 32nd power), the chances that any two distinct strings will collide by producing the same MD5 value is vanishingly small.
In case you need quality webspace to host and run your web applications, try our personal web hosting services.

434 Part III . Advanced Features and Techniques (Web design conference)

June 5th, 2008

434 Part III . Advanced Features and Techniques Advanced String Functions We have now covered the most basic things to do with strings, as well some more sophisticated means of working with them via regular expressions. Now, we ll delve into some more exotic string functions, which we ve categorized by type and/or purpose. These are the sort of functions that might only be relevant to you if you re working on a particular kind of project. Some of these sections might make you want to say, Why would anyone want to do that? If so, please ignore them until you the day that you suddenly realize that you need to do that thing exactly. HTML functions PHP offers a number of Web-specific functions for string manipulation, which are summarized in Table 22-4. Table 22-4: HTML-Specific String Functions Function Behavior htmlspecialchars() Takes a string as argument and returns the string with replacements for four characters that have special meaning in HTML. Each of these characters is replaced with the corresponding HTML entity, so that it will look like the original when rendered by a browser. The & character is replaced by & (the double-quote character) is replaced by "; < is replaced by <; > is replaced by >. Writing Well-behaved Spiders A note of caution, however (informed by the experience of one of your authors in the searchengine business). There is absolutely no reason you shouldn t feel free to point this code at www.cnn.com/ to view the links on that front page after all, it s exactly what happens when your own browser contacts that site, and certainly the people at CNN won t be able to tell the difference between those two contacts. There are two rules that you should observe, though, before writing any kind of spider that does more automated crawling. When you crawl any site, you should: . Check to see if there is a robots.txt file (at http://sitename/robots.txt). If there is no such file, the site owners are implicitly saying the site is okay to crawl. If there is such a file, you should either not crawl the site or, if you do, you should make sure that you are not crawling pages that match the patterns laid out in that file. (For more on this, do a Web search for robot exclusion standard .) . Make sure that you don t request files from any particular site too frequently. A decent interval to wait between requests is ten seconds or so. (You can implement this delay on a per-site basis, or simply by sleeping for ten seconds between every request.) It is not OK to simply create a recursive version of the preceding code, and then unleash it on a large site, grabbing new links and pages as fast as your code can loop. Remember: One man s search engine is another s denial-of-service attack.
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.

Chapter 22 . String and Regular Expression Functions (Net web server)

June 4th, 2008

Chapter 22 . String and Regular Expression Functions 433 The iteration through the HTML page s contents is taken care of by preg_match_all(), which applies the regex pattern as many times as possible, starting from the previous match each time, and saving the matches in $match_array. We chose to have the array arranged by PREG_SET_ORDER, meaning that each entry in the top-level array is the portion from a particular match in the iteration, rather than across matches. Applying the function The only argument the function requires is a URL. In testing the function before including it in the book, we pointed it at link-rich, top-level pages like http://slashdot.org, www.cnn.com, and www.php.net. Those results would be fun to display, but all of those sites have copyright notices, and publishers are understandably wary of allowing authors to put other people s copyrighted material into their copyrighted book without permission. So, instead, we pointed it at the top-level placeholder page for our own vanity site (www.troutworks.com), like this: print_links( http://www.troutworks.com/ ); You get the following result (approximately): HREF: http://www.mysteryguide.com; ANCHORTEXT: MysteryGuide HREF: http://www.sciencebookguide.com; ANCHORTEXT: ScienceBookGuide HREF: /Joycelog/joycelog.php; ANCHORTEXT: Troutgirl weblog HREF: /Timlog/timlog.php; ANCHORTEXT: Timboy weblog HREF: http://www.troutworks.com/phpbook; ANCHORTEXT: code download site HREF: http://www.amazon.com/exec/obidos/tg/detail/-/0764549553/; HREF: http://www.mysteryguide.com; ANCHORTEXT: MysteryGuide HREF: http://www.sciencebookguide.com; ANCHORTEXT: ScienceBookGuide ANCHORTEXT: PHP Bible HREF: http://www.troutworks.com/phpbook; ANCHORTEXT: code download site Just because we didn t feel that we could print the results of the links from those more interesting sites doesn t mean that you can t apply this code to them (however, see the warnings in the sidebar Writing well-behaved spiders ). Extending the code As we ve said, code like Listing 22-1 is the very beginning of writing a Web-search spider. If you want to make it more real, you could: . Convert the relative links to absolute (http://) links by remembering the URL that you are scraping and splicing that base URL appropriately with the relative path. . Add a more graceful way to bounce back from an unreachable site rather than immediately dying. . Expand the regex pattern to match HREFs that have quotes around the URL as well as HREFs that do not. . Add capability for recursive calls so that, rather than simply printing a child link, you apply the same function again to it and explore its own links.
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.

432 Part III . Advanced Features and (Net web server) Techniques

June 4th, 2008

432 Part III . Advanced Features and Techniques Using the expression in a function With an anchor-tag-matching expression in hand, our goal now is to write a function to scrape links from an HTML page. We ll need to: . Take a URL as argument. . Open up an HTTP connection to the URL and grab its contents as a string. . Iterate through the string, applying our regex pattern wherever we can, saving what matches. . Print the extracted portions (target URL and anchortext). Such a function is shown in Listing 22-1. Listing 22-1: A print_links function ([^>]*)<\/A>/i , $page_contents, $match_array, PREG_SET_ORDER); foreach ($match_array as $entry) { $href = $entry[1]; $anchortext = $entry[2]; print( HREF: $href; ANCHORTEXT: $anchortext
); } } ?> This function is easier to write than you might expect because PHP takes care of several parts of it for us. We do not need to write anything special to make an HTTP connection to download a Web page because fopen() will accept a URL as argument and do the right thing. All we need to do after calling fopen() on the URL is to read characters until we are out of them, appending what we get onto a constructed string.
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.