Tài liệu PHP and MySQL by Example- P10 pptx

50 496 0
Tài liệu PHP and MySQL by Example- P10 pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

The ftell() Function—Finding the Current Position in a File If you have read some data from a file and want to keep track of where you were in the file when you stopped reading, the ftell() function will return the current byte position, the number of bytes from the beginning of the file, and where the next read operation will start. This can be used in conjunction with the seek() function to return to the correct position in the file. (If you are using text mode, the carriage return and linefeed translation will be part of the byte count.) Format int ftell ( resource handle ) % Example: $filehandle("myfile", "r"); $contents=fgets($filehandle, 1024); echo ftell( $filehandle); // Current read postion in bytes, // starting at byte 1024 Example 11.9. 4)3#%!"#$c% <html><head><title>The ftell() Function</title></head> <body bgcolor="lavender"> <h3>Marking a Position in a File</h3> <pre> <?php //$filename="c:/wamp/www/exemples/data.file"; $filename="$_SERVER[DOCUMENT_ROOT]/exemples/data.file"; if (!file_exists($filename)){ print "No such file or directory"; exit(); } 1 $fh=fopen($filename,"r"); 2 $substring="eastern"; while( !feof($fh)){ $line_of_text=fgets($fh); echo "$line_of_text"; 3 if(substr_count($line_of_text, $substring)) { 4 $bytes=ftell($fh); } } if (! isset($bytes)){ echo "$substring not found<br />"; exit(); } 5 fseek($fh, $bytes, SEEK_SET); echo "<hr />"; echo "<b>Start reading again from byte position $bytes</b> <br />"; while( !feof($fh)){ 6 $line_of_text=fgets($fh); echo "$line_of_text"; } fclose($fh); ?> </pre> </body> </html> Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Explanation D W%7"8#%"'%)/#*#3%7)1%1#23"*>- C R=#%621"2T8#.%$substring.%"'%2''">*#3%&=#%'&1"*>%"eastern".%2%'&1"*>%&=2&%$"88%T#% '#21(=#3%7)1%"*%&=#%7"8#%&=2&%$2'%d<'&%)/#*#3- O W'%#2(=%8"*#%"'%1#23%71)5%&=#%7"8#.%&=#%substr_count()%7<*(&")*%$"88%'#21(=%7)1% &=#%'&1"*>%"eastern"%"*%2%8"*#%2*3%1#&<1*%&=#%*<5T#1%)7%&"5#'%"&%$2'%7)<*3-% R=#%7"1'&%&"5#%&="'%7<*(&")*%1#&<1*'%D%)1%5)1#.%&=#%*#;&%8"*#%$"88%T#%#*&#1#3- @ R=#%ftell()%7<*(&")*%$"88%1#&<1*%&=#%T0&#%/)'"&")*%)7%$=#1#%&=#%*#;&%1#23% )/#12&")*%$"88%&2N#%/82(#-%R=#%8"*#%()*&2"*"*>%"eastern"%=2'%281#230%T##*% 1#23-%R=#%T0&#%/)'"&")*%"'%&=#%*<5T#1%)7%(=212(&#1'%71)5%&=#%T#>"**"*>%)7%&=#% 7"8#-%R="'%628<#%"'%'26#3%"*%$bytes.%&)%T#%<'#3%82&#1%$"&=%&=#%fseek()%7<*(&")*- I R=#%fseek()%7<*(&")*%$"88%'&21&%2&%&=#%T#>"**"*>%)7%&=#%7"8#.%T0&#%A.%2*3%5)6#%&)% &=#%/)'"&")*%1#&<1*#3%71)5%ftell().%T0&#%CiD.%"*%&="'%#;25/8#-%M##%`"><1#% DD-DA- K B=#*%fgets()%'&21&'%1#23"*>%8"*#'%71)5%&=#%7"8#%"&%/"(N'%</%1">=&%27&#1%&=#%8"*#% $=#1#%&=#%'<T'&1"*>%"eastern"%$2'%7)<*3- Figure 11.10. Marking a position with ftell(). Output from Example 11.9. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 11.2.6. Opening a URL for Reading You can open files with FTP or HTTP with the fopen() function. (Note: If opening the URL fails, check if the allow_url_fopen directive in the php.ini file is disabled.) Format resource fopen ( string filename, string mode [, bool use_include_path [, resource zcontext]] ) % Example: $filehandle=fopen('http://www.site.com/'); $filehandle=fopen('ftp://username:password@ftp.wherever.com/pub/index' , 'r'); Example 11.10. <html><head><title>Open a File</title></head> <body bgcolor="lavender"> <?php 1 $filename="http://www.ellieq.com/"; 2 $fh=fopen("$filename", "r"); 3 while( !feof($fh) ){ 4 $contents=htmlspecialchars(fgets($fh, 1024)); print "<pre>$contents</pre>"; } fclose($fh); ?> </body> </html> Explanation D R=#%7"8#%"'%&=#%P?Z%)7%2%B#T%'"&#- C R=#%B#T%/2>#%"'%)/#*#3%7)1%1#23"*>%2*3%2%7"8#=2*38#%"'%1#&<1*#3.%(288#3%$fh- O R=#%#;/1#''")*%"*%&=#%while%8))/%<'#'%&=#%feof()%7<*(&")*%&)%(=#(N%$=#&=#1%$#%21#%*)&% 0#&%2&%&=#%#*3%)7%&=#%7"8#- @ R=#%fgets()%7<*(&")*%1#23'%DAC@%T0&#'%2&%2%&"5#%71)5%&=#%/2>#-%R=#% htmlspecialchars()%7<*(&")*%()*6#1&'%2*0%'/#("28%(=212(&#1'%&)%VR9Z%#*&"&"#'J%7)1% #;25/8#.%2*%&%$)<83%T#()5#%&amp%2*3%2%<%$)<83%T#()5#%&lt.%2*3%')%)*-%R=#%)<&/<&% '=)$*%"*%`"><1#%DD-DD%"'%&=#%2(&<28%')<1(#%/2>#%+!"#$%M)<1(#,%&=2&%$2'%<'#3%&)%(1#2&#% &=#%/2>#- % Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figure 11.11. Viewing the contents of a Web page opened as a URL. % 11.2.7. Reading from Files Without a Filehandle PHP provides functions that allow you to read the contents of a file without first opening a filehandle. The file_get_contents() Function—Reading the Whole File into a String An easy way to read the contents of an entire file is with the file_get_contents() function. You do not even need to get a filehandle, just pass the name of the file to the function and it will get the contents of the whole file and store it in a string. You can also start reading from a specified offset in the file and specify how many bytes you want to read. The file_get_contents() function will return FALSE, if it fails. The PHP manual suggests this as the most efficient way to read a file into a string. Format string file_get_contents ( string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]]]] ) % Example: $contents=file_get_contents("datafile.txt"); The file() Function—Reading the Whole File into an Array Without using a filehandle, you can read an entire file into an array with PHP’s file() function. The filename can be a full path, relative path, or even a URL (if each element of the array corresponds to a line in the file, with the newline still attached. The function returns FALSE if it fails. If you do not want the end-of-line character at the end of each of the array elements, use the rtrim() function, described in Chapter 6, “Strings.” [5] This function is identical to file_get_contents(), except that it returns the file in an array. [5] If PHP does not recognize the line endings (Macintosh), see the php.ini file to enable the auto_detect_line_endings runtime configuration option. Format array file ( string filename [, int use_include_path [, resource context]] ) Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Example 11.11. <html><head><title>Parsing Lines</title></head> <body bgcolor="lightgreen"> <font face=verdana" size="+2"> <?php if( ! isset($_POST['submit'])){ 1 show_form(); } else{ 2 process_file(); } 3 function show_form(){ ?> <h2>Exploding and Imploding</h2> <form method=POST action="<?php echo $_SERVER['PHP_SELF'];?>"> <table cellspacing="0" cellpadding="2"> <tr> <b> Select a first name from the file.</b> <td><input type="text" size=30 name="first_name" </td> </tr> <tr> <td>&nbsp</td> </tr> <tr> <td><input type="submit" name="submit" </tr><br /> </table> </form> <?php } 4 function process_file(){ $filename="$_SERVER[DOCUMENT_ROOT]/ /mydir/datebook"; 5 $lines = file($filename); // Lines of file stored in an array 6 $first_name=trim($_POST['first_name']); 7 foreach ($lines as $line_value) { 8 $fields=explode(":", $line_value); 9 $fullname=explode(" ", $fields[0]); $phone=$fields[1]; $address=$fields[2]; $birthday=$fields[3]; $salary=$fields[4]; 10 if( strcasecmp($fullname[0],$first_name) == 0 ){ 11 $birth=explode("/",$birthday); 12 $newstring=implode("<br />",array($fields[0],$phone, Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. $address,"19".$birth[2], '$'.number_format($salary,2))); 13 echo "$newstring<br />"; 14 $count++; echo "<hr />"; } } 15 if($count==0){ echo "$first_name is not in the file.<br />"; } } ?> </b> </font> </body> </html> Explanation D R=#%621"2T8#.%$filename.%"'%2''">*#3%&=#%/2&=%&)%2%7"8#%(288#3%data.file%)*#%8#6#8% 2T)6#%&=#%3)(<5#*&%1))&%)7%&=#%'#16#1%"*%2%3"1#(&)10%(288#3%mydir- C R=#%T<"8&Q"*%file()%7<*(&")*%&2N#'%&=#%7"8#*25#%2'%"&'%21><5#*&%+*)&%2%7"8#=2*38#,% 2*3%1#&<1*'%2*%21120%$=#1#%#2(=%8"*#%"'%2*%#8#5#*&%)7%&=#%21120- O R=#%foreach%8))/%(0(8#'%)6#1%#2(=%#8#5#*&%)7%&=#%21120%)7%8"*#'.%#;&12(&"*>%&=#%"*3#;% 2*3%&=#%628<#%)7%&=#%8"*#- @ f0%233"*>%)*#%&)%&=#%628<#%)7%$line_number.%&=#%"*3#;%"*%&=#%21120.%$#%(2*%'&21&%&=#% ()<*&%2&%D-%R="'%628<#%$"88%T#%/82(#3%"*%71)*&%)7%#2(=%8"*#%#6#10%&"5#%&=#%8))/%T)30%"'% #;#(<&#3- I :2(=%8"*#%2*3%"&'%8"*#%*<5T#1%21#%3"'/820#3%2'%'=)$*%"*%`"><1#%DD-DC- Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Figure 11.12. Using the file() function, creating line numbers. Using explode() and implode() After you have read in a line from a file or you get input from a file, you might want to break the lines into individual fields or create a string from an array of input items. This is where the array functions explode() and implode() can be useful, array functions discussed in Chapter 8, “Arrays.” Example 11.12 demonstrates how to use these functions. This example uses the text file called datebook. [6] Below are two lines from this file. Notice that the fields are separated by colons. [6] The datebook file can be found on the CD in the back of this book. Steve Blenheim:238-923-7366:95 Latham Lane, Easton, PA 83755:11/12/56:20300 Betty Boop:245-836-8357:635 Cutesy Lane, Hollywood, CA 91464:6/23/23:14500 % Example 11.12. 4)3#%!"#$c% <html><head><title>Parsing Lines</title></head> <body bgcolor="lightgreen"> <font face=verdana" size="+2"> <?php if( ! isset($_POST['submit'])){ 1 show_form(); } else{ Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 2 process_file(); } 3 function show_form(){ ?> <h2>Exploding and Imploding</h2> <form method=POST action="<?php echo $_SERVER['PHP_SELF'];?>"> <table cellspacing="0" cellpadding="2"> <tr> <b> Select a first name from the file.</b> <td><input type="text" size=30 name="first_name" </td> </tr> <tr> <td>&nbsp</td> </tr> <tr> <td><input type="submit" name="submit" </tr><br /> </table> </form> <?php } 4 function process_file(){ $filename="$_SERVER[DOCUMENT_ROOT]/ /mydir/datebook"; 5 $lines = file($filename); // Lines of file stored in an array 6 $first_name=trim($_POST['first_name']); 7 foreach ($lines as $line_value) { 8 $fields=explode(":", $line_value); 9 $fullname=explode(" ", $fields[0]); $phone=$fields[1]; $address=$fields[2]; $birthday=$fields[3]; $salary=$fields[4]; 10 if( strcasecmp($fullname[0],$first_name) == 0 ){ 11 $birth=explode("/",$birthday); 12 $newstring=implode("<br />",array($fields[0],$phone, $address,"19".$birth[2], '$'.number_format($salary,2))); 13 echo "$newstring<br />"; 14 $count++; echo "<hr />"; } } 15 if($count==0){ echo "$first_name is not in the file.<br />"; Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. } } ?> </b> </font> </body> </html> Explanation D \7%&=#%7)15%=2'%*)&%T##*%'<T5"&&#3%0#&.%&=#%show_form()%7<*(&")*%$"88%3"'/820%"&- C \7%&=#%'<T5"&%T<&&)*%$2'%/1#''#3.%&=#%7)15%=2'%281#230%T##*%7"88#3%)<&.%2*3%*)$%"&%"'% &"5#%&)%/1)(#''%"&-%R=#%process_file()%7<*(&")*%"'%(288#3- O R="'%"'%$=#1#%&=#%show_form()%7<*(&")*%"'%3#(821#3.%$="(=%/1)3<(#'%2%6#10%'"5/8#% VR9Z%7)15%$"&=%)*#%&#;&%T);%2*3%2%'<T5"&%T<&&)*-%R=#%<'#1%$"88%&0/#%"*%&=#%7"1'&% *25#%)7%')5#)*#%71)5%2*%#;&#1*28%&#;&%7"8#.%(288#3%datebook-%M##%`"><1#%DD-DO- @ R="'%"'%$=#1#%&=#%process_file()%7<*(&")*%"'%(288#3-%\&%$"88%1#23%2%7"8#%"*&)%2*%21120% 2*3%T1#2N%#2(=%8"*#%)7%&=#%7"8#%"*&)%7"#83'-%\7%2%8"*#%52&(=#'%&=#%7"1'&%*25#%)7%&=#% "*/<&%628<#%&0/#3%"*&)%&=#%7)15.%&=2&%32&2%7)1%&=2&%/#1')*%$"88%T#%3"'/820#3- I R=#%^V^%file()%7<*(&")*%1#23'%2*%#*&"1#%7"8#%2*3%2''">*'%"&%&)%2*%21120.%$=#1#%#2(=% 8"*#%)7%&=#%7"8#%"'%2*%#8#5#*&%)7%&=#%21120- K R=#%628<#%)7%&=#%621"2T8#%(288#3%$first_name%"'%$=2&%&=#%<'#1%&0/#3%"*%&=#%7)15%2*3% $2'%'#*&%6"2%&=#%POST%5#&=)3%&)%&="'%^V^%/1)>125-%W*0%$="&#'/2(#%"'%'&1"//#3%)<&% $"&=%&=#%T<"8&Q"*%trim()%7<*(&")*- E R=#%foreach%8))/%"&#12&#'%&=1)<>=%#2(=%628<#%"*%&=#%21120%)7%8"*#'%&=2&%$2'%(1#2&#3% $=#*%&=#%file()%7<*(&")*%1#23%"*%&=#%32&#T))N%7"8#%)*%8"*#%I- Y R=#%explode()%7<*(&")*%'/8"&'%</%2%'&1"*>.%$line.%T0%2%'/#("7"#3%3#8"5"&#1.%"*%&="'% (2'#.%T0%2%()8)*-%\&%(1#2&#'%2*%21120%$=#1#%#2(=%)7%&=#%#8#5#*&'%1#/1#'#*&'%&=#% "*3"6"3<28%7"#83'%&=2&%$#1#%(1#2&#3- i R=#%7"1'&%#8#5#*&%)7%&=#%21120%(288#3%$fields[0]%()*&2"*'%2%7"1'&%2*3%82'&%*25#-%R=#% explode()%7<*(&")*%$"88%(1#2&#%2%&$)Q#8#5#*&%21120.%(288#3%$fullname.%()*'"'&"*>%)7% 2%7"1'&%2*3%82'&%*25#- DA R=#%strcasecmp()%7<*(&")*%()5/21#'%&$)%'&1"*>'.%(2'#%"*'#*'"&"6#-%\7%&=#%628<#%&=2&% (25#%"*%71)5%&=#%7)15.%$first_name.%2*3%&=#%628<#%)7%$fullname[0]%21#%#U<28.%&=#*% 8"*#%DD%"'%#*&#1#3- DD R=#%explode()%7<*(&")*%(1#2&#'%&=#%$birth%21120%T0%'/8"&&"*>%$birthday;%7)1% #;25/8#.%03/16/78.%T0%'82'=#'- DC.% DO R=#%implode()%7<*(&")*%d)"*'%)1%a>8<#'b%&=#%21120%#8#5#*&'%&)>#&=#1%"*&)%)*#% '&1"*>.%(288#3%"$newstring".%3"'/820#3%)*%8"*#%DO%2*3%'=)$*%"*%`"><1#%DD-D@- Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. DO '&1"*>.%(288#3%"$newstring".%3"'/820#3%)*%8"*#%DO%2*3%'=)$*%"*%`"><1#%DD-D@- D@ W%621"2T8#%(288#3%$count%$"88%T#%"*(1#5#*&#3%#2(=%&"5#%&=1)<>=%&="'%8))/%&)%N##/% &12(N%)7%&=#%*<5T#1%)7%8"*#'%7)<*3%52&(="*>%&=#%*25#%()5/21#3%"*%8"*#%DA- DI \7%&=#%628<#%)7%&=#%$count%"'%A.%&=#1#%$#1#%*)%52&(=#'.%2*3%&=#%/1)>125%3"'/820'%2% 5#''2>#%'20"*>%')- % Figure 11.13. The HTML form. % Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... arguments: the filehandle returned by fopen() and an optional length argument, how many bytes to write to the file If it fails, fwrite() returns FALSE The file_put_contents() Function The file_put_contents() also writes a string to a file and returns the number of bytes written, but does not require a filehandle Otherwise it is the same as fwrite() and fputs() Format int fwrite ( filehandle, string, [... manageable for designers and programmers, but easier to navigate and debug This section focuses on how to include simple files to help manage content (There are many templating solutions available for PHP today easily found on the Web See http://smarty .php. net to find about Smarty, a template engine designed for PHP. ) To include files in your PHP program, the PHP include() and require() functions are...  arial   font,  centered and  vertically  aligned  at  the  top  of  the  page   Figure 11.24 The page header Example 11.27 Code  View:   (The main page: page .php) < ?php 1 2 $page_name = $_REQUEST['name']; /*http://localhost/exemples/page .php? name=about_us */ // Get the body of the page mysql_ connect("localhost","root","") or die (mysql_ error()); mysql_ select_db("test") or die (mysql_ error()); $sql =... instant feedback, and less travelling back and forth between the browser and server, but to ensure that the data has been verified, PHP can recheck it Once the user has filled out a form and submitted it, PHP can check to see if all the boxes have been filled out correctly, and if not, the user is told to reenter the data before the form data is processed With the power provided by regular expressions,... as its argument and returns TRUE if the filename exists and is readable If the PHP script is being executed by the server, the server’s permissions (usually limited) determine whether or not the PHP program can read from the file, and if it is being executed at the shell prompt, the permissions of the user running the script are the deciding factor Normally, the file should be readable by others Format...  though  the MySQL  database  system  is  not  discussed  until  Chapter  13,   “Introduction  to MySQL, ”  we  use  it  here  to  provide  a  more  real-­‐world  example  All  you   really  need  to  understand  is  that  the  the PHP  script  makes  a  connection  to  a  database   and  fetches  data  from  it  that  will  be  displayed  in  the  browser  In  this  line,  the PHP   mysql_ connect()... text and binary files for reading, writing, and appending from within a PHP script, how to deal with permissions and ownership, upload files, and navigate directories The last part of the chapter discussed content management using external files 11.5.1 What You Should Know Now that you have finished this chapter you should be able to answer the following questions: 1 What  is  a  filehandle and  how...  writable?   10 What  is  meant by  “uploading”  a  file?  What  encoding  type  is  used by  the  browser   for  file  uploads?   11 How  do  you  copy and  remove  files?   12 How  do  you  open  a  directory  in  a PHP  script and  list  its  contents?   13 How  do  you  manage  files  with  include() and  require()?   11.5.2 What’s Next? In Chapter 12, “Regular Expressions and Pattern Matching,” we... /^[a-zA-Z][\w\.\-]+[a-zA-Z0-9]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,4}$/ is called a regular expression and might look like jibberish, but by the time you finish this chapter, you will understand what all these symbols mean and how to use them We will break the expression into very small units, and when all of the pieces have been explained, we will use it to validate an HTML form Let’s start by defining a regular expression and what it is used for When a user fills... series of bytes If the file contents look weird when it is opened or you have a lot broken images, use the "b" mode $handle = fopen("/home/marko/file.txt", "wb"); $handle = fopen("http://www.ellieq.com/", "w"); $handle = fopen("ftp://user:password@ellieq.com/myfile.txt", "a");   The fwrite() and fputs() Functions The fwrite() function writes a string text to a file and returns the number of bytes written . the carriage return and linefeed translation will be part of the byte count.) Format int ftell ( resource handle ) % Example: $filehandle("myfile",. "r"); $contents=fgets($filehandle, 1024); echo ftell( $filehandle); // Current read postion in bytes, // starting at byte 1024 Example 11.9. 4)3#%!"#$c% <html><head><title>The

