This article describes how to read and write files in php. We mainly use the three functions file_get_contents, fwrite, and file. Then, we simply say that is_readable can be used to determine whether a file can be written. This article describes how to read and write files in php. We mainly use the three functions file_get_contents, fwrite, and file. Then, we simply say that is_readable can be used to determine whether a file can be written.
Script ec (2); script
The first is to check whether a file can be read (permission problem) or whether the file exists. We can use the is_readable function to obtain information .:
Php/func_filesystem_is_readable.htm "> is_readable function usage
The Code is as follows: |
|
$ File = "test.txt "; If (is_readable ($ file )) { Echo ("$ file is readable "); } Else { Echo ("$ file is not readable "); } ?> |
Output:
Test.txt is readable
Use the file_get_contents function to read files. This function can read large amounts of data or remote server files. However, allow_url_fopen = On must be started in php. ini; otherwise, this function is unavailable.
The Code is as follows: |
|
$ File = "filelist. php "; If (file_exists ($ file) = false ){ Die ('file does not exist '); } $ Data = file_get_contents ($ file ); Echo htmlentities ($ data ); ?> |
Reading remote files is another topic in this tutorial.
The Code is as follows: |
|
Function vita_get_url_content ($ url ){ If (function_exists ('file _ get_contents ')){ $ File_contents = file_get_contents ($ url ); } Else { $ Ch = curl_init (); $ Timeout = 5; Curl_setopt ($ ch, curlopt_url, $ url ); Curl_setopt ($ ch, curlopt_returntransfer, 1 ); Curl_setopt ($ ch, curlopt_connecttimeout, $ timeout ); $ File_contents = curl_exec ($ ch ); Curl_close ($ ch ); } Return $ file_contents; } |
Use fread Functions
To read files. This function can read the specified data size.
// Fread reads file instance 1
The Code is as follows: |
|
$ Filename = "/www.111cn.net/local/something.txt "; $ Handle = fopen ($ filename, "r "); $ Contents = fread ($ handle, filesize ($ filename )); Fclose ($ handle ); |
// Php5 and later versions read Remote Server Content
The Code is as follows: |
|
$ Handle = fopen ("http://www.111cn.net/", "rb "); $ Contents = stream_get_contents ($ handle ); Fclose ($ handle ); |
There is also a way to read binary files:
The Code is as follows: |
|
$ Data = implode ('', file ($ file )); |
Fwrite file write operations
Fwrite () writes the string content to the file pointer. If length is specified, the write will stop after the length byte is written or the string is written.
Fwrite () returns the number of written characters. If an error occurs, false is returned.
File writing function:
The Code is as follows: |
|
// File Writing Function Function PHP_Write ($ file_name, $ data, $ method = "w "){ $ Filenum = @ fopen ($ file_name, $ method ); Flock ($ filenum, LOCK_EX ); $ File_data = fwrite ($ filenum, $ data ); Fclose ($ filenum ); Return $ file_data; } ?> |