PHP File Functions

As always, is the reference source.

Reading the Contents of a Directory

The function scandir('directoryName') returns an array, each term of which consists of one filename.

echo "Contents of Directory $directory
"; $folder=scandir($directory); foreach($folder as $var){ echo($var); echo'<br>'; } ?>

Light Bulb

Copy a File


Determining Properties of Files

filesize('filename') returns file size in bytes.


Reading the Contents of a File -- The Easy Way

Since PHP 5, files may be opened and read with the
function. The function returns an array, each item of which corresponds to one line of the file.

echo"Contents of file $fileToRead <br>";
 foreach($content as $var){ 
  echo($var);  echo'<br>';

Light Bulb

Reading and Writing to Files -- The Hard Way

Step One -- Open the File

Files may be opened for reading or writing with the
fopen('filename', 'mode')
function. This function returns a resource, which points to the opened file.

Possible modes

ModeDescriptionFile Pointer Position
'r' Open file for reading beginning
'r+' Open file for reading and writing beginning
'w' Open or create file for writing beginning
'w+' Open or create file for writing and readingbeginning
'a' Open or create file for writing end
'a+' Open or create file for writing and reading end
Step 2 -- Read from or Write to the File

fwrite(resource, 'string',[length])

Line breaks for writing to files.

SystemLine Break Character(s)
Unix \n
Step 3 -- Close the File

Open files must be closed, to flush the writing buffer, and to make them usable to other processes. fclose(resource)
returns true on success. Important to check this.

Example -- Writing to a File
$filestring='A tisket, a tasket,
    a green and yellow basket.';
$handle = fopen($filename, 'w');
  if ($handle) echo"File Opened<br>";
fwrite($handle, $filestring);
$ok= fclose($handle);
  if ($ok) echo"File Closed";

Light Bulb

Using PHP to Create and Send non Html Files to the Browser

The type of file that PHP sends to the browser is, by default, html. However files of other mime types can be sent. This is accomplished by using the
function to designate the mime type.

Images and image files can be generated with PHP. This is explained in the section on PHP Image Functions