--------------- <> -----------------
--- KHOA HỌC - CÔNG NGHỆ - GIÁO DỤC - VIỆC LÀM ---
--- Học để đi cùng bà con trên thế giới ---

Tìm kiếm trong Blog

Ngu ngơ học làm web (81) - Kỹ thuật đệ quy 1

Tiếp theo của: Ngu ngơ học làm web (80) - Bài tập xử lý tập tin 2
-----

Phần 81.       Kĩ thuật đệ quy 1


Đây là clip số 87:


Đệ quy (recursive): là sự lặp lại chính nó.

Hàm đệ quy là hàm gọi lại chính nó, lồng nhau liên tục, cho tới khi gặp điều kiện dừng.

function myFunction ($param1, $param2) {
    if ($param1 == $param2) { // điều kiện dừng hàm
      // trả về giá trị - kết thúc hàm
    } else {
      // gọi lại hàm myFunction ($param1, $param2)
    }
  }

Ví dụ, viết hàm tính n!

Với cách viết thông thường:

function giaiThua($n) {
    $result = 1;
    if ($n == 0 || $n == 1) {
      return $result;
    } else {
      for ($i = 2; $i <= $n; $i++) {
        $result = $result * $i;
      }
      return $result;
    }
  }

Viết lại theo kiểu đệ quy:

  function giaiThua($n) {
    $result = 1;
    if ($n == 0 || $n == 1) {
      return $result;
    } else {
      $result = $n * giaiThua($n - 1);
    }
    return $result;
  }

Hàm tính tổng từ 0 đến n, viết theo kiểu đệ quy:

  function tinhTong($n) {
    $result = 0;
    if ($n == 0) {
      return 0;
    } else {
      $result = $n + tinhTong($n -1);
    }
    return $result;
  }

Đây là clip số 88:


Sử dụng hàm đệ quy để tạo menu đa cấp.

Cho một menu đa cấp, lưu dưới dạng mảng như sau:

  $menu = array();
  $menu[] = array('id' => 1, 'name' => 'Home', 'parent' => 0);
  $menu[] = array('id' => 2, 'name' => 'About', 'parent' => 0);
  $menu[] = array('id' => 3, 'name' => 'News', 'parent' => 0);
  $menu[] = array('id' => 4, 'name' => 'Products', 'parent' => 0);
  $menu[] = array('id' => 5, 'name' => 'Contact', 'parent' => 0);
  $menu[] = array('id' => 6, 'name' => 'Tin trong nước', 'parent' => 3);
  $menu[] = array('id' => 7, 'name' => 'Tin quốc tế', 'parent' => 3);
  $menu[] = array('id' => 8, 'name' => 'Công nghệ', 'parent' => 6);
  $menu[] = array('id' => 9, 'name' => 'Giáo dục', 'parent' => 6);
  $menu[] = array('id' => 10, 'name' => 'Y tế', 'parent' => 6);
  $menu[] = array('id' => 11, 'name' => 'Education', 'parent' => 7);
  $menu[] = array('id' => 12, 'name' => 'Breaking news', 'parent' => 7);
  $menu[] = array('id' => 13, 'name' => 'Software', 'parent' => 4);

Mảng $menu gồm 13 phần tử, mỗi phần tử chứa ba thông tin, một là “id”, hai là “name” và ba là “id của menu mức cha nó”.

Việc tiếp theo là thêm thông tin về cấp của menu vào mỗi phần tử của mảng, để được kết quả như sau:

  $menu1 = array();
  $menu1[] = array('id' => 1, 'name' => 'Home', 'parents' => 0, 'level' => 1);
  $menu1[] = array('id' => 2, 'name' => 'About', 'parents' => 0, 'level' => 1);
  $menu1[] = array('id' => 3, 'name' => 'News', 'parents' => 0, 'level' => 1);
  $menu1[] = array('id' => 4, 'name' => 'Products', 'parents' => 0, 'level' => 1);
  $menu1[] = array('id' => 5, 'name' => 'Contact', 'parents' => 0, 'level' => 1);
  $menu1[] = array('id' => 6, 'name' => 'Tin trong nước', 'parents' => 3, 'level' => 2);
  $menu1[] = array('id' => 7, 'name' => 'Tin quốc tế', 'parents' => 3, 'level' => 2);
  $menu1[] = array('id' => 8, 'name' => 'Công nghệ', 'parents' => 6, 'level' => 3);
  $menu1[] = array('id' => 9, 'name' => 'Giáo dục', 'parents' => 6, 'level' => 3);
  $menu1[] = array('id' => 10, 'name' => 'Y tế', 'parents' => 6, 'level' => 3);
  $menu1[] = array('id' => 11, 'name' => 'Education', 'parents' => 7, 'level' => 3);
  $menu1[] = array('id' => 12, 'name' => 'Breaking news', 'parents' => 7, 'level' => 3);
  $menu1[] = array('id' => 13, 'name' => 'Software', 'parents' => 4, 'level' => 2);

