Home / code / php

Files in PHP

There are several ways to read a file :

$array=file('filename.ext');
File reads a file in as a array. Everyline is a element in the array (with the newline attached).

$string=file_get_contents('filename.ext');
Reads the file in as a string.

Reading and writing to file with fopen()

If you want to read and write to a file it is best to use fopen();

$fh=fopen('filename.ext', 'mode');
The 'mode' can be several things :
r Opens the file only for reading, places the pointer at the start of the file.
r+ Opens the file for reading and writing, places the pointer at the start of the file
w Opens only for writing; Places the pointer at the start of the file and makes the file 0 bytes. If the file doesn't exists, it tries to make it.
w+ Opens for reading and writing; Places the pointer at the start of the file and makes the file 0 bytes. If the file doesn't exists, it tries to make it.
a Opens only for writing; Places the pointer at the end of the file. If the file doesn't exists, it tries to make it.
a+ Opens for reading and writing; Places the pointer at the end of the file. If the file doesn't exists, it tries to make it.

Example :

$filename="test.txt";
$fh = fopen($filename,'r+');

// read the file
$buffer = fread($fh, filesize($filename));

// set the pointer back to start of file
rewind($fh);

//use the buffer and put something else in it

//writing to the file
fwrite($fh, $buffer);

//close the file
fclose($fh);
Note : if you want to open a binary file safely, you need to add b in the mode (fopen($filename,"rb")) )

List files in a directory

Reading files in a directory is also very easy.

Example of list files in a directory :
$handle=opendir(`/full/path/to/directory/`);
echo "Directory handle: $handle";
echo "Files:";

  while($file = readdir($handle))
  {
	echo "$file";
  }

  closedir($handle); 

 

TOP

Latest script:

 

Books: