PHP/File Directory/Directory
Содержание
- 1 Calculate the size for a directory
- 2 Clean Path by Regular Expressions
- 3 Print all files under a directory
- 4 readdir: Read entry from directory handle
- 5 Reading Contents from a Directory
- 6 Read the content from a directory
- 7 scandir: List files and directories inside the specified path
- 8 The current working directory
Calculate the size for a directory
<source lang="html4strict">
<?php
function directory_size($directory) { $directorySize=0; if ($dh = @opendir($directory)) { while (($filename = readdir ($dh))) { if ($filename != "." && $filename != "..") { if (is_file($directory."/".$filename)){ $directorySize += filesize($directory."/".$filename); } if (is_dir($directory."/".$filename)){ $directorySize += directory_size($directory."/".$filename); } } } } @closedir($dh); return $directorySize; } $directory = "./"; $totalSize = round((directory_size($directory) / 1024), 2); echo "Directory $directory: ".$totalSize. "kb.";
?>
</source>
Clean Path by Regular Expressions
<source lang="html4strict">
<html> <body> <?php if (isset($_POST["posted"])) {
$path = $_POST["path"]; $outpath = ereg_replace("\.[\.]+", "", $path); $outpath = ereg_replace("^[\/]+", "", $outpath); $outpath = ereg_replace("^[A-Za-z][:\|][\/]?", "", $outpath); echo "The old path is " . $path . " and the new path is " . $outpath;
} ?> <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST"> <input type="hidden" name="posted" value="true"> Enter your file path for cleaning: <input type="text" name="path" size="30"> <input type="submit" value="Clean"> </form> </body> </html>
</source>
Print all files under a directory
<source lang="html4strict">
<?php $dirname = "."; $dh = opendir($dirname) or die("couldn"t open directory"); while (!(($file = readdir($dh)) === false ) ) {
if (is_dir("$dirname/$file")) { echo "(D) "; } echo $file."
";
} closedir($dh); ?>
</source>
readdir: Read entry from directory handle
<source lang="html4strict">
<?php
$dh = opendir("./"); while ($file = readdir($dh)) echo "$file
"; closedir($dh);
?>
</source>
Reading Contents from a Directory
<source lang="html4strict">
<?php if (file_exists ("./")) { if (is_dir ("./")) { $dh = opendir ("./") or die (" Directory Open failed !"); while ($file = readdir ($dh)) { echo "$file\n"; } echo "Directory was opened successfully"; Closedir ($dh); } } ?> </source>
Read the content from a directory
<source lang="html4strict">
<?php
$dir = opendir("./"); while ($read_file = readdir($dir)) { echo "$read_file", "\n"; } closedir($dir);
?>
</source>
scandir: List files and directories inside the specified path
<source lang="html4strict">
<?php
print_r(scandir("./"));
?>
</source>
The current working directory
<source lang="html4strict">
<?php
$working_dir = getcwd(); echo "The current working directory is: $working_dir ", "\n";
?>
</source>