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
<?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.";
?>
Clean Path by Regular Expressions
<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>
Print all files under a directory
<?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."<br/>";
}
closedir($dh);
?>
readdir: Read entry from directory handle
<?php
$dh = opendir("./");
while ($file = readdir($dh))
echo "$file <br>";
closedir($dh);
?>
Reading Contents from a Directory
<?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);
}
}
?>
Read the content from a directory
<?php
$dir = opendir("./");
while ($read_file = readdir($dir)) {
echo "$read_file", "\n";
}
closedir($dir);
?>
scandir: List files and directories inside the specified path
<?php
print_r(scandir("./"));
?>
The current working directory
<?php
$working_dir = getcwd();
echo "The current working directory is: $working_dir ", "\n";
?>