SlideShare a Scribd company logo
Files Operations
Opening A File And Reading Its Contents In order to read the contents of the file into a PHP script, there are three distinct steps to be followed:  Open the file and assign it a file handle.  Interact with the file, via its handle, and extract its contents into a PHP variable.  Close the file.
Example: 1.php <?php  // set file to read $file  =  ‘omelette.txt'  or die( 'Could not open file!' );  // open file  $fh  =  fopen ( $file ,  'r' ) or die( 'Could not open file!' );  // read file contents  $data  =  fread ( $fh ,  filesize ( $file )) or die( 'Could not read file!' );  // close file  fclose ( $fh );  // print file contents  echo  $data ;  ?>
Explanations Each Of The Three Steps In Detail:  Open the file and assign it a file handle PHP needs a file handle to read data from a file. This file handle can be created with the  fopen()  function, which accepts two arguments: the name and path to the file, and a string indicating the &quot;mode&quot; in which the file is to be opened ( 'r'  for read).  Three different modes are available for use with the  fopen()  function. Here's the list:  'r'  - opens a file in read mode  'w'  - opens a file in write mode, destroying existing file contents  'a'  - opens a file in append mode, preserving existing file contents
Interact with the file via its handle and extract its contents into a PHP variable If the  fopen() function is successful, it returns a file handle,  $fh , which can be used for further interaction with the file. This file handle is used by the  fread() function, which reads the file and places its contents into a variable.  The second argument to  fread() is the number of bytes to be read. You can usually obtain this information through the  filesize()  function, -returns the size of the file in bytes. Close the file PHP closes the file automatically once it reaches the end of the script, but it's a good habit to closing the file with  fclose() . die() function: as a primitive error-handling mechanism; In the event of a fatal error, such as the file path being invalid or the file permissions being such that PHP cannot read it,  die() terminates script processing and optionally displays a user-specified error message.
An Alternative Method Of Reading Data From A File:  file() and   file_get_contents()  Function file()  function: reads the entire file into an array with one line of code.  Each element of the array then contains one line from the file.  To display the contents of the file, simply iterate over the array in a  foreach()  loop and print each element. If don't want the data in an array: Try the  file_get_contents()  function, new in PHP 4.3.0 and PHP 5.0, which reads the entire file into a string.
Example: 2.php ( file() ) <?php  // set file to read $file  =  'omelette.txt'  or die( 'Could not read file!' );  // read file into array  $data  =  file ( $file ) or die( 'Could not read file!' );  // loop through array and print each line  foreach ( $data  as  $line ) {       echo  $line ;  }  ?>
Example: 3.php  ( file_get_contents() ) <?php  // set file to read $file  =  'omelette.txt'  ;  // read file into string  $data  =  file_get_contents ( $file ) or die( 'Could not read file!' );  // print contents  echo  $data ;  ?>
include()  And   require() Functions Those are useful functions to import files into a PHP script. These functions can be used to import external files lock, stock and barrel into a PHP script, which is very handy if, for example, you have a modular application which has its code broken down across files in separate locations. Example: Assume that on your Web site you have a standard menu bar at the top of every page, and a standard copyright notice in the bottom. Instead of copying and pasting the header and footer code on each individual page, PHP simply create separate files for the header and footer, and import them at the top and bottom of each script. This also makes a change to the site design easier to implement: instead of manually editing a gazillion files, you simply edit two, and the changes are reflected across your entire site instantaneously.
header.php <html>  <head>  <title> <?php  echo  $page [ 'title' ]; ?> </title>  </head>  <body>    <table width=&quot;90%&quot; border=&quot;0&quot; cellspacing=&quot;5&quot; cellpadding=&quot;5&quot;>  <tr>  <td><a href=&quot;#&quot;>Home</a></td>  <td><a href=&quot;#&quot;>Site Map</a></td>  <td><a href=&quot;#&quot;>Search</a></td>  <td><a href=&quot;#&quot;>Help</a></td>  </tr>  </table>
footer.php   <br /> <center>Your usage of this site is subject to its published <a href=&quot;tac.html&quot;>terms and conditions</a>. Data is copyright Big Company Inc, 1995- <?php  echo  date ( &quot;Y&quot; ,  mktime ());  ?> </center>  </body>  </html>
Implimentation  include() Function  Example: 4.php  <?php  // create an array to set page-level variables $page  = array();  $page [ 'title' ] =  'Product Catalog' ;  /* once the file is imported, the variables set above will become available to it */  // include the page header  include( 'header.php' );  ?>    <?php  // include the page footer  include( 'footer.php' );  ?>
when you run the script above, PHP will automatically read in the header and footer files, merge them with the HTML content, and display the complete page to you. Notice that you can even write PHP code inside the files being imported. When the file is first read in, the parser will look for  <?php...?>  tags, and automatically execute the code inside it.  PHP also offers the  require_once()  and  include_once() functions, which ensure that a file which has already been read is not read again. This can come in handy if you have a situation in which you want to eliminate multiple reads of the same include file, either for performance reasons or to avoid corruption of the variable space. A quick note on the difference between the  include()  and  require() functions: the  require() function returns a fatal error if the named file cannot be found and halts script processing, while the  include()  function returns a warning but allows script processing to continue.
Writing To A File The steps involved in writing data to a file are almost identical to those involved in reading it:  open the file and obtain a file handle. use the file handle to write data to it. and close the file. There are two differences: first, you must  fopen()  the file in write mode (' w ' for write), and second, instead of using the  fread()  function to read from the file handle, use the  fwrite()  function to write to it.
Example: 5.php <?php  // set file to write $file  =  'dump.txt' ;  // open file  $fh  =  fopen ( $file ,  'w' ) or die( 'Could not open file!' );  // write to file  fwrite ( $fh ,  &quot;Look, Ma, I wrote a file! &quot; ) or die( 'Could not write to file' );  // close file  fclose ( $fh );  ?> When you run this script, it should create a file named dump.txt in /PHP 101(5), and write a line  of text to it, with a carriage return at the end. Notice that double quotes are needed to convert into a carriage return. The  fopen() ,  fwrite()  and  fread()  functions are all binary-safe, which means you can use them on binary files without worrying about damage to the file contents.
Writing To A File via  file_put_contents() Example: 6.php file_put_contents()  function: which takes a string and writes it to a file in a single line of code. Bear in mind that the directory in which you're trying to create the file must exist before you can write to it. Forgetting this important step is a common cause of script errors. <?php  // set file to write $filename  =  'dump.txt' ;  // write to file  file_put_contents ( $filename ,  &quot;Look, Ma, I wrote a file! &quot; ) or die( 'Could not write to file' );  ?>
To Test The existence of a File via  file_exists()  function Example:  7.php Here's an example which asks the user to enter the path to a file in a Web form, and then returns a message displaying whether or not the file exists: <html>  <head>  </head>  <body>  <?php  // if form has not yet been submitted & display input box  if (!isset( $_POST [ 'file' ])) {  ?>   <form action=&quot; <?php  echo  $_SERVER [ 'PHP_SELF' ];  ?> &quot; method=&quot;post&quot;>    Enter file path <input type=&quot;text&quot; name=&quot;file&quot;>   </form>  <?php  }  // else process form input  else {       // check if file exists & display appropriate message       if ( file_exists ( $_POST [ 'file' ])) {          echo  'File exists!' ;          }      else {          echo  'File does not exist!' ;      }  }  ?>  </body>  </html>
To check the status of the file PHP also comes with a bunch of functions that allow you to test the status of a file - for example to find out whether it exists, whether it's empty, whether it's readable or writable, and whether it's a binary or text file. Here's a brief list: is_dir()  - returns a Boolean indicating whether the specified path is a directory is_file()  - returns a Boolean indicating whether the specified file is a regular file is_link()  - returns a Boolean indicating whether the specified file is a symbolic link is_executable()  - returns a Boolean indicating whether the specified file is executable is_readable()-  returns a Boolean indicating whether the specified file is readable is_writable()-  returns a Boolean indicating whether the specified file is writable filesize()  - gets size of file filemtime()  - gets last modification time of file filamtime()  - gets last access time of file fileowner()  - gets file owner filegroup()  - gets file group fileperms()  - gets file permissions filetype()  - gets file type
Example: 8.php <html>  <head>  </head>  <body>  <?php  /* if form has not yet been submitted, display input box */  if (!isset( $_POST [ 'file' ])) {  ?>  <form action=&quot; <?php  echo  $_SERVER [ 'PHP_SELF' ];  ?> &quot; method=&quot;post&quot;>Enter file path <input type=&quot;text&quot; name=&quot;file&quot;>  </form>  <?php  }  // else process form input  else {    echo  'File name: <b>' . $_POST [ 'file' ]  . '</b><br />' ;       /* check if file exists and display appropriate message */     if ( file_exists ( $_POST [ 'file' ])) {           // print file size     echo  'File size: ' . filesize ( $_POST [ 'file' ]). ' bytes<br />' ;           // print file owner     echo  'File owner: ' . fileowner ( $_POST [ 'file' ]). '<br />' ;           // print file group     echo  'File group: ' . filegroup ( $_POST [ 'file' ]). '<br />' ;           // print file permissions     echo  'File permissions: ' . fileperms ( $_POST [ 'file' ]). '<br />' ;           // print file type     echo  'File type: ' . filetype ( $_POST [ 'file' ]). '<br />' ;           // print file last access time     echo  'File last accessed on: ' . date ( 'Y-m-d' ,  fileatime ( $_POST [ 'file' ])). '<br />' ;           // print file last modification time     echo  'File last modified on: ' . date ( 'Y-m-d' ,  filemtime ( $_POST [ 'file' ])). '<br />' ;
  // is it a directory?           if ( is_dir ( $_POST [ 'file' ])) {              echo  'File is a directory <br />' ;          }           // is it a file?           if ( is_file ( $_POST [ 'file' ])) {              echo  'File is a regular file <br />' ;          }           // is it a link?           if ( is_link ( $_POST [ 'file' ])) {              echo  'File is a symbolic link <br />' ;          }           // is it executable?           if ( is_executable ( $_POST [ 'file' ])) {              echo  'File is executable <br />' ;          }           // is it readable?           if ( is_readable ( $_POST [ 'file' ])) {              echo  'File is readable <br />' ;          }           // is it writable?           if ( is_writable ( $_POST [ 'file' ])) {              echo  'File is writable <br />' ;          }      }      else {          echo  'File does not exist! <br />' ;      }  }  ?>  </body>  </html>