Sau đó, sắp xếp lại mảng để các phần từ có mối liên hệ cha-con thì đặt cạnh nhau:

  $menu1 = array();
  $menu1[] = array('id' => 1, 'name' => 'Home', 'parent' => 0, 'level' => 1);
  $menu1[] = array('id' => 2, 'name' => 'About', 'parent' => 0, 'level' => 1);
  $menu1[] = array('id' => 3, 'name' => 'News', 'parent' => 0, 'level' => 1);
  $menu1[] = array('id' => 6, 'name' => 'Tin trong nước', 'parent' => 3, 'level' => 2);
  $menu1[] = array('id' => 8, 'name' => 'Công nghệ', 'parent' => 6, 'level' => 3);
  $menu1[] = array('id' => 9, 'name' => 'Giáo dục', 'parent' => 6, 'level' => 3);
  $menu1[] = array('id' => 10, 'name' => 'Y tế', 'parent' => 6, 'level' => 3);
  $menu1[] = array('id' => 7, 'name' => 'Tin quốc tế', 'parent' => 3, 'level' => 2);
  $menu1[] = array('id' => 11, 'name' => 'Education', 'parent' => 7, 'level' => 3);
  $menu1[] = array('id' => 12, 'name' => 'Breaking news', 'parent' => 7, 'level' => 3);
  $menu1[] = array('id' => 4, 'name' => 'Products', 'parent' => 0, 'level' => 1);
  $menu1[] = array('id' => 13, 'name' => 'Software', 'parent' => 4, 'level' => 2);
  $menu1[] = array('id' => 5, 'name' => 'Contact', 'parent' => 0, 'level' => 1);

Đây là clip số 89:


Đoạn mã thực hiện yêu cầu ở trên (không dùng kĩ thuật đệ quy):

  foreach ($menu as $key => $value) {
    if ($value['parent'] == 0) {
      $value['level'] = 1;
      $menu1[] = $value;
      unset($menu[$key]);

      $parent = $value['id'];
      foreach ($menu as $key1 => $value1) {
        if ($value1['parent'] == $parent) {
          $value1['level'] = $value['level'] + 1;
          $menu1[] = $value1;
          unset($menu[$key1]);

          $parent1 = $value1['id'];
          foreach ($menu as $key2 => $value2) {
            if ($value2['parent'] == $parent1) {
              $value2['level'] = $value1['level'] + 1;
              $menu1[] = $value2;
              unset($menu[$key2]);
            }
          }
        }
      }
    }
  }

// xuất menu
  foreach ($menu1 as $key => $value) {
    if ($value['level'] == 1) {
      echo '<div style="border: 1px solid #ccc;">+' . $value['name'] . '</div>';
    } else {
      $padding = ($value['level'] - 1) * 20;
      $padding = 'padding-left:' . $padding . 'px';
      echo '<div style="border: 1px solid #ccc;'. $padding . '">-' . $value['name'] . '</div>';
    }
  }

Viết lại đoạn mã ở trên (có dùng kĩ thuật đệ quy):

function deQuyLevel($array, $parent, $level, &$newArray) {
    // điều kiện dừng
    if (count($array) > 0) {
      foreach ($array as $key => $value) {
        if ($value['parent'] == $parent) {
          $value['level'] = $level;
          $newArray[] = $value;
          unset($array[$key]);
          $newParent = $value['id'];
          deQuyLevel($array, $newParent, $level + 1, $newArray);
        }
      }
    }
  }
  $menu1 = array();

  deQuyLevel($menu, 0, 1, $menu1);
-----------
Cập nhật [16/9/2020]
-----------
Xem thêm:

Tiếng Anh chuyên ngành Công nghệ Thông tin (4) - The computer (hết)

Tiếp theo của: Tiếng Anh chuyên ngành Công nghệ Thông tin (3) - The computer (tiếp)
------

1.1        Học nói – Chào hỏi bằng tiếng Anh

1.1.1        Một vài gợi ý để học nói

– Kỹ năng nghe và nói luôn luôn song hành với nhau, nên học hai cái cùng nhau

– Mạnh dạn gặp gỡ và nói chuyện

– Luôn tôn trọng, và chân thành với mọi người

– Luôn quan sát tình huống, quan sát người khác để học hỏi qua các buổi gặp gỡ, làm việc

