PHP File Functions

As always, php.net 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.

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

Light Bulb

Copy a File

copy('sourceFilename','destinationFilename')

Determining Properties of Files

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

is_writeable('filename')
is_readable('filename')
file_exists('filename')

Reading the Contents of a File -- The Easy Way

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

<?php
$fileToRead="bitOfBreath.txt"; 
echo"Contents of file $fileToRead <br>";
$content=file($fileToRead);
 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
Windows\r\n
Mac\r
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
<?php
$filename='../test/tisket.txt';
$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
header()
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