PHP include / require Directives.


PHP include / require Directives  It is often inconvenient or impractical to include all of the code and function definitions used by a script in a single source file.  PHP provides a very powerful mechanism to support storing various logical components of a script in one or more separate source files.  include     Includes and evaluates the specified file. If the specified file doesn't exist, a warning will be issued. include_once     Includes and evaluates the specified file only once (if the file had previously been included, it will not be included again). require     Includes and evaluates the specified file. If the specified file doesn't exist, a fatal error will be issued. require_once     Includes and evaluates the specified file only once (if the file had previously been included, it will not be included again).  Files for including are first looked in the PHP configuration value include_path relative to the current working directory, and then in include_path relative to the directory of current script. You can determine the current include_path value by referencing the function phpinfo().  Includes/Requireds are not limited to local files on the server. If a full URL is specified, both data files and the execution of other scripts can be specified that are stored on other servers.  When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.  The file that is included must match the standard file content syntax for PHP; that is, the file begins in HTML mode. If you wish to include PHP code in the included file, it must be surrounded by the standard <?php ?> tags.  include 'test.mod'; include 'subdir/test.mod'; include_once '/home/user/fred/test.mod'; include 'http://example.site.com/test.cgi';  $filename = 'test.mod'; require_once $filename;  PHP and File Processing  PHP includes a rich set of functions designed to process file-based data. It has the advantage over most other programming languages in that it can access web-based data stored on other servers using the same functions that are used to access locally-stored server data.  Accessing a File as an Array - file()  The function  file(filename)  will return the indicated file as an array, storing one line in the file per element in the array. This function is therefore best suited for text-based data files. It can also be used to read web-based data as well -- if the filename argument is a full URL, it will go to the internet and read the corresponding file.  $data = file('test.dat');  $filename = 'somedata.txt'; $moredata = file($filename);  $internetFile = file('http://some.server.com/webpage.html');  In later versions of PHP4, the file_get_contents() function is available. It differs from file() in that it reads the data into a binary-safe string. It can therefore be used to read binary data, such as images.  $imagedata = file_get_contents ('image.jpg');  Lower-level File Processing Functions  PHP's lower-level file processing functions are modeled after their equivalent C functions. Below is a summary of this group of functions designed to read/write data at many levels (individual bytes/characters, contiguous blocks of characters, individual lines), and direct/random access of data files:      fopen ( filename, attr )     Opens specified filename using one of the following attribute strings found here. It returns a resource handle to the file that must be used in the other related file functions.      fgets ( handle [, length] )     Reads the next line of text from the associated file, optionally limiting the resultant string's length to length.      fgetss ( handle [,length [,allowable_tags]] )     Identical to fgets(), except that fgetss() attempts to strip any HTML and PHP tags from the text it reads. You can use the optional third parameter to specify tags which should not be stripped.      fgetc ( handle )     Returns a string containing a single character read from the file pointed to by handle. Returns FALSE on EOF.      fread ( handle, length )     Binary-safe file read. fread() reads up to length bytes from the file pointer referenced by handle. Reading stops when length bytes have been read, or EOF is reached, whichever comes first.      fgetcsv ( handle, length [,delimiter [,enclosure]] )     Gets line from file pointer and parses for CSV (Comma-Separated Value) fields. Similar to fgets() except that fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read. The optional third delimiter parameter defaults as a comma, and the optional enclosure defaults as a double quotation mark. Both delimiter and enclosure are limited to one character. If either is more than one character, only the first character is used.      fscanf ( handle, format [, &args...] )     Similar to sscanf().      feof ( handle )     Tests for end-of-file on a file pointer.      fwrite ( handle, string [, length] )     Binary safe file write. fwrite() writes the contents of string to the file stream pointed to by handle. If the length argument is given, writing will stop after length bytes have been written or the end of string is reached, whichever comes first.      fputs ( handle, string [, length] )     Alias of fwrite().      fseek ( handle, offset [, whence] )     Seek to a specified byte location in a file. Sets the file position indicator for the file referenced by handle. The new position, measured in bytes from the beginning of the file, is obtained by adding offset to the position specified by whence.      Possible whence values are SEEK_SET (from the beginning of the file, SEEK_CUR (from current location of file pointer + offset), and SEEK_END (from end of file; offset is normally a negative value to access a location near the end of a file).      ftell ( handle )     Returns the position of the file pointer referenced by handle.      ftruncate ( handle, size )     Truncates the file to the specified size.      rewind ( handle )     Reposition a file's pointer to the beginning of the file.      fclose ( handle )     Closes the specified file handle.  $handle = fopen('test.dat','r'); while ($line = fgets($handle))   echo $line; fclose ($handle);  $handle = fopen('test.dat','r'); // Limit the lines read to only 80 characters while ($line = fgets($handle,80))   echo $line; fclose ($handle);  $handle = fopen('test.dat','r'); while ($c = fgetc($handle))   echo $c; fclose ($handle);  $handle = fopen('test.dat','r'); while (!feof($handle)) {   $c = fgetc($handle);   echo $c;   } fclose ($handle);  CSV-based Datafile (Example 1):  donr,Don,,Retzlaff,"this, that" elr001,Elisa,L,Retzlaff,something else mac203,Mac,,Macro,more and moredata    // Read the CSV-based Data $infile = fopen('people.dat','r'); while (!feof($infile)) {   $fields = fgetcsv($infile,100);   print_r ($fields);   } fclose ($infile);    Array (     [0] => donr     [1] => Don     [2] =>     [3] => Retzlaff     [4] => this, that ) Array (     [0] => elr001     [1] => Elisa     [2] => L     [3] => Retzlaff     [4] => something else ) Array (     [0] => mac203     [1] => Mac     [2] =>     [3] => Macro     [4] => more and moredata )  CSV-based Datafile (Example 2):  donr|Don||Retzlaff|'this, that' elr001|Elisa|L|Retzlaff|something else mac203|Mac||Macro|more and moredata    // Read the CSV-based Data $infile = fopen('people2.dat','r'); while (!feof($infile)) {   $fields = fgetcsv($infile,100,'|',"'");   print_r ($fields);   } fclose ($infile);  // Read a file from the web and store it locally  $infile = fopen('http://server.com/dataimage.jpg','rb'); $outfile = fopen('localimage.jpg','wb');  while (!feof($infile)) {   $image = fread($infile,1000);   fwrite ($outfile,$image);   } fclose ($infile); fclose ($outfile);  // Read and display last 10 characters in file $directfile = fopen('testfile.dat','r'); fseek ($directfile,-10,SEEK_END); $line = fread ($directfile,10); echo "<p>Last 10 chrs in file: '$line'\n"; fclose ($directfile);  echo "<p>Read a file backwards: "; $directfile = fopen('testfile.dat','r'); fseek ($directfile,-1,SEEK_END); while (true) {   echo fgetc($directfile);   if (ftell($directfile) == 1) break;   fseek ($directfile,-2,SEEK_CUR);   } fclose ($directfile);  // Trunacate a file after the 10th line $infile = fopen('testfile.dat','r+'); for ($i=1; $i <= 10; $i++)   fgets($infile); $len = ftell($infile); rewind($infile); ftruncate($infile,$len); fclose($infile);  Other PHP File-Related Functions  A variety of additinal file functions are available to check various status options on files, check the type of a file, and other file-related activities. Below is a quick summary of many of these functions:      is_dir ( filename )     Tells whether the filename is a directory.      is_executable ( filename )     Tells whether a filename is an executable file.      is_readable ( filename )     Tells whether a filename is readable.      is_writeable ( filename )     Tells whether a filename is writeable.      file_exists ( filename )     Tells whether a filename exists.      fileatime ( filename )     Gets last access time of filename (UNIX timestamp).      filectime ( filename )     Gets last changed time of filename (UNIX timestamp). In most UNIX systems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated.      filemtime ( filename )     Gets last modified time (content changed) of filename (UNIX timestamp).      filegroup ( filename )     Tells the value of the group ID of the filename.      fileinode ( filename )     Tells the value of the filename's inode.      fileowner ( filename )      fileperms ( filename )      filesize ( filename )      filetype ( filename )  Error Checking - the @ operator  When processing data files, a very real possibility is that there might be an error while attempting to access the file, the most common error being that the file doesn't exist.  Normally the file() function (and the other file-related functions we discussed) will produce an warning message when a file does not exist, and will continue processing your script. In most cases, this is not appropriate, as your script is probably relying on that data file being there.  The PHP @ operator is designed to trap this type of error and prevent the warning message from appearing. The @ operator is placed immediately before the function that might cause the warning. It is therefore your responsibility to test for the error to see if it actually occured or not.  $data = @file('test.dat'); if (!$data) exit ("Could not open file test.dat.");  if (!($data = @file('test.dat')))   exit ("Could not open file test.dat.");  $str = @file_get_contents('test.dat'); if (!$str) exit ("Could not open file test.dat.");  $handle = @fopen('test.dat','r'); if (!$handle) exit ("Could not open file test.dat.");  $chars = @readfile('test.dat'); if (!$chars) exit ("Could not open file test.
dat.");


Share on Google Plus

About M

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment