View Category

Read the contents of a file into a string

php
$file_contents = file_get_contents("file.txt");

Process a file one line at a time

Open the source file to your solution and print each line in the file, prefixed by the line number, like:
1> First line of file
2> Second line of file
3> Third line of file
php
$lines = file('file.txt');
foreach ($lines as $lnum => $line) {
echo $line_num."> ".$line; // you may want to add a <br />\n
}
<?php
$lines = new SplFileObject('file.txt');
foreach ($lines as $line) {
echo $line;
}
?>

Write a string to a file

php
/****
* For some (security)reason I couldn't
* submit this without adding a space to
* the functionnames. Please remove it :)
****/

if ($fh = f open("file.txt", 'w')) {
f write($fh, "Some text\n");
f close($fh);
}
<?php
file_put_contents('file.txt', 'a string');
?>

Append to a file

php
<?php
if ($fh = fopen("file.txt", 'a')) { // a == append
fwrite($fh, "Append some text\n");
fclose($fh);
}
?>
<?php
file_put_contents('file.txt', 'a string to append', FILE_APPEND);
?>

Process each file in a directory

php
if ($dh = opendir($dir)) { // if we have access
while (($file = readdir($dh)) !== false) { // as long as there is a file
echo "name: $file\n"; // echo its name
}
closedir($dh); // close the dir
}

Process each file in a directory recursively

php

if ($dir_handle = opendir($dir))
list_dir($dir_handle);

function list_dir($dh) {
// as long as we can read the dir
while (($file = readdir($dh)) !== false) {
// if it's a dir and it's not the current dir nor the above dir
if (is_dir($file) && $file != '.' && $file !='..') {
// open the dir, print it's name and all files inside
$handle = opendir($file);
echo $file."\n";
list_dir($handle);
// if it's a simple file
} else if ($file != '.' && $file !='..') {
// type it's name
echo $file."\n";
}
}
closedir($dir_handle); // close the dirs
}