– Nhờ đối tác chỉ lại cho mình

1.1.2        Một số câu dùng để chào hỏi

 Tiếng Anh

Nghĩa

Đáp lại

Hello, hello there

Xin chào

 

Hi, Hi all, Hi everyone, Hey,

Chào (thân mật)

 

Good morning

Chào buổi sáng

 

Good afternoon

Chào buổi chiều (sau 12 giờ trưa tới trước khi trời tối, khoảng 5 giờ chiều)

 

Good evening

Chào buổi tối (từ khi trời tối tới khuya, khoảng sau 5 giờ chiều tới khuya)

 

Nice to meet you

Rất vui được gặp bạn

 

Nice to meet you here

Rất vui được gặp bạn ở đây

 

Happy to meet you again

Rất vui được gặp lại bạn

 

It’s good to see you

Thật tốt khi được gặp bạn

 

Long time no see

Lâu rồi không gặp (thân mật)

 

How’s it going?

Dạo này sao rồi?

 

It’s a pleasure to meet you

Hân hạnh được gặp bạn

 

What have you been up to?

Dạo này bạn như thế nào?

 

How are you?

Bạn khỏe  không?

 

How are you doing?

Bạn dạo này thế nào?

I’m doing well. I’m doing great. I’m happy. How about you.

Not so good. Not so well.

How are you today?

Hôm nay bạn thế nào?

 

Thanks for agreeing to meet with me

Cám ơn vì đã đồng ý gặp tôi

 

Xem: https://www.youtube.com/watch?v=0oJzdvnfHQc

Xem: https://www.youtube.com/watch?v=LhXN2X6wF1Q

Xem thêm: https://www.youtube.com/watch?v=u8yX9lhhYBM

Đọc thêm: https://www.fluentu.com/blog/english/english-greetings-expressions/

1.1.3        Bài tập

Bài tập 1. Tìm các câu đáp lại cho mỗi câu chào ở bảng trên.

1.2        Học nghe

1.2.1        Gợi ý các bước để học nghe

Với mỗi bài nghe:

– Nghe qua từ đầu đến cuối để làm quen (chưa cần hiểu nội dung của cả bài)

– Nghe để hiểu nội dung (vừa nghe vừa dõi theo văn bản–transcript đi kèm), dùng từ điển để tra nghĩa các từ mới, có thể viết lại nội dung của từng câu ra giấy

– Nghe và cảm nhận (nghe mà không cần transcript), nghe tới đâu hiểu tới đó

– Có thể thực hiện lại mỗi bước ở trên (nếu cần) cho tới khi nào bạn nghe mà hiểu được toàn bộ nội dung của bài

1.2.2        Bài tập

Bài tập 1: Dùng từ điển đọc 10 từ trong bài đọc hiểu, ghi lại các từ bạn đã nghe được.

Bài tập 2: New mobile computing devices

https://www.youtube.com/watch?v=lKTIHkDvaF4

Nghe/hoặc đọc rồi điền từ vào chỗ trống:

Search                        Partnership                Divices            Versions                     Generation                 Product            Industry         Digital             Tablet             Operating Sytem

From VOA Learning English, this is the Technology Report in Special English.

Competition in the field of mobile computing (1) ……… is increasing faster than ever. In September, many (2) ……… leaders announced new products to a market already crowded with choices. The announcements come as people start to think about the holiday gift-giving season.

Nokia and Microsoft introduced two new smartphones at a joint announcement in New York. The new devices can be charged wirelessly and have improved cameras. But they also run on the new Microsoft Windows 8 operating system. The (3)………. with Microsoft is very important to Nokia.

Nokia's chief executive told people attending the (4)……… announcement that "Nokia needed to be part of an ecosystem."

An ecosystem is the mix of software, hardware and (5)………. networks that make mobile computing devices useful. Apple has built its own operating system, which includes the cloud computing system. And Google has its Android (6)……….. So far, Apple and Google have built powerful market positions with popular smartphone and computer devices.

In May, the Internet (7)………. leader Google bought Motorola, a technology manufacturer. That led to new smartphones that run on the faster, fourth (8)………., or 4-G, high-speed communications network.

Microsoft hopes to gain market share with Windows 8, a new operating system. Windows 8 will be available in (9)………. for personal computers, smartphones and tablet computers.

Through the fall, market watchers are expecting new mobile computing devices to appear in stores. They include a new Kindle eReader and a new (10)……… computer from Microsoft.

Bài tập 3: Xem clip, học nói, nghe và ghi lại đoạn nghe ra giấy.

