chmod
C:\wamp\www
have no business in C:\
php.ini
the open_basedir
setting limits thiswarning: file_get_contents() [function.file-get-contents]: open_basedir restriction in effect. File(/tmp/../a) is not within the allowed path(s): (/home/:/usr/lib/php:/usr/local/lib/php:/tmp) in /home/public_html/test.php on line 14.
php.ini
the post_max_size
and upload_max_filesize
settings limit this
post_max_size
limits the size of a POST request, including files
upload_max_filesize
limits the size of an uploaded file
DIRECTORY_SEPARATOR
is a predefined constant containing the directory separator
\
on Windows, /
on *nix/
works fine on Windows too./
= current working directory (*)
$myBaseDir = './';
__FILE__
= The full path and filename of the PHP file.
$myBaseDir = dirname(__FILE__);
__DIR__
= The full path of the PHP file.
$myBaseDir = __DIR__;
__DIR__
fopen()
— Opens file or URL, returns a file pointer on successfread()
— Binary-safe file readfwrite()
— Binary-safe file writefgets()
— Gets line from file pointerfseek()
— Seeks on a file pointerfeof()
— Tests for end-of-file on a file pointerrewind()
— Rewind the position of a file pointerfclose()
— Closes an open file pointer<?php
// path to file (relative from this PHP file)
$filename = __DIR__ . '/testfile.txt';
// open the file in read mode
$handle = fopen($filename, 'r');
// file was opened, read in the contents
if ($handle) {
$contents = fread($handle, filesize($filename));
} else { // file not opened
$contents = 'Error while opening file!';
}
// close the filehandle
fclose($handle);
// output the fetched contents
echo $contents;
// EOF
<?php
$handle = fopen(__DIR__ . '/testfile.txt', 'r');
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 20);
echo $buffer . '<br />' . PHP_EOL;
}
fclose($handle);
}
// EOF
file()
<?php
$lines = file(__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
echo file_get_contents(__DIR__ . '/testfile.txt');
fopen()
and a few other functions
file_put_contents()
<?php
file_put_contents(__DIR__ . '/testfile2.txt', 'hello!' . PHP_EOL);
file_put_contents()
with a flag
<?php
file_put_contents(
__DIR__ . '/testfile2.txt',
'hello!' . PHP_EOL,
FILE_APPEND
);
<?php
$filename = __DIR__ . '/testfile.txt';
echo '<p>The file ' . $filename . (file_exists($filename) ? 'exists' : 'does not exist') . '</p>' . PHP_EOL;
echo '<p>The file ' . $filename . ' was last modified on ' . date('Y-m-d H:i:s', filemtime($filename)) . '</p>' . PHP_EOL;
echo '<p>The file ' . $filename . ' is ' . (is_dir($filename) ? '' : 'not') . ' a directory</p>' . PHP_EOL;
echo '<p>The file ' . $filename . ' is ' . (is_file($filename) ? '' : 'not') . ' a file</p>' . PHP_EOL;
echo '<p>The file ' . $filename . ' is ' . (is_link($filename) ? '' : 'not') . ' a shortcut</p>' . PHP_EOL;
<?php
// Copy file
copy(__DIR__ . '/testfile.txt', __DIR__ . '/copiedfile.txt');
// Rename file
// @note if the path differs you can move a file with this function!
rename(__DIR__ . '/copiedfile.txt', __DIR__ . '/testfile2.txt');
// Delete file
unlink(__DIR__ . '/testfile2.txt');
<?php
$myBaseDir = __DIR__;
$dp = opendir($myBaseDir);
// read base directory
while (($file = readdir($dp)) !== false) {
// exclude . and ..
if ($file == '.') continue;
if ($file == '..') continue;
// we don't want directories
if (is_dir($myBaseDir . '/' . $file)) continue;
// output the filename
echo $file . '<br />' . PHP_EOL;
}
// close base directory pointer
closedir($dp);
@
and stop the process when neccessary
<?php
$myBaseDir = __DIR__;
$dp = @opendir($myBaseDir) or die('Error reading ' . $myBaseDir);
...
SPLFileInfo
class, an object oriented interface to information for an individual file (phpdocs)SplFileObject
class — which extends SPLFileInfo
— an object oriented interface for an individual file (phpdocs)→ Instead of using the oldskool functions, create an instance of this class and access the datamembers/ functions on it
<?php
$filename = __DIR__ . '/testfile.txt';
$fi = new SplFileInfo($filename);
echo '<p>The file ' . $fi->getFileName() . ' was last modified on ' . date('Y-m-d H:i:s', $fi->getMTime()) . '</p>' . PHP_EOL;
echo '<p>The file ' . $fi->getFileName() . ' is ' . ($fi->isDir() ? '' : 'not') . ' a directory</p>' . PHP_EOL;
echo '<p>The file ' . $fi->getFileName() . ' is ' . ($fi->isFile() ? '' : 'not') . ' a file</p>' . PHP_EOL;
echo '<p>The file ' . $fi->getFileName() . ' is ' . ($fi->isLink() ? '' : 'not') . ' a shortcut</p>' . PHP_EOL;
// EOF
<?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
SplFileObject
: it's line-oriented
SplFileObject
-version of file_get_contents()
DirectoryIterator
class — which extends SPLFileInfo
(!) — a simple interface for viewing the contents of filesystem directories (phpdocs)<?php
$myBaseDir = __DIR__;
$di = new DirectoryIterator($myBaseDir);
foreach ($di as $file) {
// exclude . and .. + we don't want directories
if (!$file->isDot() && !$file->isDir()) {
echo $file . '<br />' . PHP_EOL;
}
}
// EOF
Exception
<?php
$di = new DirectoryIterator('/this/path/does/not/exist');
// EOF
try
/catch
to properly handle it
<?php
try {
$di = new DirectoryIterator('/this/path/does/not/exist');
} catch (Exception $e) {
echo 'There was an error: <br />' . $e->getMessage();
}
// EOF
DirectoryIterator
SplFileInfo
and SplFileObject
SplFileObject
unlink()
copy()
rename()
file_get_contents()
and file_put_contents()
move_uploaded_file()
$_FILES
containing that temp location per 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>
files/
files/photoalbums/1
and files/photoalbums/2
1.jpg
, 2.jpg
, etc..php
file, right?A code-only summary of this chapter is available at 05.files.and.folders.summary.html