PHP Cheat Sheet: File Handling

1. Checking Whether a File Exists:

if (file_exists("testfile.txt")) echo "File exists";

2. Reading from Files:

Method 1: Using fgets() to read one line a time:

$fh = fopen("testfile.txt", 'r') or die("Cannot open file.");
while (!feof($fh)) {
    $line = fgets($fh);
    $out .= $line;
}

fclose($fh);

Method 2: Using file_get_contents() to read the entire content:

$userfile= file_get_contents('users.txt');

3. Writing Files:

Method 1: Using fwrite():

// Regular writing, no locking.
$fh = fopen("testfile.txt", 'w') or die("Failed to create file");
fwrite($fh, $text) or die("Could not write to file");
fclose($fh);

// Writing with locking
$fh = fopen("testfile.txt", 'w') or die("Failed to create file");
flock($fh, LOCK_EX) or die("Cannot lock file");
fwrite($fh, $text) or die("Cannot not write to file");
flock($fh, LOCK_UN) or die ("Cannot unlock file");
fclose($fh);

// File append
$fh = fopen("testfile.txt", 'a') or die("Failed to create file");
fwrite($fh, $text) or die("Could not write to file");
fclose($fh); 

Method 2: Using file_put_contents():

// No appending
file_put_contents('output.txt', $data) or die("Cannot write file");

// File append
file_put_contents('output.txt', $data, FILE_APPEND) or die("Cannot write file");

4. Determining a File’s Last Modified Time:

echo "File last updated: ".date("m-d-y g:i:sa", filemtime($file));

5. Determining a File’s Size:

$bytes = filesize($file);
$kilobytes = round($bytes/1024, 2);


 

To top