https://www.youtube.com/watch?v=akXGSw7H49Y

1.3        Tập viết

Các bước để viết một email đơn giản (theo web5ngay):

– Bước 1: Soạn email bằng tiếng Việt

– Bước 2: Dịch sẵn một số từ quan trọng

– Bước 3: Dùng Google translate dịch sang tiếng Anh

– Bước 4: Sử dụng website để kiểm tra lại ngữ pháp

– Bước 5: Viết lại ra giấy, email bằng tiếng Anh để học, để nhớ.

Xem thêm: https://www.youtube.com/watch?v=HzBxBtk6XB4

Ví dụ: viết email xin đi thực tập tại một công ty phần mềm.

Xin chào anh Teo Nguyen,

Em tên là Mit Le, sinh viên năm 4, chuyên ngành công nghệ phần mềm, khoa CNTT, đại học ABC.

Theo chương trình đào tạo, em sẽ đi thực tập tại một công ty vào học kỳ thứ 8.

Thời gian thực tập (dự kiến) bắt đầu vào tháng 9/2021 và kết thúc vào tháng 12/2021.

Em đã tìm hiểu về công ty, và thấy rất phù hợp với chuyên ngành em đang theo đuổi.

Lĩnh vực chuyên môn của em là web, các ngôn ngữ, công nghệ và các dự án em đã làm được ghi chi tiết trong CV em gửi kèm trong email này.

Rất mong nhận được hồi âm từ anh.

Trân trọng.

Mit Le.

Email: mitle@gmail.com

Phone: 0123456789

-------------

Đáp án

Bài tập 1. circuit, certain, signal, instruction, with, switch, data, date, day, tape

Bài tập 2. (1) devices, (2) industry, (3) partnership, (4) product,  (5) digital, (6) Operating  system, (7) search, (8) generation, (9) version, (10) tablet

[Email xin thực tập]

Bước 1: Soạn email bằng tiếng Việt

Xin chào anh Teo Nguyen,

Em tên là Mit Le, sinh viên năm 4, chuyên ngành công nghệ phần mềm, khoa CNTT, đại học ABC.

Theo chương trình đào tạo, em sẽ đi thực tập tại một công ty vào học kỳ thứ 8.

Thời gian thực tập (dự kiến) bắt đầu vào tháng 9/2021 và kết thúc vào tháng 12/2021.

Em đã tìm hiểu về công ty, và thấy rất phù hợp với chuyên ngành em đang theo đuổi.

Lĩnh vực chuyên môn của em là web, các ngôn ngữ, công nghệ và các dự án em đã làm được ghi chi tiết trong CV em gửi kèm trong email này.

Rất mong nhận được hồi âm từ anh.

Trân trọng.

Mit Le.

Email: mitle@gmail.com

Phone: 0123456789

Bước 2: Dịch các từ quan trọng

Xin chào anh Teo Nguyen,

Em tên là Mit Le, sinh viên năm 4, majoring in software engineering, khoa CNTT, đại học ABC.

Theo education program, em sẽ đi internship tại một công ty vào học kỳ thứ 8.

Internship duration (expected) bắt đầu vào tháng 9/2021 và kết thúc vào tháng 12/2021.

Em đã tìm hiểu về công ty, và thấy rất phù hợp với major em đang theo đuổi.

Lĩnh vực chuyên môn của em là web, các ngôn ngữ, công nghệ và các dự án em đã làm được ghi chi tiết trong CV em gửi kèm trong email này.

Rất mong nhận được hồi âm từ anh.

Trân trọng.

Mit Le.

Email: mitle@gmail.com

Phone: 0123456789

Bước 3: Dịch toàn bộ email sang tiếng Anh bằng Google translate

Hello Mr. Teo Nguyen,

My name is Mit Le, a 4th year student, majoring in software engineering, IT department, ABC University.

Under the education program, I will do an internship at a company in the 8th semester.

Internship duration (expected) starts in September 2021 and ends in December 2021.

I have researched about the company, and found it very suitable for the major I am pursuing.

My area of expertise is web, languages, technology and projects I have worked on are detailed in my CV attached in this email.

Looking forward to hearing from you.

Best regards.

Mit Le.

Bước 4: Kiểm tra ngữ pháp bằng website https://app.grammarly.com/

Ví dụ,



Sửa các lỗi theo gợi ý ở cửa sổ bên phải.

Bước 5: Đã được email hoàn thiện. Bạn nên viết lại email ra giấy để nhớ, và hình thành kĩ năng viết về sau. Sau này sẽ tự viết email mà không cần (hoặc rất ít) phải dùng tới sự hỗ trợ của các công cụ.