Output The output maybe like this: File name: /usr/local/apache/logs/error_log  File size: 53898 bytes  File owner: 0  File group: 0  File permissions: 33188  File type: file  File last accessed on: 2004-05-26  File last modified on: 2004-06-20  File is a regular file File is readable
To Sum-up: omelette’s page case study Let's go back to my Spanish omelette recipe: “omelette.txt” SPANISH OMELETTE INGREDIENTS:  1 chopped onion  1 chopped tomato 1/2 chopped green pepper  4 beaten eggs Salt and pepper to taste METHOD:  1. Fry onions in a pan 2. Pour beaten eggs over onions and fry gently  3. Add tomatoes, green pepper, salt and pepper to taste  4. Serve with toast or bread I need a quick way to convert them all into HTML so that they look presentable on my Web site using PHP.
Example: 9.php <html>  <head></head> <body>  <?php  // read recipe file into array  $data  =  file ( 'omelette.txt' ) or die( 'Could not read file!' );  /* first line contains title: read it into variable */  $title  =  $data [ 0 ];  // remove first line from array  array_shift ( $data );  ?>  <h2> <?php  echo  $title ;  ?> </h2>  <?php  /* iterate over content and print it */  foreach ( $data  as  $line ) {      echo  nl2br ( $line );  }  ?>  </body>  </html>
Discussion I've used the  file()  function to read the recipe into an array, and assign the first line (the title) to a variable. That title is then printed at the top of the page. Since the rest of the data is fairly presentable as is, I can simply print the lines to the screen one after the other.  Line breaks are automatically handled for me by the extremely cool  nl2br()  function, which converts regular text linebreaks into the HTML equivalent, the  <br />  tag.  The end result: an HTML-ized version of my recipe that the world can marvel at.
Output: <html>  <head></head> <body> <h2>SPANISH OMELETTE </h2>  INGREDIENTS:<br /> - 1 chopped onion<br />  - 1 chopped tomato<br />  - 1/2 chopped green pepper<br />  - 4 beaten eggs<br />  - Salt and pepper to taste<br />  METHOD:<br /> 1. Fry onions in a pan<br />  2. Pour beaten eggs over onions and fry gently<br />  3. Add tomatoes, green pepper, salt and pepper to taste<br /> 4. Serve with toast or bread<br />  </body>  </html>
Uploading a file Description:Before you can use PHP to manage your uploads, you must first build an HTML form that lets users select a file to upload. See our  HTML Form  lesson for a more in-depth look at forms.   <html> <head> <title>A simple file upload form</title> </head> <body> <form action=&quot;processupload.php&quot; enctype=&quot;multipart/form-data&quot; method=&quot;POST&quot;> <input type=&quot;hidden&quot; name=&quot;MAX_FILE_SIZE&quot; value=&quot;5120038383838&quot;> <p><strong>File to Upload:</strong> <input type=&quot;file&quot; name=&quot;fileupload&quot;></p> <p><input type=&quot;submit&quot; value=&quot;upload!&quot;></p> </form> </body> </html>
Uploading process <?php $file_dir = &quot;upload&quot;; foreach($_FILES as $file_name => $file_array) { echo &quot;path: &quot;.$file_array['tmp_name'].&quot;<br>&quot;; echo &quot;name: &quot;.$file_array['name'].&quot;<br>&quot;; echo &quot;type: &quot;.$file_array['type'].&quot;<br>&quot;; echo &quot;size: &quot;.$file_array['size'].&quot;<br>&quot;; if (is_uploaded_file($file_array['tmp_name'])) { move_uploaded_file($file_array['tmp_name'], &quot;$file_dir/$file_array[name]&quot;) or die (&quot;Couldn't copy&quot;); echo &quot;file was moved!<br><br>&quot;; }  } ?>

More Related Content

Php File Operations

  • 2. Opening A File And Reading Its Contents In order to read the contents of the file into a PHP script, there are three distinct steps to be followed: Open the file and assign it a file handle. Interact with the file, via its handle, and extract its contents into a PHP variable. Close the file.
  • 3. Example: 1.php <?php // set file to read $file = ‘omelette.txt' or die( 'Could not open file!' ); // open file $fh = fopen ( $file , 'r' ) or die( 'Could not open file!' ); // read file contents $data = fread ( $fh , filesize ( $file )) or die( 'Could not read file!' ); // close file fclose ( $fh ); // print file contents echo $data ; ?>
  • 4. Explanations Each Of The Three Steps In Detail: Open the file and assign it a file handle PHP needs a file handle to read data from a file. This file handle can be created with the fopen() function, which accepts two arguments: the name and path to the file, and a string indicating the &quot;mode&quot; in which the file is to be opened ( 'r' for read). Three different modes are available for use with the fopen() function. Here's the list: 'r' - opens a file in read mode 'w' - opens a file in write mode, destroying existing file contents 'a' - opens a file in append mode, preserving existing file contents
  • 5. Interact with the file via its handle and extract its contents into a PHP variable If the fopen() function is successful, it returns a file handle, $fh , which can be used for further interaction with the file. This file handle is used by the fread() function, which reads the file and places its contents into a variable. The second argument to fread() is the number of bytes to be read. You can usually obtain this information through the filesize() function, -returns the size of the file in bytes. Close the file PHP closes the file automatically once it reaches the end of the script, but it's a good habit to closing the file with fclose() . die() function: as a primitive error-handling mechanism; In the event of a fatal error, such as the file path being invalid or the file permissions being such that PHP cannot read it, die() terminates script processing and optionally displays a user-specified error message.
  • 6. An Alternative Method Of Reading Data From A File: file() and file_get_contents() Function file() function: reads the entire file into an array with one line of code. Each element of the array then contains one line from the file. To display the contents of the file, simply iterate over the array in a foreach() loop and print each element. If don't want the data in an array: Try the file_get_contents() function, new in PHP 4.3.0 and PHP 5.0, which reads the entire file into a string.
  • 7. Example: 2.php ( file() ) <?php // set file to read $file = 'omelette.txt' or die( 'Could not read file!' ); // read file into array $data = file ( $file ) or die( 'Could not read file!' ); // loop through array and print each line foreach ( $data as $line ) {      echo $line ; } ?>
  • 8. Example: 3.php ( file_get_contents() ) <?php // set file to read $file = 'omelette.txt' ; // read file into string $data = file_get_contents ( $file ) or die( 'Could not read file!' ); // print contents echo $data ; ?>
  • 9. include() And require() Functions Those are useful functions to import files into a PHP script. These functions can be used to import external files lock, stock and barrel into a PHP script, which is very handy if, for example, you have a modular application which has its code broken down across files in separate locations. Example: Assume that on your Web site you have a standard menu bar at the top of every page, and a standard copyright notice in the bottom. Instead of copying and pasting the header and footer code on each individual page, PHP simply create separate files for the header and footer, and import them at the top and bottom of each script. This also makes a change to the site design easier to implement: instead of manually editing a gazillion files, you simply edit two, and the changes are reflected across your entire site instantaneously.
  • 10. header.php <html> <head> <title> <?php echo $page [ 'title' ]; ?> </title> </head> <body> <!-- top menu bar --> <table width=&quot;90%&quot; border=&quot;0&quot; cellspacing=&quot;5&quot; cellpadding=&quot;5&quot;> <tr> <td><a href=&quot;#&quot;>Home</a></td> <td><a href=&quot;#&quot;>Site Map</a></td> <td><a href=&quot;#&quot;>Search</a></td> <td><a href=&quot;#&quot;>Help</a></td> </tr> </table> <!-- header ends -->
  • 11. footer.php <!-- footer begins --> <br /> <center>Your usage of this site is subject to its published <a href=&quot;tac.html&quot;>terms and conditions</a>. Data is copyright Big Company Inc, 1995- <?php echo date ( &quot;Y&quot; , mktime ()); ?> </center> </body> </html>
  • 12. Implimentation include() Function Example: 4.php <?php // create an array to set page-level variables $page = array(); $page [ 'title' ] = 'Product Catalog' ; /* once the file is imported, the variables set above will become available to it */ // include the page header include( 'header.php' ); ?> <!-- HTML content here --> <?php // include the page footer include( 'footer.php' ); ?>
  • 13. when you run the script above, PHP will automatically read in the header and footer files, merge them with the HTML content, and display the complete page to you. Notice that you can even write PHP code inside the files being imported. When the file is first read in, the parser will look for <?php...?> tags, and automatically execute the code inside it. PHP also offers the require_once() and include_once() functions, which ensure that a file which has already been read is not read again. This can come in handy if you have a situation in which you want to eliminate multiple reads of the same include file, either for performance reasons or to avoid corruption of the variable space. A quick note on the difference between the include() and require() functions: the require() function returns a fatal error if the named file cannot be found and halts script processing, while the include() function returns a warning but allows script processing to continue.
  • 14. Writing To A File The steps involved in writing data to a file are almost identical to those involved in reading it: open the file and obtain a file handle. use the file handle to write data to it. and close the file. There are two differences: first, you must fopen() the file in write mode (' w ' for write), and second, instead of using the fread() function to read from the file handle, use the fwrite() function to write to it.
  • 15. Example: 5.php <?php // set file to write $file = 'dump.txt' ; // open file $fh = fopen ( $file , 'w' ) or die( 'Could not open file!' ); // write to file fwrite ( $fh , &quot;Look, Ma, I wrote a file! &quot; ) or die( 'Could not write to file' ); // close file fclose ( $fh ); ?> When you run this script, it should create a file named dump.txt in /PHP 101(5), and write a line of text to it, with a carriage return at the end. Notice that double quotes are needed to convert into a carriage return. The fopen() , fwrite() and fread() functions are all binary-safe, which means you can use them on binary files without worrying about damage to the file contents.
  • 16. Writing To A File via file_put_contents() Example: 6.php file_put_contents() function: which takes a string and writes it to a file in a single line of code. Bear in mind that the directory in which you're trying to create the file must exist before you can write to it. Forgetting this important step is a common cause of script errors. <?php // set file to write $filename = 'dump.txt' ; // write to file file_put_contents ( $filename , &quot;Look, Ma, I wrote a file! &quot; ) or die( 'Could not write to file' ); ?>
  • 17. To Test The existence of a File via file_exists() function Example: 7.php Here's an example which asks the user to enter the path to a file in a Web form, and then returns a message displaying whether or not the file exists: <html> <head> </head> <body> <?php // if form has not yet been submitted & display input box if (!isset( $_POST [ 'file' ])) { ?> <form action=&quot; <?php echo $_SERVER [ 'PHP_SELF' ]; ?> &quot; method=&quot;post&quot;>   Enter file path <input type=&quot;text&quot; name=&quot;file&quot;>  </form> <?php } // else process form input else {      // check if file exists & display appropriate message      if ( file_exists ( $_POST [ 'file' ])) {         echo 'File exists!' ;         }     else {         echo 'File does not exist!' ;     } } ?> </body> </html>
  • 18. To check the status of the file PHP also comes with a bunch of functions that allow you to test the status of a file - for example to find out whether it exists, whether it's empty, whether it's readable or writable, and whether it's a binary or text file. Here's a brief list: is_dir() - returns a Boolean indicating whether the specified path is a directory is_file() - returns a Boolean indicating whether the specified file is a regular file is_link() - returns a Boolean indicating whether the specified file is a symbolic link is_executable() - returns a Boolean indicating whether the specified file is executable is_readable()- returns a Boolean indicating whether the specified file is readable is_writable()- returns a Boolean indicating whether the specified file is writable filesize() - gets size of file filemtime() - gets last modification time of file filamtime() - gets last access time of file fileowner() - gets file owner filegroup() - gets file group fileperms() - gets file permissions filetype() - gets file type
  • 19. Example: 8.php <html> <head> </head> <body> <?php /* if form has not yet been submitted, display input box */ if (!isset( $_POST [ 'file' ])) { ?> <form action=&quot; <?php echo $_SERVER [ 'PHP_SELF' ]; ?> &quot; method=&quot;post&quot;>Enter file path <input type=&quot;text&quot; name=&quot;file&quot;> </form> <?php } // else process form input else {   echo 'File name: <b>' . $_POST [ 'file' ]  . '</b><br />' ;      /* check if file exists and display appropriate message */    if ( file_exists ( $_POST [ 'file' ])) {          // print file size    echo 'File size: ' . filesize ( $_POST [ 'file' ]). ' bytes<br />' ;          // print file owner    echo 'File owner: ' . fileowner ( $_POST [ 'file' ]). '<br />' ;          // print file group    echo 'File group: ' . filegroup ( $_POST [ 'file' ]). '<br />' ;          // print file permissions    echo 'File permissions: ' . fileperms ( $_POST [ 'file' ]). '<br />' ;          // print file type    echo 'File type: ' . filetype ( $_POST [ 'file' ]). '<br />' ;          // print file last access time    echo 'File last accessed on: ' . date ( 'Y-m-d' , fileatime ( $_POST [ 'file' ])). '<br />' ;          // print file last modification time    echo 'File last modified on: ' . date ( 'Y-m-d' , filemtime ( $_POST [ 'file' ])). '<br />' ;
  • 20. // is it a directory?          if ( is_dir ( $_POST [ 'file' ])) {             echo 'File is a directory <br />' ;         }          // is it a file?          if ( is_file ( $_POST [ 'file' ])) {             echo 'File is a regular file <br />' ;         }          // is it a link?          if ( is_link ( $_POST [ 'file' ])) {             echo 'File is a symbolic link <br />' ;         }          // is it executable?          if ( is_executable ( $_POST [ 'file' ])) {             echo 'File is executable <br />' ;         }          // is it readable?          if ( is_readable ( $_POST [ 'file' ])) {             echo 'File is readable <br />' ;         }          // is it writable?          if ( is_writable ( $_POST [ 'file' ])) {             echo 'File is writable <br />' ;         }     }     else {         echo 'File does not exist! <br />' ;     } } ?> </body> </html>
  • 21. Output The output maybe like this: File name: /usr/local/apache/logs/error_log File size: 53898 bytes File owner: 0 File group: 0 File permissions: 33188 File type: file File last accessed on: 2004-05-26 File last modified on: 2004-06-20 File is a regular file File is readable
  • 22. To Sum-up: omelette’s page case study Let's go back to my Spanish omelette recipe: “omelette.txt” SPANISH OMELETTE INGREDIENTS: 1 chopped onion 1 chopped tomato 1/2 chopped green pepper 4 beaten eggs Salt and pepper to taste METHOD: 1. Fry onions in a pan 2. Pour beaten eggs over onions and fry gently 3. Add tomatoes, green pepper, salt and pepper to taste 4. Serve with toast or bread I need a quick way to convert them all into HTML so that they look presentable on my Web site using PHP.
  • 23. Example: 9.php <html> <head></head> <body> <?php // read recipe file into array $data = file ( 'omelette.txt' ) or die( 'Could not read file!' ); /* first line contains title: read it into variable */ $title = $data [ 0 ]; // remove first line from array array_shift ( $data ); ?> <h2> <?php echo $title ; ?> </h2> <?php /* iterate over content and print it */ foreach ( $data as $line ) {     echo nl2br ( $line ); } ?> </body> </html>
  • 24. Discussion I've used the file() function to read the recipe into an array, and assign the first line (the title) to a variable. That title is then printed at the top of the page. Since the rest of the data is fairly presentable as is, I can simply print the lines to the screen one after the other. Line breaks are automatically handled for me by the extremely cool nl2br() function, which converts regular text linebreaks into the HTML equivalent, the <br /> tag. The end result: an HTML-ized version of my recipe that the world can marvel at.
  • 25. Output: <html> <head></head> <body> <h2>SPANISH OMELETTE </h2> INGREDIENTS:<br /> - 1 chopped onion<br /> - 1 chopped tomato<br /> - 1/2 chopped green pepper<br /> - 4 beaten eggs<br /> - Salt and pepper to taste<br /> METHOD:<br /> 1. Fry onions in a pan<br /> 2. Pour beaten eggs over onions and fry gently<br /> 3. Add tomatoes, green pepper, salt and pepper to taste<br /> 4. Serve with toast or bread<br /> </body> </html>
  • 26. Uploading a file Description:Before you can use PHP to manage your uploads, you must first build an HTML form that lets users select a file to upload. See our HTML Form lesson for a more in-depth look at forms. <html> <head> <title>A simple file upload form</title> </head> <body> <form action=&quot;processupload.php&quot; enctype=&quot;multipart/form-data&quot; method=&quot;POST&quot;> <input type=&quot;hidden&quot; name=&quot;MAX_FILE_SIZE&quot; value=&quot;5120038383838&quot;> <p><strong>File to Upload:</strong> <input type=&quot;file&quot; name=&quot;fileupload&quot;></p> <p><input type=&quot;submit&quot; value=&quot;upload!&quot;></p> </form> </body> </html>
  • 27. Uploading process <?php $file_dir = &quot;upload&quot;; foreach($_FILES as $file_name => $file_array) { echo &quot;path: &quot;.$file_array['tmp_name'].&quot;<br>&quot;; echo &quot;name: &quot;.$file_array['name'].&quot;<br>&quot;; echo &quot;type: &quot;.$file_array['type'].&quot;<br>&quot;; echo &quot;size: &quot;.$file_array['size'].&quot;<br>&quot;; if (is_uploaded_file($file_array['tmp_name'])) { move_uploaded_file($file_array['tmp_name'], &quot;$file_dir/$file_array[name]&quot;) or die (&quot;Couldn't copy&quot;); echo &quot;file was moved!<br><br>&quot;; } } ?>