PHP directory and file processing methods

Source: Internet
Author: User
Tags fread http post readfile rewind
    1. if (mkdir ("./path", 0700))//Create the path directory in the current directory
    2. echo "created successfully";
    3. ?>
Copy Code

2. Get and change the current directory using the GETCWD () function to get the current working directory, the function has no parameters. Success returns the current working directory, and failure returns false

3. Open and close the directory handle Opendir ($dir) closed ($dir _handle)

4. Read the contents of the directory Readdir (), which is an already open directory handle, and the while loop can implement the traversal of the directory

5. Gets the directories and files in the specified path. Array Scandir (string $directory [, int $sorting _order [, Resource $context]] Description: $directory is the specified path. The parameter $sorting_order is sorted alphabetically by default, and if set to 1, it is arranged in descending alphabetical order. The $context is an optional parameter and is a resource variable that can be generated with the stream_context_create () function, which holds some data about the specific object being manipulated. If the function succeeds, it returns an array containing all directories and filenames under the specified path, and failure returns FALSE2. General method of manipulating Files 3. Open and close the file 1. Open File Resource fopen (string $filename, String $mode [ , bool $use _include_path [, Resource $context]]) $filename parameters. The fopen () function binds the name resource specified by the $filename parameter to a stream $mode parameter. The $mode parameter specifies the mode in which the fopen () function accesses the file, as shown in table 4.5. $mode description ' R ' read-only open the file, from the beginning of the file read ' r+ ' read and write mode open the file, from the beginning of the file header read and write ' W ' write open file, the file pointer to the file header. If the file already exists, delete the existing content, and if the file does not exist, try to create it ' w+ ' read-write mode to open the file and point the file pointer to the file header. If the file already exists, delete the existing content, if the file does not exist, try to create it ' a ' to open the file, point the file pointer to the end of the file, and write the contents of the file if it has already been written from the end of the file. If the file does not exist, try to create it ' a + ' to open the file, and point the file pointer to the end of the file. If the file already has content, it starts reading and writing from the end of the file. If the file does not exist, try to create it ' X ' to create and open the file in writing, pointing the file pointer to the file header. If the file already exists, the fopen () call fails and returns false, and generates an E_warning level error message. If the file does not exist, try to create it. This option is supported by ph and later versions and can only be used for local file ' x+ ' to create and open files in read-write mode, pointing the file pointer to the file header. If the file already exists, the fopen () call fails and returns false, and generates an E_warning level error message. If the file does not exist, try to create it. This option is supported by the ph and later versions and can only be used for local file ' B ' binary mode for connectionfollowed by other modes. If the file system is able to differentiate between binary and text files (Windows differentiated, and UNIX is not differentiated), then this option is required, and it is recommended to use this option all the time for maximum portability

$use the _include_path parameter. If you need to search for files in the include_path (PHP include path, in the PHP configuration file settings), you can set the value of the optional parameter $use _include_path to 1 or true, and the default is False. $context parameters. The optional $context parameter is used only when the file is opened remotely (for example, via HTTP), which is a resource variable that holds some data about the specific operand of the fopen () function. If fopen () opens an HTTP address, this variable records the request type, HTTP version, and other header information of the HTTP request, and if the FTP address is open, the FTP passive/Active mode may be logged

2. Close file bool Fclose (Resource $handle)

4. File write file before writing to open the file, does not exist to create it first, generally use the fopen () function to create a fwrite (). After the file is opened, write to the file the contents of int fwrite (resource $handle, string $string [, int $ Length]) Description: The parameter $handle is the file handle that is written, $string is the string data that will be written to the file, $length is an optional parameter, and if $length is specified, the write is stopped after the first $length bytes of data in $string are written. The File_put_contents () function. PHP 5 also introduces the File_put_contents () function. This function is functionally the same as calling fopen (), fwrite (), and fclose () functions in turn. The syntax format is as follows: int file_put_contents (String $filename, String $data [, int $flags [, Resource $context]]) Description: $filename is the name of the file to write the data to. $data is the string to write, $data can also be an array, but not a multidimensional array. Optional parameters $flags and $context can be used when writing data to remote files using FTP or HTTP, not specifically described here. After the write succeeds, the function returns the number of bytes written, otherwise it returns false. The Fputcsv () function. CSV is a more commonly used file format, typically with. csv as the extension. The CSV format considers a row of a file to be a record, with fields in the record separated by commas. Using the Fputcsv () function in PHP, you can format the specified array as content that conforms to the CSV file format and write to the current line that the file pointer points to. The syntax format is as follows: Int fputcsv (Resource $handle [, Array $fields [, String $delimiter [, String $enclosure]]) Description: The parameter $handle is the file handle to write. The parameter $fields is the array to format. The optional $delimiter parameter is used to set the field delimiter (only one character is allowed), and the default is a comma. The optional $enclosure parameter sets the field wrapping character (only one character is allowed), and the default is double quotation marks

5 reading of the file

1. Read any length fread () function can be used to read the contents of the file, the syntax format is as follows: string fread (int $handle, int $length) Description: Parameter $handle is an open file pointer, $ Length is the maximum number of bytes to read, and the maximum value for $length is 8192. If the end of File flag (EOF) is encountered before the $length bytes are read, the read character is returned and the read operation is stopped. Returns the Read string if the read succeeds, or False if an error occurs. Note: When displaying file contents after reading a file, the text may contain characters that cannot be displayed directly, such as HTML tags. You need to use the Htmlspecialchars () function to convert HTML tags to entities to display the characters in the file.

2. Read the entire file () function. The file () function is used to read entire files into an array with the following syntax format: Array file (string $filename [, int $use _include_path [, Resource $context]]) Description: The function is to return the file as an array, each cell in the array is the corresponding line in the file, including the newline character, or False if it fails. The parameter $filename is the name of the read file, and the $use_inclue_path and $context of the parameters are the same as the ReadFile () function described earlier. The ReadFile () function is used to output the contents of a file into the browser with the following syntax: int readfile (string $filename [, bool $use _include_path [, Resource $context]]) The Fpassthru () function. The Fpassthru () function reads the given file pointer from the current location to EOF and writes the result to the output buffer. To use this function, you must first open the file with the fopen () function, and then pass the file pointer as an argument to the Fpassthru () function, and the Fpassthru () function sends the file contents pointed to by the file pointer to the standard output. Returns False if the operation successfully returns the number of bytes read. The file_get_contents () function. The file_get_contents () function reads the entire or part of a file's contents into a string, with the function of calling fopen (), Fread (), and fclose () functions in turn. The syntax format is as follows: String file_get_contents (string $filename [, int $offset [, int $maxlen]]) Description: $filename is the file name to read, optional parameter $ Offset can specify the offset from the beginning of the file header, and the function can return the content starting at the position specified by $offset from the $maxlen length. If it fails, the function returns false

3. Read a row of data fgets () functions. The fgets () function can read a line of text from a file with the following syntax: string fgets (int $handle [, int $length]) Description: $handle is a file handle that has been opened, optional parameter $length specifies the maximum number of bytes returned. With a line terminator in mind, you can return up to length-1 bytes of string. If $length is not specified, the default is 1024 bytes the FGETSS () function is essentially the same as fgets (), but the FGETSS () function attempts to remove any HTML and PHP tags from the text being read. The Fgetcsv () function. The Fgetcsv () function reads the current line of the specified file, resolves the field using the CSV format, and returns an array containing the fields. The syntax format is as follows: Array fgetcsv (int $handle [, int $length [, String $delimiter [, String $enclosure]])

4. Read a character fgetc () function. The fgetc () function can read a character from the file pointer in the syntax format: string fgetc (Resource $handle) The function returns a character in the file pointed to by the $handle pointer and returns FALSE if EOF is encountered

5. Read the file fscanf () function using the specified format. The fscanf () function can read the data in the file, format it according to the specified format, and return an array. The syntax format is as follows: Mixed fscanf (Resource $handle, String $format [, mixed &$ ...] Any whitespace in the format string matches any whitespace in the input stream. This means that even the tab "\ T" in the format string will also match a space character in the input stream.

6. Uploading and downloading of files

1. Uploading file uploads can be done by submitting an HTML form. After the file upload is finished, it is stored in the temp directory by default, and must be removed from the temp directory or moved to another location using PHP's Move_uploaded_file (). Move_uploaded_file () function syntax is in the following format: BOOL Move_uploaded_file (String $filename, String $destination) Note: Before moving a file, you need to check to see if the file was uploaded via HTTP post. This can be used to ensure that a malicious user cannot spoof a script to access a file that it cannot access, and then needs to use the Is_uploaded_file () function. The function's parameters are temporary file names, and if the file is uploaded via HTTP POST, the function returns True. Example 4.5 Moving a GIF picture file uploaded by an HTML form to an HTML directory

    1. !--HTML form-->
    2. !--? php if (isset ($_post[' up '))
    3. {
    4. if ($_files[' myFile ' [' Type ']== "image/gif")//determine if the file format is gif
    5. {
    6. if ($_files[' myFile '] [' ERROR ']> 0)//To determine if the upload error
    7. echo "error:". $_files[' myFile ' [' Error '];//Output error message
    8. else
    9. {
    10. $tmp _filenam e=$_files[' myFile ' [' tmp_name ']; Temporary file name
    11. $filename =$_files[' myFile ' [' name '];//uploaded file name
    12. $dir = "html/";
    13. if (is_uploaded_file ($tmp _filename))//decide whether to upload via HTTP post
    14. {
    15. if (move_uploaded_file ($tmp _filename, $dir. $filename))//upload and move files
    16. {
    17. echo ' file uploaded successfully! ";
    18. //output File size
    19. The
    20. echo file size is: ". ($_files[' myFile ' [' Size ']/1024). " KB ";
    21. }
    22. else
    23. echo "failed to upload the file! ";
    24. }
    25. }
    26. }
    27. else
    28. {
    29. echo ' file format non-GIF pictures! ";
    30. }
    31. }
    32. ?
Copy Code

2. The file download header () function is to send the correct HTTP header to the browser, which specifies information such as the type of Web page content, the properties of the page, and so on. The header () function is a lot of functions, here are only the following: page jump. If the argument of the header () function is "location:xxx", the page will automatically jump to the URL address that "xxx" points to. For example: Header ("location:http://www.baidu.com"); Jump to Baidu Page header ("Location:first.php"); Jump to the first.php page of the working directory to specify the page content. For example, in the same XML-formatted file, if the header () function parameter is specified as "Content-type:application/xml", the browser will parse it according to the XML file format. But if it is "Content-type:text/xml", the browser will consider it as text parsing. The header () function, in conjunction with the ReadFile () function, allows you to download the files that will be browsed

7. Other common file functions

1. Calculate File size filesize () function is used to calculate the size of the file, in bytes filesize () function combined with the fread () function can be implemented to read the entire file at once

2. Determine if a file exists file_exits () the Is_dir () function is used to determine whether a given file name is a directory Is_file () function to determine whether a given file name is a file. The is_readable () function is used to determine whether a given file is readable. Is_writeable () is used to determine whether a given file is writable

3. deleting files unlink ()

4. copy file bool Copy (string $source, String $dest), which will be overwritten if the target file already exists

5. Move and rename files in addition to the Move_uploaded_file () function, there is also a rename () function to move the file. The syntax format is as follows: BOOL Rename (string $oldname, String $newname [, Resource $context]) Description: The rename () function is mainly used to rename a file, $oldname is the old name of the file, The $newname is the new file name. Of course, if the path of $oldname and $newname is not the same, the function of moving the file is realized.

6. File pointer operation there are many functions in PHP that manipulate file pointers, such as Rewind (), Ftell (), fseek () functions, and so on. The previously used feof () function is used to test whether a file pointer is at the end of a file or a file pointer manipulation function. The rewind () function. The pointer position used to reset the file so that the pointer is returned to the file header. It has only one parameter, which is the file handle of the specified file that has been opened. The Ftell () function. The position of the pointer in the file, which is the offset in the file stream, can be reported in bytes. Its arguments are also file handles that have been opened. The Fseek () function. Can be used to move the file pointer, the syntax format is as follows: Int fseek (resource $handle, int $offset [, int $whence])

Example 4.8 Poll statistics

  1. $votefile = "Ex4_6_vote.txt"; Text file for Count $votefile
  2. if (!file_exists ($votefile))//Determine if the file exists
  3. {
  4. $handle =fopen ($votefile, "w+"); Does not exist then create the file
  5. Fwrite ($handle, "0|0|0"); Initializes the contents of the file
  6. Fclose ($handle);
  7. }
  8. if (Isset ($_post[' Sub '))
  9. {
  10. if (Isset ($_post[' vote '))//Determine if the user is voting
  11. {
  12. $vote =$_post[' vote ']; Receive voting values
  13. $handle =fopen ($votefile, "r+");
  14. $votestr =fread ($handle, FileSize ($votefile)); Read file contents to string $votestr
  15. Fclose ($handle);
  16. $votearray =explode ("|", $VOTESTR); $votestr according to the "|" Segmentation
  17. echo "

    The polls are over!

    ";
  18. if ($vote = = ' PHP ')
  19. $votearray [0]++; If PHP is selected, the 1th value of the array is added 1
  20. echo "The current number of votes in PHP is:". $votearray [0]. "
    ";
  21. if ($vote = = ' ASP ')
  22. $votearray [1]++; If you select ASP, the 2nd value of the array is added 1
  23. echo "The current number of ASP votes is:". $votearray [1]. "
    ";
  24. if ($vote = = ' JSP ')
  25. $votearray [2]++; If you select JSP, the 3rd value of the array is added 1
  26. echo "The current number of tickets for JSP is:". $votearray [2]. "
    ";
  27. Calculate the total number of votes
  28. $sum = $votearray [0]+ $votearray [1]+ $votearray [2];
  29. echo "Total votes:". $sum. "
    ";
  30. $votestr 2=implode ("|", $votearray); Use "|" for the new array after the poll Concatenate into a string $votestr2
  31. $handle =fopen ($votefile, "w+");
  32. Fwrite ($handle, $votestr 2); Writes a new string to the file $votefile
  33. Fclose ($handle);
  34. }
  35. Else
  36. {
  37. echo "";
  38. }
  39. }
  40. ?>
Copy Code
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.