Lưu ý: Khi viết email, sẽ dùng chữ Dear (nghĩa là thưa, kính chào, mang nghĩa trân trọng) để thay chữ “Hello”. Nếu email cho người quen, bạn thân thì có thể chào là “Hi”.

Dear Mr. Teo Nguyen,

My name is Mit Le, a 4th-year student, majoring in software engineering, IT department, ABC University.

Under the education program, I will do an internship at a company in the 8th semester.

The internship duration (expected) starts in September 2021 and ends in December 2021.

I have researched about the company and found it very suitable for the major I am pursuing.

My area of expertise is web, languages, technology, and projects I have worked on are detailed in my CV attached to this email.

Looking forward to hearing from you.

Best regards.

Mit Le.

------
Video: https://www.youtube.com/watch?v=wF3_E0fSRsg&t=50s
------
Cập nhật [28/8/2021]
-----------
Xem thêm:
- Tiếng Anh chuyên ngành Công nghệ Thông tin (0) - Danh mục các bài học
- Tiếng Anh chuyên ngành Công nghệ Thông tin (5) - 

Ngu ngơ học làm web (80) - Bài tập xử lý tập tin 3

Tiếp theo của: Ngu ngơ học làm web (79) - Bài tập xử lý tập tin 2
-----

Phần 80.       Bài tập xử lý tập tin 3


Đây là clip số 86:


Bài tập 1. Khi danh sách tập tin rỗng trang web sẽ hiển thị thông báo và ẩn nút “Xóa tập tin”

[index.php]

Kiểm tra danh sách tập tin đọc được, nếu không có tập tin nào, gán biến $noFile = true.

  require_once 'functions.php';
  $data = scandir('./files');
  $noFile = false;
  if (count($data) - 2 <= 0)
  {
    $noFile = true;
  }
?>

Nếu biến $noFile mang giá trị true thì xuất câu thông báo:

    <div class="heading">QUẢN LÝ TẬP TIN</div>
    <?php
      if ($noFile) {
        echo '<p>Chưa có tập tin.</p>';
      }
    ?>

Bài tập 2. Thay đổi thông báo cho hai trường hợp: thêm tập tin mới và sửa tập tin.

Sửa lại dòng thông báo trong [edit.php]:

<?php
          if ($flag == true) {
            echo '<div class="row">Cập nhật dữ liệu thành công!</div>';
          }
        ?>

Bài tập 3. Thông báo khi web client gửi ID của một tập tin mà nó không tồn tại trên server:

Cách làm: kiểm tra việc đọc nội dung tập tin, nếu kết quả trả về là false nghĩa là tập tin đó không tồn tại, thêm dấu @ trước hàm đọc tập tin để không xuất hiện cảnh báo trong trường hợp không đọc được tập tin.

[edit.php]

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
  <script src="js/jquery.js"></script>
  <script>
    $(document).ready(function() {
      $('#btnHuy').click(function() {
        window.location = 'index.php';
      });
    });
  </script>
</head>
<body>
<?php
  require_once 'functions.php';
  $noExist = false;
  $id = $_GET['id'];
  $content = @file_get_contents('./files/' . $id . '.txt');
  if ($content == false) {
    $noExist = true;
  } else {
    $content = explode('||', $content);
    $title = $content[0];
    $description = $content[1];
    $flag = false;
    $errorTitle = '';
    $errorDescription = '';
    if (isset($_POST['title']) && isset($_POST['description'])) {
      $title = $_POST['title'];
      $description = $_POST['description'];
    // kiểm tra dữ liệu nhập vào
      if (checkEmpty($title)) {
        $errorTitle = '<p class="error">Tiêu đề không được để trống</p>';
      }
      if (checkLength($title, 5, 100)) {
        $errorTitle .= '<p class="error">Tiêu đề dài từ 5 đến 100 kí tự</p>';
      }
      if (checkEmpty($description)) {
        $errorDescription = '<p class="error">Mô tả không được để trống</p>';
      }
      if (checkLength($description, 10, 500)) {
        $errorDescription .= '<p class="error">Mô tả dài từ 10 đến 500 kí tự</p>';
      }
    // nếu dữ liệu hợp lệ
      if ($errorTitle == '' && $errorDescription == '') {
        $data = $title . '||' . $description;
        $fileName = './files/' . $id . '.txt';
        if (file_put_contents($fileName, $data)) {
          $title = '';
          $description = '';
          $flag = true;
        }
      }
    } 
  }
