Xử lý tập tin và thư mục

 1 -Kiểm tra một tập tin có tồn tại hay không chúng ta sử dụng hàm file_exists()

<?php
     echo file_exists('zendvn.txt') ? "File exists" : "File does not exist";
?>

 2- Lấy thông tin chi tiết của một tập tin nào đó

Câu hỏi: Khi bạn muốn lấy thông tin chi tiết của một tập tin nào đó (ví dụ như lấy kích thước, kiểu tập tin...)
Giải pháp: Chúng ta sẽ sử dụng một số hàm stat(), filesize(), or filetype() để giải quyết vấn đề
 

<?php
$file = "dummy.txt";

$info = stat($file);
print_r($info);

$type = filetype($file);
echo "File type is $typen";

$size = filesize($file);
echo "File size is $size bytesn";

echo is_readable($file) ? "File is readablen" : "File is not readablen";

echo is_writable($file) ? "File is writablen" : "File is not writablen";

echo is_executable($file) ? "File is executablen": "File is not executablen";
?>

 3. Đưa nội dung của một tập tin vào mảng hoặc chuỗi

Câu hỏi: Làm sao đưa nội dung của một tập tin ở localhost hay ở một website nào đó vào mảng hoặc vào chuỗi
Giải phảp: Để làm được này chúng ta dùng hàm file_get_contents() hoặc file()
 

<?php
// thiet lap duong dan den tap tin
$file = "http://www.zend.vn/framework.txt";

// doc file va dua  noi dung vao mang
$dataArr = file($file);
print_r($dataArr);

// doc file va dua noi dung vao chuoi
$dataStr = file_get_contents($file);
echo $dataStr;
?>

 4. Đọc từng dòng của một tập tin

<?php
// doc noi dung tap tin vao mang
$data = file('fortunes.txt') or die("Cannot read file");

// in ra dong thu nhat
echo $data[0] . "n";

// in ra dong cuoi cung
echo end($data) . "n";

// in ra dong thu 5
echo $data[4] . "n";

// in ra dong 2 den thu 6
$lines = array_slice($data, 1, 5);
echo implode("n", $lines);
?>

5. Đếm số dòng, số từ và số chữ trong một tập tin

<?php
// thiet lap duong dan den tap tin
$file = "dummy.txt";

// doc noi dung tap tin va dua vao chuoi
$str = file_get_contents($file) or die ("Cannot read from file");

// doc noi dung cua tap tin va dua vao mang
$arr = file ($file) or die ("Cannot read from file");

// Dem so dong co trong tap tin
echo "Counted ". sizeof($arr) . " line(s).n";

// Dem so chu co trong tap tin, ke ca khoang trang
$numCharsSpaces = strlen($str);
echo "Counted $numCharsSpaces character(s) with spaces.n";

// Dem so chu co trong tam tin, khong co khoang trang
$newStr = ereg_replace('[[:space:]]+', '', $str);
$numChars = strlen($newStr); 
echo "Counted $numChars character(s) without spaces.n";

// Dem so tu co trong tap tin
$numWords = str_word_count($str);
echo "Counted $numWords words.n";
?>

 6.Đưa một chuỗi vào tập tin

<?php
// Tao mot chuoi mac dinh
$data = "Ở đâu có ước mơ rnỞ đó có con đường";

// Ghi chuỗi vào tập tin
file_put_contents('danhngon.txt', $data) or die("Cannot write to file"); 

echo "File successfully written.";

?>

7. Xóa một dòng trong tập tin

<?php

// Khai bao ten tap tin
$file = "fortunes.txt";

// Dua noi dung cua tap tin vao mang
$data = file($file) or die("Cannot read file");

// Xoa dong can xoa (vi du: dong so 3)
unset ($data[2]);

// thiet lap lai chi so cua mang
$data = array_values($data);

// dua noi dung con lai vao tap tin
file_put_contents($file, implode($data)) or die("Cannot write to file");
echo "File successfully written.";
?>

8. In ra các tập tin trong một thu mục

<?php
// Khai bao ten va duong dan thu muc
$dir = './test';

// Lay noi dung trong thu muc dua vao mot mang
$fileList = scandir($dir) or die ("Not a directory");

// In ra ten va kich thuoc tap tin
foreach ($fileList as $file) {
    if (is_file("$dir/$file") && $file != '.' && $file != '..') {
        echo "$file: " . filesize("$dir/$file") . "n";
    }
}
?>

9.In ra được cấu trúc thư mục (kể cả những thư mục con)

<pre>
<?php
// Ham de qui
function printTree($dir, $depth=0) {
    // Kiem tra tham so truyen vao
    if (!is_dir($dir)) { die("Argument is not a directory!")
    // Mo thu muc can xu ly
    $dh = opendir($dir) or die ("Cannot open directory");
    // tao vong lap in ra tat ca cac tap tin trong thu muc 
    while (($file = readdir($dh)) !== false)  {
        if ($file != "." && $file != "..") {
            if (is_dir("$dir/$file")) {
                echo str_repeat("  ", $depth) . " [$file]n"
                printTree("$dir/$file", ($depth+1));
            } else     {
                echo str_repeat("  ", $depth) . " $filen";
            }
        }
    }
}
// goi ham de qui de in ra cau truc thu muc va tap tin 
printTree('./test/');
?>
</pre>

10.Copy tập tin từ thư mục này đến thư mục khác

<?php
// Khai bao thu muc chua tap tin can chep
$source = "test/dummy.txt";

//Khai bao thu muc se chep tap tin dummy.txt vao
$destination = "test2/dummy.txt";

// Sao chep tap tin neu tap tin ton tai
if (file_exists($source)) {
    copy ($source, $destination) or die ("Cannot copy file '$source'");
    echo "File successfully copied.";
} else {
    die ("Cannot find file '$source'");
}
?>