PHP: Files and Folders

This page forms the code summary of 05.files.and.folders.html, part of the Webscripting1 — Serverside Webscripting course, part of the Professional Bachelor ICT study programme, taught at Odisee, Ghent, Belgium. The materials and this summary were developed by Bram(us) Van Damme, lecturer ICT at Odisee, who blogs over at bram.us and Twitters as @bramus. The materials and this summary may be used freely, as long as credit to Bramus is present and a clear an upfront link to ikdoeict.be remains in place. Suggestions and additions may be mailed to Bramus, or sent via a pull request on GitHub.

File and Folder Operations

Loop a directory using DirectoryIterator

<?php

    $myBaseDir = __DIR__;
    try {
        $di = new DirectoryIterator($myBaseDir);
    } catch (Exception $e) {
        echo 'There was an error: ' . $e->getMessage();
    }

    foreach ($di as $file) {
        // exclude . and .. + we don't want directories
        if (!$file->isDot() && !$file->isDir()) {
            echo $file . '<br />' . PHP_EOL;
        }
    }

// EOF

Fetch file info using SplFileInfo

<?php

    $filename = __DIR__ . '/testfile.txt';
    $fi = new SplFileInfo($filename);

    echo 'The file ' . $fi->getFileName() . ' was last modified on ' . date('Y-m-d H:i:s', $fi->getMTime()) . PHP_EOL;

    echo 'The file ' . $fi->getFileName() . ' is ' . ($fi->isDir() ? '' : 'not') . ' a directory' . PHP_EOL;

    echo 'The file ' . $fi->getFileName() . ' is ' . ($fi->isFile() ? '' : 'not') . ' a file' . PHP_EOL;

    echo 'The file ' . $fi->getFileName() . ' is ' . ($fi->isLink() ? '' : 'not') . ' a shortcut' . PHP_EOL;

// EOF

Delete a file using unlink()

<?php

	unlink(__DIR__ . '/testfile2.txt');

// EOF

Copy a file using copy()

<?php

	copy(__DIR__ . '/testfile.txt', __DIR__ . '/copiedfile.txt');

// EOF

Rename or move a file using rename()

<?php

	rename(__DIR__ . '/copiedfile.txt', __DIR__ . '/testfile2.txt');

// EOF

Reading File Contents

Use SplFileObject to read a file line by line

<?php

    $lines = new SPLFileObject(__DIR__ . '/testfile.txt');

    // Loop through our array, show line and line numbers too.
    foreach ($lines as $line_num => $line) {
        echo '<strong>#' . $line_num . ':</strong> ' . $line . '<br />' . PHP_EOL;
    }

// EOF

Use file_get_contents() to read a file entirely

<?php

    echo file_get_contents(__DIR__ . '/testfile.txt');

// EOF

Writing File Contents

Use file_put_contents() to overwrite the entire contents of a file

<?php

    echo file_put_contents(__DIR__ . '/testfile2.txt', 'hello!' . PHP_EOL);

// EOF

Use file_put_contents() with the FILE_APPEND flag to add content at the end of a file

<?php

    file_put_contents(__DIR__ . '/testfile2.txt', 'hello!' . PHP_EOL, FILE_APPEND);

// EOF

Handling file uploads

Find info about the uploaded files in the superglobal $_FILES

Given you've just uploaded a file using an input named avatar

<?php

	var_dump($_FILES);

// EOF
array(1) {
	'avatar' =>
	 array(3) {
		'name' =>
		string(8) "test.jpg"
		'tmp_name' =>
		string(15) "/tmp/1234567890"
		'size' =>
		string(3) "560"
	}
}

Move the file after upload to its final location using move_uploaded_file()

<php

	if (isset($_FILES['avatar'])) {

		echo '<p>Uploaded file: ' . $_FILES['avatar']['name'] . '</p>';
		echo '<p>Temp location: ' . $_FILES['avatar']['tmp_name'] . '</p>';
		echo '<p>Size: ' . $_FILES['avatar']['size'] . '</p>';

		if (!in_array((new SplFileInfo($_FILES['avatar']['name']))->getExtension(), array('jpeg', 'jpg', 'png', 'gif'))) {
			exit('<p>Invalid extension. Only .jpeg, .jpg, .png or .gif allowed</p>');
		}

		@move_uploaded_file($_FILES['avatar']['tmp_name'], __DIR__ . DIRECTORY_SEPARATOR . $_FILES['avatar']['name'])
		or die('<p>Error while saving file in the uploads folder</p>');

		echo '<p><img src=' . $_FILES['avatar']['name'] . ' alt="" /><p>';
	}

?>

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
    <input type="file" name="avatar" id="avatar" /><input type="submit" />
</form>