Basic File Functions in PHP

file_exists( ) file_size( ) basename( ) fopen( ) fclose( )

File_Exists( )

  • Use the file_exists( ) function to determine whether or not a file exists.
  • Returns true if it does exist; false if not

_________________________________________________________________________________________

Example

_________________________________________________________________________________________

<?php


$filename = "practice6.txt";


if (file_exists($filename))

{

echo "The file $filename exists";

}

else

{

echo "$filename does not exist";

}

?>

Filesize( )

  • Use the filesize( ) function to determine the size of a file.
  • Returns in bytes; false if error

____________________________________________________________________________

Example

____________________________________________________________________________


<?php


$filename = "practice6.txt";


echo $filename .':'.filesize($filename) . 'bytes';


?>

basename( )

  • separates a file from its directory path


_______________________________________________________________________

Example

_______________________________________________________________________


$filename = basename("/home/Emily/documents/practice6.txt");

Opening a File: fopen( )

  • To work with a file in your PHP script, you usually need to open it first.
  • When you open a file, a file handle is created.
  • A file handle points to the location of the file you want to access.
  • The handle is removed when you close the file.
  • The first argument = file name; Second argument = how you want to use it (r, r+, w, etc)

_______________________________________________________________________________

Example

_______________________________________________________________________________


<?php


$handle=fopen("practice6.txt", "w+") or exit ("Unable to open file!");


?>

Closing a File: fclose( )

  • Once you're finished working with a file, you need to close it.
  • PHP should automatically do this, but it's best to do it manually as well.

_____________________________________________________________________________________

Example

_____________________________________________________________________________________


fclose($handle);