Ngày đăng: 21/01/2014, 09:20

Từ khóa liên quan

Mục lục

  • PHP & MySQL by Example

  • Copyright

    • Preface

    • Acknowledgments

    • Chapter 1

      • 1.1. From Static to Dynamic Web Sites

        • 1.1.1. Static Web Sites

        • 1.1.2. Dynamic Web Sites

        • 1.1.3. What Is Open Source?

        • 1.2. About PHP

          • 1.2.1. Where to Get PHP and Documentation

          • 1.3. About MySQL

            • 1.3.1. Where to Get MySQL and Documentation

            • 1.3.2. Features of MySQL

            • 1.3.3. How to Install MySQL and PHP

            • 1.3.4. Advantages of MySQL and PHP

            • 1.4. Chapter Summary

              • 1.4.1. What You Should Know

              • 1.4.2. What’s Next?

              • Chapter 2

                • 2.1. The Life Cycle of a Web Page

                  • 2.1.1. Analysis of a Web Page

                  • 2.2. The Anatomy of a PHP Script

                    • 2.2.1. The Steps of Writing a PHP Script

                    • 2.3. Some Things to Consider

                      • 2.3.1. PHP and HTML Are Different Languages

                      • 2.3.2. Statements, Whitespace, and Line Breaks

                      • 2.3.3. Comments

                      • 2.3.4. Using PHP Functions

                      • 2.4. Review

                        • 2.4.1. PHP on the Command Line

Tài liệu cùng người dùng

Tài liệu liên quan