?>
<?php
  if ($noExist) {
    echo '<p>Tập tin không tồn tại </p>';
  } else {
?>
  <div class="wrapper">
    <div class="heading">EDIT FILE</div>
    <div id="form">
      <form action="#" method="post">
        <div class="row">
          <p class="title">Tiêu đề</p>
          <input type="text" name="title" value="<?php echo $title; ?>">
          <?php echo $errorTitle; ?>
        </div>
        <div class="row">
          <p class="title">Mô tả</p>
          <textarea name="description" rows="5" cols="100"><?php echo $description; ?></textarea>
          <?php echo $errorDescription; ?>
        </div>
        <div class="row">
          <input type="submit" value="Lưu">
          <input type="button" value="Hủy" id="btnHuy">
        </div>
        <?php
          if ($flag == true) {
            echo '<div class="row">Cập nhật dữ liệu thành công!</div>';
          }
        ?>
      </form>
    </div>
  </div>
<?php
}
?>
</body>
</html>

Tương tự cho [delete.php]

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
  <script src="js/jquery.js"></script>
  <script>
    $(document).ready(function() {
      $('#btnHuy').click(function() {
        window.location = 'index.php';
      });
    });
  </script>
</head>
<body>
<?php
  require_once 'functions.php';
  $noExist = false;
  $id = $_GET['id'];
  $content = @file_get_contents('./files/' . $id . '.txt');
  if ($content == false) {
    $noExist = true;
  } else {
    $content = explode('||', $content);
    $title = $content[0];
    $description = $content[1];
    $flag = false;
    if (isset($_POST['id'])) {
      $id = $_POST['id'];
      @unlink('./files/' . $id . '.txt');
      $flag = true;
    }
  }
?>
<?php
  if ($noExist) {
    echo '<p>Tập tin không tồn tại </p>';
  } else {
?>
  <div class="wrapper">
    <div class="heading">DELETE FILE</div>
    <?php if ($flag == false) { ?>
    <div id="form">
      <form action="#" method="post">
        <div class="row">
          <p>Tập tin:</p>
          <span><?php echo realpath('./files/' . $id . '.txt'); ?></span>
        </div>
        <div class="row">
          <p>Tiêu đề:</p>
          <span><?php echo $title; ?></span>
        </div>
        <div class="row">
          <p>Mô tả:</p>
          <span><?php echo $description; ?></span>
        </div>
        <div class="row">
          <input type="hidden" name="id" value="<?php echo $id; ?>">
          <input type="submit" value="Xóa">
          <input type="button" value="Hủy" id="btnHuy">
        </div>
      </form>
      <?php }else {
        echo '<p>Đã xóa được tập tin. Bấm vào <a href="index.php">đây</a> để về trang chủ. </p>';
      } ?>
    </div>
  </div>
<?php
  }
?>
</body>
</html>

Bài tập 4. Khi xóa nhiều tập tin, trang web sẽ hiển thị một cửa sổ xác nhận “có chắc chắn xóa không?”, nếu người dùng bấm “đồng ý” thì xóa. Sử dụng jAlert của jQuery.

jAlert là một plug-in của jQuery, vào đây để tải jAlert về máy:


Khai báo trong [index.php]

<link rel="stylesheet" href="/jAlert/jAlert.css">
  <script src="js/jquery.js"></script>
  <script src="jAlert/jAlert.min.js"></script>
  <script>
    $(document).ready(function() {
      $('#multipleDelete').click(function() {
        $.jAlert({'type': 'confirm','confirmQuestion':'Các tập tin sẽ bị xóa vĩnh viễn, Bạn có chắc chắn muốn xóa không?', 'onConfirm': function(){
          $('#mainForm').submit();   
          }
        });
      });
    });

  </script>
-----------
Cập nhật [16/9/2020]
-----------
Xem thêm:

Ngu ngơ học làm web (79) - Bài tập xử lý tập tin 2

Tiếp theo của: Ngu ngơ học làm web (78) - Bài tập xử lý tập tin 1 
------

Phần 79.       Bài tập xử lý tập tin 2


Đây là clip số 84:


Bổ sung hàm convertSize vào cuối tập tin functions.php

[functions.php]

// hàm chuyển đơn vị đo kích thước tập tin
    function convertSize($size, $totalDigit = 2, $distance = ' ') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    $length = count($units);
    for($i = 0; $i < $length; $i++) {
      if ($size >= 1024) {
        $size = $size/1024;
      } else {
        $unit = $units[$i];
        break;
      }
    }
    $result = round($size, $totalDigit) . $distance . $unit;
    return $result;
  }

Viết mã cho trang index.php,

[index.php]

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>File</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
<?php
  require_once 'functions.php';
  $data = scandir('./files');
