Home >Backend Development >PHP Tutorial >PHP file operations: reading and writing files
where the @ symbol means that PHP will suppress all errors generated by the current function call. 2, PHP reads files After opening the file in PHP, you need to read the file, usually using the fgets() function. This function can read one line of content from the file at a time, and it will continue to read data until it encounters the newline character of this line, or the end symbol EOF of the full text. The fgets() function can only read one line of data, so if you need to read all the data in the file, you must use a loop statement to complete it. for example:
where the feof() function is used Check whether the file ends. The only parameter of this function is the file pointer (that is, $fp corresponds to the open file). Of course, in PHP you can also use the readfile() function to read the entire file at once. This function includes opening the file, reading the file and outputting it to the browser, and closing the file. for example:
3, PHP close file Use the function fclose() to close the file. Second, how to write data to file in PHP Similar to PHP reading files, PHP writing files also requires: opening the file, writing data and closing the file. The method of opening and closing files has been explained above, but what about writing data to files in PHP? Use the fwrite() function, such as fwrite(file path, write content):
Other useful file functions: file_exists(): Check whether the file exists and return a Boolean value filesize(): Check the file size and can directly echo the output unlink(): Delete files. Note that there is no delete function in PHP. |