PHP file handling

fopen() function is used to open files in PHP.

Open files

There is no separate file creation function in PHP. The fopen() function is used to create and open files. When a file is opened using the fopen() function, if the file does not exist, an attempt is made to create the file and a resource is returned. If the open fails, the function returns FALSE.

Syntax

resource fopen (string $filename, string mode)

The first parameter of this function contains the name of the file to be opened , the second parameter specifies which mode to use to open the file:

<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>

The file may be opened through the following modes:

Mode                     Description

r             Read only. Start at the beginning of the file. ​

r+ ​ ​ ​ Read/Write. Start at the beginning of the file. ​

w ​ ​ ​ ​ Only write. Opens and clears the contents of the file; if the file does not exist, creates a new file. ​

w+ ​ ​ ​ Read/Write. Opens and clears the contents of the file; if the file does not exist, creates a new file. ​

a ​ ​ ​ ​ Append. Opens and writes to the end of the file, or creates a new file if it does not exist. ​

a+ ​ ​ ​ Read/Append. Maintain file contents by writing to the end of the file. ​

x ​ ​ ​ ​ Only write. Create new file. If the file already exists, returns FALSE and an error. ​

x+ ​ ​ Read/write. Create new file. If the file already exists, returns FALSE and an error.

Note: If the fopen() function cannot open the specified file, it returns 0 (false).

Example

If the fopen() function cannot open the specified file, the following example will generate a message:

<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
// 不能打开指定文件的错误信息: Unable to open file 
?>
</body>
</html>

Close the file

fclose() Function used to close an open file:

<?php
$file = fopen("test.txt","r");
//执行一些代码
fclose($file);
?>

Detect end of file (EOF)

##feof() function detects whether the end of file (EOF) has been reached.

The feof() function is useful when looping through data of unknown length.

Note: In w , a and x modes, you cannot read open files!

if (feof($file)) echo "End of file";

##Read the file line by linefgets() function is used to read a file line by line from a file.

Note: After calling this function, the file pointer will move to the next line.

Syntax

string fgets( int handle [, int length] )

fgets() Reads a line from the file pointed to by handle and returns a string up to length-1 bytes long. Stops on a newline character (included in the return value), EOF, or after length-1 bytes have been read. If length is not specified, it defaults to 1K, or 1024 bytes.

Example

The following example reads a file line by line until the end of the file:

<?php
$file = fopen("welcome.txt", "r") or exit("无法打开文件!");
// 读取文件每一行,直到文件结尾
while(!feof($file))
{
 echo fgets($file). "<br>";
}
fclose($file);
?>

Reads the file character by character

fgetc() function is used to read a file character by character from a file.

Note: After calling this function, the file pointer will move to the next character.

Example

The following example reads the file character by character until the end of the file:

<?php
$file=fopen("welcome.txt","r") or exit("无法打开文件!");
while (!feof($file))
{
  echo fgetc($file);
}
fclose($file);
?>

Read the entire file

fread() function is used to read files (safe for binary files).

Syntax:

string fread( int handle, int length )

##fread() Reads up to length bytes from the file pointer handle. Reading of the file will stop when any of the following situations are encountered:

When up to length bytes have been read

When the end of the file is reached (EOF)

(for network streams) when a packet is available

or (after opening the userspace stream) when 8192 bytes have been read

Read 10 from the file Bytes (including spaces):

<?php
  $filename = "test.txt";
  $fh = fopen($filename, "r");
  echo fread($fh, "10");
  fclose($fh);
?>

file_get_contents()

file_get_contents() function is used to read the entire file into a string, Returns a string on success, FALSE on failure.

Syntax:

string file_get_contents( string filename [, int offset [, int maxlen]] )

Parameter description:

Parameters Description

filename The name of the file to be read

offset Optional, Specify the starting position of reading, the default is the starting position of the file

maxlen Optional, specify the length of the read file, in bytes

Example:

<?php
 $filename = 'NoAlike.txt';
 $filestring = file_get_contents($filename);
 echo $filestring;
?>

fwrite()

fwrite() function is used to write a string to a file and returns the number of characters written successfully, otherwise it returns FALSE.

Syntax:

int fwrite( resource handle, string string [, int length] )

fwrite() writes the contents of string to the file Pointer handle.

Parameter description:

Parameter                                                                                            The fopen() function creates data the string to be written

length Optional, specifies the maximum number of bytes to be written

If the optional parameter length is specified, writing will stop when length bytes have been written or string has been written.

Example:

<?php
  // 要写入的文件名字
  $filename = 'file.txt';
   // 写入的字符
  $word = "你好!";
  $fh = fopen($filename, "w");
  echo fwrite($fh, $word);    // 输出:6
  fclose($fh);
?>

Execute this example program. In the same directory as the program, the content of the file.txt file is: Hello!

In the above example, if the length parameter is used, at most length strings can be written:

echo fwrite($fh, $word, 4); // Output :4


##file_put_contents()

file_put_contents() function is used to put string Write to a file, and return the number of bytes of data written to the file if successful, or FALSE if failed.

Syntax:

int file_put_contents (string filename, string data [, int flags [, resource context]])

Parameter description:

Parameters                                                                                                                                                          data The data to be written. The type can be string, array (but not multi-dimensional array), or stream resource flags Optional, specifies how to open/write the file. Possible values: FILE_USE_INCLUDE_PATH: Check the built-in path for a copy of filename

FILE_APPEND: Write data appended to the end of the file

LOCK_EX: Lock the file

context Optional, Context is a set of options through which text attributes can be modified

Example:

<?php
   echo file_put_contents("test.txt", "This is something.");
?>

Run this example, the browser output:

18

Continuing Learning
||
<?php $filename = "test.txt"; //需要创建一个test.txt文件 $fh = fopen($filename, "r"); echo fread($fh, "10"); fclose($fh); ?>
submitReset Code