PHP and MySQL by Example- P10

Chia sẻ: Thanh Cong | Ngày: | Loại File: PDF | Số trang:50

0
46
lượt xem
9
download

PHP and MySQL by Example- P10

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

Tham khảo tài liệu 'php and mysql by example- p10', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả

Chủ đề:
Lưu

Nội dung Text: PHP and MySQL by Example- P10

  1. 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. Code  View:   The ftell() Function Marking a Position in a File Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  2. Explanation 1 A  file  is  opened  for  reading. 2 The  variable,  $substring,  is  assigned  the  string  "eastern",  a  string  that  will  be   searched  for  in  the  file  that  was  just  opened. 3 As  each  line  is  read  from  the  file,  the  substr_count()  function  will  search  for   the  string  "eastern"  in  a  line  and  return  the  number  of  times  it  was  found.   The  first  time  this  function  returns  1  or  more,  the  next  line  will  be  entered. 4 The  ftell()  function  will  return  the  byte  position  of  where  the  next  read   operation  will  take  place.  The  line  containing  "eastern"  has  already  been   read.  The  byte  position  is  the  number  of  characters  from  the  beginning  of  the   file.  This  value  is  saved  in  $bytes,  to  be  used  later  with  the  fseek()  function. 5 The  fseek()  function  will  start  at  the  beginning  of  the  file,  byte  0,  and  move  to   the  position  returned  from  ftell(),  byte  291,  in  this  example.  See  Figure   11.10. 6 When  fgets()  starts  reading  lines  from  the  file  it  picks  up  right  after  the  line   where  the  substring  "eastern"  was  found. 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.
  3. 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. Open a File Explanation 1 The  file  is  the  URL  of  a  Web  site. 2 The  Web  page  is  opened  for  reading  and  a  filehandle  is  returned,  called  $fh. 3 The  expression  in  the  while  loop  uses  the  feof()  function  to  check  whether  we  are  not   yet  at  the  end  of  the  file. 4 The  fgets()  function  reads  1024  bytes  at  a  time  from  the  page.  The   htmlspecialchars()  function  converts  any  special  characters  to  HTML  entities;  for   example,  an  &  would  become  &amp  and  a  <  would  become  &lt,  and  so  on.  The  output   shown  in  Figure  11.11  is  the  actual  source  page  (View  Source)  that  was  used  to  create   the  page.   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  4. 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.
  5. Example 11.11. Parsing Lines "> Select a first name from the file.
  6. $address,"19".$birth[2], '$'.number_format($salary,2))); 13 echo "$newstring"; 14 $count++; echo ""; } } 15 if($count==0){ echo "$first_name is not in the file."; } } ?> Explanation 1 The  variable,  $filename,  is  assigned  the  path  to  a  file  called  data.file  one  level   above  the  document  root  of  the  server  in  a  directory  called  mydir. 2 The  built-­‐in  file()  function  takes  the  filename  as  its  argument  (not  a  filehandle)   and  returns  an  array  where  each  line  is  an  element  of  the  array. 3 The  foreach  loop  cycles  over  each  element  of  the  array  of  lines,  extracting  the  index   and  the  value  of  the  line. 4 By  adding  one  to  the  value  of  $line_number,  the  index  in  the  array,  we  can  start  the   count  at  1.  This  value  will  be  placed  in  front  of  each  line  every  time  the  loop  body  is   executed. 5 Each  line  and  its  line  number  are  displayed  as  shown  in  Figure  11.12. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  7. 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. Code  View:   Parsing Lines
  8. 2 process_file(); } 3 function show_form(){ ?> Exploding and Imploding
  9. } } ?> Explanation 1 If  the  form  has  not  been  submitted  yet,  the  show_form()  function  will  display  it. 2 If  the  submit  button  was  pressed,  the  form  has  already  been  filled  out,  and  now  it  is   time  to  process  it.  The  process_file()  function  is  called. 3 This  is  where  the  show_form()  function  is  declared,  which  produces  a  very  simple   HTML  form  with  one  text  box  and  a  submit  button.  The  user  will  type  in  the  first   name  of  someone  from  an  external  text  file,  called  datebook.  See  Figure  11.13. 4 This  is  where  the  process_file()  function  is  called.  It  will  read  a  file  into  an  array   and  break  each  line  of  the  file  into  fields.  If  a  line  matches  the  first  name  of  the   input  value  typed  into  the  form,  that  data  for  that  person  will  be  displayed. 5 The  PHP  file()  function  reads  an  entire  file  and  assigns  it  to  an  array,  where  each   line  of  the  file  is  an  element  of  the  array. 6 The  value  of  the  variable  called  $first_name  is  what  the  user  typed  in  the  form  and   was  sent  via  the  POST  method  to  this  PHP  program.  Any  whitespace  is  stripped  out   with  the  built-­‐in  trim()  function. 7 The  foreach  loop  iterates  through  each  value  in  the  array  of  lines  that  was  created   when  the  file()  function  read  in  the  datebook  file  on  line  5. 8 The  explode()  function  splits  up  a  string,  $line,  by  a  specified  delimiter,  in  this   case,  by  a  colon.  It  creates  an  array  where  each  of  the  elements  represents  the   individual  fields  that  were  created. 9 The  first  element  of  the  array  called  $fields[0]  contains  a  first  and  last  name.  The   explode()  function  will  create  a  two-­‐element  array,  called  $fullname,  consisting  of   a  first  and  last  name. 10 The  strcasecmp()  function  compares  two  strings,  case  insensitive.  If  the  value  that   came  in  from  the  form,  $first_name,  and  the  value  of  $fullname[0]  are  equal,  then   line  11  is  entered. 11 The  explode()  function  creates  the  $birth  array  by  splitting  $birthday;  for   example,  03/16/78,  by  slashes. 12,   The  implode()  function  joins  or  “glues”  the  array  elements  together  into  one   13 string,  called  "$newstring",  displayed  on  line  13  and  shown  in  Figure  11.14. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  10. 13 string,  called  "$newstring",  displayed  on  line  13  and  shown  in  Figure  11.14. 14 A  variable  called  $count  will  be  incremented  each  time  through  this  loop  to  keep   track  of  the  number  of  lines  found  matching  the  name  compared  in  line  10. 15 If  the  value  of  the  $count  is  0,  there  were  no  matches,  and  the  program  displays  a   message  saying  so.   Figure 11.13. The HTML form.   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  11. Figure 11.14. After the lines in the file have been parsed. Output from Example 11.12. The readfile() Function—Reading and Writing a File The readfile() function reads from a file and writes it to the output buffer. It returns the number of bytes read from the file. If an error occurs, FALSE is returned and an error message is printed. Format int readfile ( string filename [, bool use_include_path [, resource context]] )   Example: readfile("myfile.txt"); Example 11.13. Reading and Outputting a File Reading and Outputting a File 1
  12. ?> Explanation 1 The  HTML    tag  is  used  here  so  that  when  the  file  is  displayed,  the   newlines  will  be  preserved,  as  shown  in  Figure  11.16. 2 The  readfile()  function  will  read  in  the  contents  of  data.file  and  send  the   output  to  the  the  output  stream;  for  example,  browser  or  terminal.  It  returns   the  number  of  bytes  read.  The  function  was  called  as  @readfile()  to  suppress   the  printing  of  an  error  message  if  an  error  occurred. Figure 11.15. Reading a file and outputting its contents.   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  13. 11.2.8. Opening a File for Writing and Appending When you open a file for writing, the file is created if it does not exist, and truncated if it does. If you open a file for appending, the file will not be overwritten if it exists and the data will be appended to the bottom of the file. If it does not exist, opening for appending creates the file. To open a file for writing, the fopen() function returns a filehandle to either a text or binary file. Although UNIX and MacOS do not distinguish between text and binary files, Windows does. If a file is to be shared by multiple operating systems, it is safer to open it in binary mode in conjunction with one of the other modes. (As of PHP 4.3.2, the default mode is set to binary for all platforms that distinguish between binary and text mode.) UNIX and MacOS X represent the end-of-line character with \n, whereas Windows uses \r\n. If you use Windows, the "t" mode can be used with plain-text files to translate the \n to \r\n. Otherwise, the "b" mode should be used, which does not interpret data but treats it as just a 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. An alias for the fwrite() function is fputs(). It takes two 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, [ int length] )   Example: $bytes=fwrite( $filehandle, "Peter Piper picked a peck of pickled peppers.\n"); $bytes=fwrite( $filehandle, "Jack in the Beanstalk", 4); Example 11.14.       Open a File (Output: Contents of info.txt) Joe Shmoe Jr. 100 Main St. jshmoe@whatever.mil Major   Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  14. Explanation 1 A  set  of  scalar  variables  are  defined,  the  information  that  will  be  written  to  a   file. 2 A  string  is  created  with  each  word  separated  by  a  tab. 3 Because  the  file  must  be  a  writeable  file,  it  is  stored  outside  the  server’s  root   directory.  It  is  located  in  the  a  directory  called  mydir,  and  the  name  of  the  file   is  info.txt. 4 The  filehandle  returned  from  fopen()  is  opened  for  writing.  The  "b"  (binary)   mode  is  recommended  when  using  systems  that  differentiate  between  binary   and  text  files;  that  is,  Windows. 5 The  fwrite()  function  writes  the  specified  string,  $outputstring  to  the   filehandle,  $filehandle.  The  number  of  bytes  written  are  returned  by  the   strlen()  function. Appending to a File When a file is opened for appending, the write will start at the end of the file. If the file does not exist, it will be created. Example 11.15. Code  View:   Appending Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  15. Explanation 1 The  values  of  the  variables  are  assigned  to  the  variable,  $outputstring.  Each  value  is   separated  by  a  tab  and  the  string  ends  with  a  newline. 2 The  file  info.txt  is  opened  for  appending,  which  means  the  internal  file  pointer  will   start  writing  at  the  end  of  the  file,  rather  than  the  beginning. 3 If  the  fwrite()  function  fails,  the  program  will  produce  an  error.  Otherwise,  the  string   in  $outputstring  will  be  appended  to  the  file.  Output  is  shown  in  Figure  11.16.  The  line   starting  with  Joe Doe  has  been  appended. 4 The  contents  of  the  file  are  read  and  displayed.   Figure 11.16. After writing and appending. Output from Example 11.15.   Locking Files with flock() What if two or more customers are trying to write to a Web site at the same time? To prevent this, you can lock the file so that a user has exclusive access to it and then unlock it when he or she has finished using it. PHP supports a portable way of locking complete files with the flock() function. This is called advisory locking because all accessing programs have to use the same locking mechanism or it will not work. See Table 11.6 for a list of flock() operations. Table 11.6. flock() Operations (Constant)  Numeric   Operation Value Operation  It  Peforms LOCK_EX 2 Acquires  an  exclusive  lock  (writer). LOCK_NB 4 Nonblocking  (no  waiting)  while  the  lock  is  being   acquired. LOCK_SH 1 Acquires  a  shared  lock  (reader). LOCK_UN 3 Releases  a  lock  (shared  or  exclusive).   The flock() function uses a filehandle returned from the fopen() function. The lock can be released by fclose(), which is also called automatically when the script finished. The function returns TRUE on success or FALSE on failure. Whether or not this function works properly is entirely dependent on your operating system; for example, it is not supported on older systems like Windows 98 or for networked file systems (NFS), and so on. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  16. Format bool flock ( resource handle, int operation [, int &wouldblock] ) Example 11.16. Code  View:     File Locking
  17. 11.2.9. File Checks Before performing operations on files or directories, it is a good practice to verify whether or not the file even exists, if it is readable, writable, executable, and so on. PHP provides a set of functions for testing the status of a file. See Table 11.7. Table 11.7. File Testing Functions Function Description file_exists() Checks  if  the  file  or  directory  exists. is_dir() Checks  if  the  filename  is  a  directory. is_file() Checks  if  the  filename  is  a  file. is_link() Checks  if  the  filename  is  a  symbolic  link. is_readable() Checks  if  the  file  is  readable. is_uploaded_file() Checks  if  the  file  was  uploaded  by  an  HTTP  host. is_writable() Checks  if  the  file  is  writable. is_writeable() An  alias  for  is_writable. stat() Gives  information  about  a  file.   The file_exists() Function The file_exists() function checks to see whether a file or directory exists. It returns TRUE if it does, and FALSE if it does not. Format bool file_exists ( string filename );   Example: if ( file_exists("filetest.php"); Example 11.17. Appending
  18. ?> Explanation 1 The  file_exists()  function  checks  to  see  if  the  image  file  assigned  to   $filename  exists  before  displaying  it. The is_file() Function The is_file() function checks to see if a file exists and is a regular file; that is, not a directory. It takes the name of the file as its argument and returns TRUE if the file is a regular file, and FALSE if it is not.[7] [7] Processing is faster if you use a relative path name rather than an absolute path. Format bool is_file ( string filename )   Example: if ( is_file("myfile.php"){ print "True"; } Example 11.18. Is it a Regular File? Explanation 1 The  is_file()  function  not  only  checks  to  see  if  the  file  exists,  but  also  if  it  is  a  regular   file;  that  is,  not  a  directory. 2 This  line  is  displayed  in  Figure  11.17.  The  file  c:\wamp\www  is  not  a  regular  file.           Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  19. Figure 11.17. The file exist, but it is not a plain file. Output from Example 11.18.   The is_readable() Function The is_readable() function checks to see if you can read from a file. It takes the filename 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 bool is_readable ( string filename );   Example: if ( is_readable("file.txt")) { echo "File is readable";} Example 11.19. Is Readable?
  20. The is_writable() Function When opening a file for writing, you might run into a problem with permissions if you are trying to put the file in a directory not accessible to the Web. Because the PHP script is executed on behalf of the server, it shares the same permissions. Normally, the server does not have world-write permissions turned on to prevent hackers from breaking into your site and causing havoc. The is_writable() (or is_writeable) function returns true if a file exists and is writable, and false if it is not. Format bool is_writable ( string filename )   Example: if (is_writable($filename)) {echo "$filename is writable";} Example 11.20. Appending
Đồng bộ tài khoản