לדלג לתוכן

1.6 - פעולות עם קבצים php - הרצאה

בהרצאה הבאה נראה פעולות שונות שניתן לעשות עם קבצים בPHP.

1. קריאת קבצים

קריאת קובץ כולו (file_get_contents)

הדרך הפשוטה ביותר לקרוא קובץ:

$content = file_get_contents('example.txt');
echo $content;

קריאת קובץ שורה אחר שורה (fopen + fgets)

כאשר עובדים עם קבצים גדולים:

$file = fopen('example.txt', 'r');
if ($file) {
    while (($line = fgets($file)) !== false) {
        echo $line . "<br>";
    }
    fclose($file);
} else {
    echo "Unable to open the file";
}

קריאת קובץ למערך (file)

מחזיר כל שורה כפריט במערך:

$lines = file('example.txt');
foreach ($lines as $line) {
    echo $line . "<br>";
}

2. כתיבה לקבצים

כתיבה לקובץ (file_put_contents)

כתיבה פשוטה או החלפת תוכן קיים:

file_put_contents('example.txt', 'New content for the file');

הוספת תוכן לסוף קובץ (FILE_APPEND)

file_put_contents('example.txt', "\nNew line", FILE_APPEND);

כתיבה עם fopen + fwrite

שיטה גמישה יותר לכתיבה:

$file = fopen('example.txt', 'w'); // 'w' - write (replaces content), 'a' - append to end
if ($file) {
    fwrite($file, "First line\n");
    fwrite($file, "Second line\n");
    fclose($file);
} else {
    echo "Unable to open the file for writing";
}

3. בדיקות קבצים

בדיקת קיום קובץ

if (file_exists('example.txt')) {
    echo "The file exists";
} else {
    echo "The file does not exist";
}

בדיקת סוג הקובץ

if (is_file('example.txt')) {
    echo "This is a regular file";
}

if (is_dir('folder')) {
    echo "This is a folder";
}

קבלת מידע על הקובץ

$file_info = [
    'size' => filesize('example.txt') . ' bytes',
    'last modified' => date("d/m/Y H:i", filemtime('example.txt')),
    'type' => filetype('example.txt')
];

print_r($file_info);

4. שימוש ב-include ו-require

אנחנו יכולים לחלק את הקוד שלנו למספר קבצי php ואז לעשות להם import, באמצעות פעולת Include או פעולת require.

הכללת קבצי PHP

include 'header.php'; // continues to run even if the file doesn't exist
require 'config.php'; // stops the script if the file doesn't exist

include_once 'functions.php'; // included only once
require_once 'db_connection.php'; // included only once

הבדלים עיקריים

פונקציה תגובה אם קובץ לא קיים טעינה מרובה
include אזהרה (warning) מאפשר טעינה מרובה
require שגיאה (error) מאפשר טעינה מרובה
include_once אזהרה (warning) מונע טעינה מרובה
require_once שגיאה (error) מונע טעינה מרובה
פונקציות אלו יודעות לטעון קוד php אחר שכתבנו ישירות לקובץ שלנו!
## 5. ניהול תיקיות

יצירת תיקייה

if (!file_exists('new_folder')) {
    mkdir('new_folder');
    echo "The folder was created";
}

סריקת תיקייה

$files = scandir('folder_name');
foreach ($files as $file) {
    if ($file != "." && $file != "..") {
        echo $file . "<br>";
    }
}

מחיקת תיקייה

if (file_exists('folder_to_delete')) {
    rmdir('folder_to_delete');
    echo "The folder was deleted";
}