?>
  <div class="wrapper">
    <div class="heading">QUẢN LÝ TẬP TIN</div>
    <form action="multipleDelete.php" method="post">
      <?php
        $i = 0;
        foreach ($data as $key => $value) {
          if ($value == '.' || $value == '..' || preg_match('/.txt$/imsU', $value) == false) continue;
          $content = file_get_contents('./files/'.$value);
          $content = explode('||', $content);
          $title = $content[0];
          $description = $content[1];
          $id = substr($value, 0, 5);
          $size = convertSize(filesize('./files/'.$value));
      ?>
      <div class="row <?php if ($i % 2 == 0) echo 'odd'; ?>">
        <p class="check">
          <input type="checkbox" name="checkbox[]" value="fileName">
        </p>
        <p class="content"><?php echo $title; ?><span><?php echo $description; ?></span></p>
        <p class="id"><?php echo $id; ?></p>
        <p class="size"><?php echo $size; ?></p>
        <p class="action">
          <a href="edit.php?id=<?php echo $id; ?>">Edit</a> |
          <a href="delete.php?id=<?php echo $id; ?>">Delete</a>
        </p>
      </div>
      <?php
        $i++;
       }
      ?>
    </form>
  </div>
</body>
</html>

Đây là clip số 85:


Viết mã cho chức năng Edit một tập tin,

[edit.php]

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
  <script src="js/jquery.js"></script>
  <script>
    $(document).ready(function() {
      $('#btnHuy').click(function() {
        window.location = 'index.php';
      });
    });
  </script>
</head>
<body>
<?php
  require_once 'functions.php';
  $id = $_GET['id'];
  $content = file_get_contents('./files/' . $id . '.txt');
  $content = explode('||', $content);
  $title = $content[0];
  $description = $content[1];
  $flag = false;
  $errorTitle = '';
  $errorDescription = '';
  if (isset($_POST['title']) && isset($_POST['description'])) {
    $title = $_POST['title'];
    $description = $_POST['description'];
    // kiểm tra dữ liệu nhập vào
    if (checkEmpty($title)) {
      $errorTitle = '<p class="error">Tiêu đề không được để trống</p>';
    }
    if (checkLength($title, 5, 100)) {
      $errorTitle .= '<p class="error">Tiêu đề dài từ 5 đến 100 kí tự</p>';
    }
    if (checkEmpty($description)) {
      $errorDescription = '<p class="error">Mô tả không được để trống</p>';
    }
    if (checkLength($description, 10, 500)) {
      $errorDescription .= '<p class="error">Mô tả dài từ 10 đến 500 kí tự</p>';
    }
    // nếu dữ liệu hợp lệ
    if ($errorTitle == '' && $errorDescription == '') {
      $data = $title . '||' . $description;
      $fileName = './files/' . $id . '.txt';
      if (file_put_contents($fileName, $data)) {
        $title = '';
        $description = '';
        $flag = true;
      }
    }
  }
?>
  <div class="wrapper">
    <div class="heading">ADD FILE</div>
    <div id="form">
      <form action="#" method="post">
        <div class="row">
          <p class="title">Tiêu đề</p>
          <input type="text" name="title" value="<?php echo $title; ?>">
          <?php echo $errorTitle; ?>
        </div>
        <div class="row">
          <p class="title">Mô tả</p>
          <textarea name="description" rows="5" cols="100"><?php echo $description; ?></textarea>
          <?php echo $errorDescription; ?>
        </div>
        <div class="row">
          <input type="submit" value="Lưu">
          <input type="button" value="Hủy" id="btnHuy">
        </div>
        <?php
          if ($flag == true) {
            echo '<div class="row">Ghi dữ liệu thành công!</div>';
          }
        ?>
      </form>
    </div>
  </div>
</body>
</html>


Lưu ý: ở trong edit.php, nếu thay đoạn mã <form action="#" method="post"> thành <form action="edit.php" method="post"> sẽ bị lỗi, nguyên nhân là do giá trị id truyền trên URL bị mất khi action=“edit.php”.


Viết mã cho chức năng Delete,


[delete.php]
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
  <script src="js/jquery.js"></script>
  <script>
    $(document).ready(function() {
      $('#btnHuy').click(function() {
        window.location = 'index.php';
      });
    });
  </script>
</head>
<body>
<?php
  require_once 'functions.php';
  $id = $_GET['id'];
  $content = file_get_contents('./files/' . $id . '.txt');
  $content = explode('||', $content);
  $title = $content[0];
  $description = $content[1];
  $flag = false;
  if (isset($_POST['id'])) {
    $id = $_POST['id'];
    @unlink('./files/' . $id . '.txt');
    $flag = true;
  }
