Home >Backend Development >PHP Tutorial >PHP directory and file processing methods
2. Get and change the current directory The current working directory can be obtained using the getcwd() function, which has no parameters. Returns the current working directory on success, FALSE on failure 3. Open and close directory handles opendir($dir) closed($dir_handle) 4. Read directory contents readdir(), this parameter is an already opened directory handle, which can be used with the while loop to traverse the directory 5. Get the directories and files in the specified path. array scandir(string $directory [, int $sorting_order [, resource $context ]]) Note: $directory is the specified path. The parameter $sorting_order defaults to sorting in ascending alphabetical order. If set to 1, it means sorting in descending alphabetical order. $context is an optional parameter and is a resource variable that can be generated using the stream_context_create() function. This variable stores some data related to the specific operation object. If the function succeeds, it returns an array containing all directory and file names under the specified path, if it fails, it returns FALSE. 2. General methods of operating files 3. Opening and closing files 1.Open the file resource fopen(string $filename, string $mode [, bool $use_include_path [, resource $context ]]) ●$filename parameter. 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 files. The values are shown in Table 4.5. $mode illustrate 'r' Open the file in read-only mode and read from the beginning of the file 'r+' Open the file in read-write mode and start reading and writing from the beginning of the file. 'w' Open the file in write mode 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 'w+' Open the file in read-write mode 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' Open the file in writing mode and point the file pointer to the end of the file. If the file already has content, it will be written from the end of the file. If the file does not exist try to create it 'a+' Open the file in read-write mode and point the file pointer to the end of the file. If the file already contains content, reading and writing will start from the end of the file. If the file does not exist try to create it 'x' Create and open the file for 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 then attempts to create it. This option is supported by PH and later versions and can only be used for local files 'x+' Create and open the file for reading and 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 then attempts to create it. This option is supported by PH and later versions and can only be used for local files 'b' Binary mode, used to connect behind other modes. If the file system can distinguish between binary files and text files (Windows does, but UNIX does not), you need to use this option. It is recommended to always use this option for maximum portability ●$use_include_path parameter. If you need to search for files in include_path (PHP's include path, set in PHP's configuration file), The value of the optional parameter $use_include_path can be set to 1 or TRUE, and the default is FALSE. ●$context parameter. The optional $context parameter is only used when the file is opened remotely (such as via HTTP). It is a resource variable. It stores some data related to the specific operation object of the fopen() function. If fopen() opens an HTTP address, Then this variable records the request type, HTTP version and other header information of the HTTP request; if the FTP address is opened, What is recorded may be the passive/active mode of FTP 2.Close the file bool fclose(resource $handle) 4.Writing files The file needs to be opened before writing. If it does not exist, create it first. Generally, it is created using the fopen() function. ●fwrite(). After the file is opened, write content to the file int fwrite(resource $handle , string $string [, int $length ]) Description: The parameter $handle is the file handle to be written. $string is the string data to be written to the file, $length is an optional parameter. If $length is specified, writing will stop after writing the first $length bytes of data in $string. ●file_put_contents() function. PHP 5 also introduced the file_put_contents() function. The function of this function is the same as calling the fopen(), fwrite(), and fclose() functions in sequence. The syntax format is as follows: int file_put_contents(string $filename , string $data [, int $flags [, resource $context ]]) Note: $filename is the name of the file to which data is to be written. $data is the string to be written. $data can also be an array, but it cannot be a multi-dimensional array. When using FTP or HTTP to write data to a remote file, you can use the optional parameters $flags and $context, which are not introduced in detail here. After the writing is successful, the function returns the number of bytes written, otherwise it returns FALSE. ●fputcsv() function. CSV is a commonly used file format, generally with .csv as the extension. The CSV format treats one line of the file as a record, and the fields in the record are separated by commas. Use the fputcsv() function in PHP to format the specified array into content that conforms to the CSV file format, and write the current line pointed to by the file pointer. 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 be written. The parameter $fields is the array to be formatted. The optional $delimiter parameter is used to set the field delimiter (only one character is allowed), which defaults to a comma. The optional $enclosure parameter sets the field wrapper (only one character allowed), the default is double quotes 5 File reading 1. Read any length The fread() function can be used to read the contents of a file. The syntax format is as follows: string fread(int $handle, int $length) Description: The parameter $handle is the open file pointer. $length specifies the maximum number of bytes to read, and the maximum value of $length is 8192. If the end-of-file flag (EOF) is encountered before reading $length bytes, the read characters are returned and the reading operation stops. If the read is successful, the read string is returned, if an error occurs, FALSE is returned. Note: When displaying the file content after reading the file, the text may contain characters that cannot be displayed directly, such as HTML tags. At this time, you need to use the htmlspecialchars() function to convert HTML tags into entities to display the characters in the file. 2. Read the entire file ●file() function. The file() function is used to read the entire file into an array. The syntax format is as follows: array file(string $filename [, int $use_include_path [, resource $context ]]) Description: The function of this function is to return the file as an array. Each unit in the array is a corresponding line in the file, including newlines. Returns FALSE on failure. The parameter $filename is the file name to be read. The meanings of the parameters $use_inclue_path and $context are the same as those introduced before. ●readfile() function. The readfile() function is used to output the contents of a file to the browser. The syntax format is as follows: int readfile(string $filename [, bool $use_include_path [, resource $context ]]) ●fpassthru() function. The fpassthru() function reads the given file pointer from the current position to EOF and writes the result to the output buffer. To use this function, you must first open the file using the fopen() function, and then pass the file pointer as a parameter to the fpassthru() function, The fpassthru() function sends the contents of the file pointed to by the file pointer to standard output. Returns the number of bytes read if the operation is successful, otherwise returns FALSE. ●file_get_contents() function. The file_get_contents() function can read the entire or part of the file content into a string. The function is the same as calling the fopen(), fread() and fclose() functions in sequence. The syntax format is as follows: string file_get_contents(string $filename [, int $offset [, int $maxlen ]]) Description: $filename is the file name to be read. The optional parameter $offset can specify the offset from the beginning of the file. The function can return content with a length of $maxlen starting from the position specified by $offset. If it fails, the function will return FALSE 3. Read a row of data ●fgets() function. The fgets() function can read a line of text from a file. The syntax format is as follows: string fgets(int $handle [, int $length ]) Description: $handle is the file handle that has been opened. The optional parameter $length specifies the maximum number of bytes returned, taking into account line terminators. A string of up to length-1 bytes can be returned. If $length is not specified, the default is 1024 bytes ●The fgetss() function is basically the same as fgets(), except that the fgetss() function will try to remove any html and php tags from the read text. ●fgetcsv() function. The fgetcsv() function can read the current line of the specified file, parse out the fields using CSV format, and return an array containing these 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. The syntax format is: string fgetc(resource $handle) This function returns a character in the file pointed to by the $handle pointer. If it encounters EOF, it returns FALSE 5. Read files using the specified format fscanf() function. 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 will match any whitespace in the input stream. This means that even the tab character "t" in the format string will match a space character in the input stream. 6. File upload and download 1.File upload File upload can be achieved by submitting an html form. After the file is uploaded, it is stored in the temporary directory by default. At this time, it must be deleted from the temporary directory or moved to other places. Use PHP's move_uploaded_file() to move it to another location The syntax format of the move_uploaded_file() function is as follows: bool move_uploaded_file(string $filename, string $destination) Note: You need to check whether the file was uploaded via HTTP POST before moving it. This can be used to ensure that malicious users cannot trick scripts into accessing files that are otherwise inaccessible. At this time, you need to use the is_uploaded_file() function. The parameter of this function is the temporary file name of the file. If the file is uploaded through HTTP POST, the function returns TRUE. Example 4.5 Move the GIF image file uploaded by the HTML form to the html directory
2.File download The function of the header() function is to send the correct HTTP header to the browser. The header specifies the type of web page content, page attributes and other information. The header() function has many functions, only the following are listed here: ●Page jump. If the parameter of the header() function is "Location: xxx", the page will automatically jump to the URL pointed to by "xxx". For example: header("Location: http://www.baidu.com"); //Jump to Baidu page header("Location: first.php"); //Jump to the first.php page in the working directory ●Specify web page content. For example, for the same XML format file, if the parameter of the header() function 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 treat it as text parsing. The header() function combined with the readfile() function can download the file to be browsed 7. Other commonly used file functions 1. Calculate file size The filesize() function is used to calculate the size of a file in bytes The filesize() function combined with the fread() function can read the entire file at once 2. Determine whether the file exists file_exits() The is_dir() function is used to determine whether a given file name is a directory The is_file() function is used 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.Delete files unlink() 4.Copy files bool copy(string $source,string $dest), if the directory file already exists, it will be overwritten 5. Move and rename files In addition to the move_uploaded_file() function, there is also a rename() function that can also move files. The syntax format is as follows: bool rename ( string $oldname , string $newname [, resource $context ] ) Note: The rename() function is mainly used to rename a file. $oldname is the old name of the file, and $newname is the new file name. Of course, if the paths of $oldname and $newname are different, the function of moving the file is realized 6. File pointer operation There are many functions in PHP that operate file pointers, such as rewind(), ftell(), fseek() functions, etc. The feof() function used before is used to test whether the file pointer is at the end of the file. Also belongs to the file pointer operation function. rewind() function. Used to reset the file pointer position so that the pointer returns to the beginning of the file. It has only one parameter, which is the file handle of the specified file that has been opened. ftell() function. The position of a pointer in the file, that is, the offset in the file stream, can be reported in bytes. Its parameter is also the file handle that has been opened. fseek() function. It 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 Voting statistics
Statement: The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn Previous article:How to download files in php, the correct way to download php filesNext article:How to download files in php, the correct way to download php files Related articlesSee more |