1.6 - פעולות עם קבצים php - הרצאה
בהרצאה הבאה נראה פעולות שונות שניתן לעשות עם קבצים בPHP.
1. קריאת קבצים¶
קריאת קובץ כולו (file_get_contents)¶
הדרך הפשוטה ביותר לקרוא קובץ:
קריאת קובץ שורה אחר שורה (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)¶
מחזיר כל שורה כפריט במערך:
2. כתיבה לקבצים¶
כתיבה לקובץ (file_put_contents)¶
כתיבה פשוטה או החלפת תוכן קיים:
הוספת תוכן לסוף קובץ (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. ניהול תיקיות |
יצירת תיקייה¶
סריקת תיקייה¶
$files = scandir('folder_name');
foreach ($files as $file) {
if ($file != "." && $file != "..") {
echo $file . "<br>";
}
}