?>
  <div class="wrapper">
    <div class="heading">DELETE FILE</div>
    <?php if ($flag == false) { ?>
    <div id="form">
      <form action="#" method="post">
        <div class="row">
          <p>Tập tin:</p>
          <span><?php echo realpath('./files/' . $id . '.txt'); ?></span>
        </div>
        <div class="row">
          <p>Tiêu đề:</p>
          <span><?php echo $title; ?></span>
        </div>
        <div class="row">
          <p>Mô tả:</p>
          <span><?php echo $description; ?></span>
        </div>
        <div class="row">
          <input type="hidden" name="id" value="<?php echo $id; ?>">
          <input type="submit" value="Xóa">
          <input type="button" value="Hủy" id="btnHuy">
        </div>
      </form>
      <?php }else {
        echo '<p>Đã xóa được tập tin. Bấm vào <a href="index.php">đây</a> để về trang chủ. </p>';
      } ?>
    </div>
  </div>
</body>
</html>

Để ý, trong delete.php có sử dụng một trường input ẩn để gửi id của tập tin cần xóa về server: <input type="hidden" name="id" value="<?php echo $id; ?>">

Để hệ thống không xuất cảnh báo khi hàm unlink bị thất bại, thêm dấu @ phía trước của nó. Ví dụ:

@unlink('./files/' . $id . '.txt');

Xóa nhiều tập tin,

Thêm đoạn mã sau vào cuối tập tin index.php

…
   ?>
    </form>
    <div>
      <a href="add.php">Thêm tập tin</a>
      <a id="multipleDelete" href="#">Xóa tập tin</a>
    </div>
  </div>
</body>
…

Sử dụng jQuery để thực hiện submit một form, (khi bấm vào một nút bất kì, nút này không thuộc kiểu submit và không nằm trong form):

$(document).ready(function() {
      $('#multipleDelete').click(function() {
        $('#mainForm').submit();
      });
    });

[multipleDelete.php]

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
<div>
<?php
  $checkbox = $_POST['checkbox'];
  if (!empty($checkbox)) {
    foreach ($checkbox as $key => $value) {
      @unlink('./files/' . $value . '.txt');
    }
  }
?>
    <div class="wrapper">
      <div class="heading">DELETE FILE</div>
    </div>
    <div>
      <p>Đã xóa được tập tin. Bấm vào <a href="index.php">đây</a> để về trang chủ. </p>
    </div>
</div>
</body>
</html>
[index.php]
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>File</title>
  <link rel="stylesheet" href="style.css">
  <script src="js/jquery.js"></script>
  <script>
    $(document).ready(function() {
      $('#multipleDelete').click(function() {
        $('#mainForm').submit();
      });
    });
  </script>
</head>
<body>
<?php
  require_once 'functions.php';
  $data = scandir('./files');
?>
  <div class="wrapper">
    <div class="heading">QUẢN LÝ TẬP TIN</div>
    <form action="multipleDelete.php" method="post" id="mainForm">
      <?php
        $i = 0;
        foreach ($data as $key => $value) {
          if ($value == '.' || $value == '..' || preg_match('/.txt$/imsU', $value) == false) continue;
          $content = file_get_contents('./files/'.$value);
          $content = explode('||', $content);
          $title = $content[0];
          $description = $content[1];
          $id = substr($value, 0, 5);
          $size = convertSize(filesize('./files/'.$value));
      ?>
      <div class="row <?php if ($i % 2 == 0) echo 'odd'; ?>">
        <p class="check">
          <input type="checkbox" name="checkbox[]" value="<?php echo $id; ?>">
        </p>
        <p class="content"><?php echo $title; ?><span><?php echo $description; ?></span></p>
        <p class="id"><?php echo $id; ?></p>
        <p class="size"><?php echo $size; ?></p>
        <p class="action">
          <a href="edit.php?id=<?php echo $id; ?>">Edit</a> |
          <a href="delete.php?id=<?php echo $id; ?>">Delete</a>
        </p>
      </div>
      <?php
        $i++;
       }
      ?>
    </form>
    <div>
      <a href="add.php">Thêm tập tin</a>
      <a id="multipleDelete" href="#">Xóa tập tin</a>
    </div>
  </div>
</body>
</html>

Sử dụng thuộc tính name=array[] của checkbox để lấy về một mảng các giá trị, ví dụ:

<input type="checkbox" name="checkbox[]" value="<?php echo $id; ?>">
-----------
Cập nhật [16/9/2020]
-----------
Xem thêm:
- Tổng hợp các bài viết về Ngu ngơ học làm web