-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05_file_create_write.php
More file actions
58 lines (48 loc) · 1.72 KB
/
05_file_create_write.php
File metadata and controls
58 lines (48 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
/*
|--------------------------------------------------------------------------
| 📝 PHP File Create and Write
|--------------------------------------------------------------------------
| You can create and write to files using:
| - fopen() with "w" (write) or "a" (append) mode
| - fwrite() to write text
| - fclose() to close the file
|
| If the file doesn't exist, PHP will create it.
| If it exists:
| - "w" mode will overwrite it
| - "a" mode will append to it
*/
// 📄 Create a new file "newfile.txt" and write content
echo "<h3>Creating and writing to a file using 'w' mode</h3>";
$myfile = fopen("newfile.txt", "w") or die("❌ Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt); // First write
$txt = "Jane Doe\n";
fwrite($myfile, $txt); // Second write
fclose($myfile);
echo "✔️ Written 'John Doe' and 'Jane Doe' to newfile.txt<br><br>";
// 📄 Overwrite existing file (same as above, will erase old content)
echo "<h3>Overwriting existing file using 'w' mode</h3>";
$myfile = fopen("newfile.txt", "w") or die("❌ Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
echo "✔️ Overwrote content with 'Mickey Mouse' and 'Minnie Mouse'<br><br>";
// 📄 Append new content to file using "a" mode
echo "<h3>Appending content using 'a' mode</h3>";
$myfile = fopen("newfile.txt", "a") or die("❌ Unable to open file!");
$txt = "Donald Duck\n";
fwrite($myfile, $txt);
$txt = "Goofy Goof\n";
fwrite($myfile, $txt);
fclose($myfile);
echo "✔️ Appended 'Donald Duck' and 'Goofy Goof' to newfile.txt<br><br>";
// ✅ Final content of "newfile.txt" now should be:
// Mickey Mouse
// Minnie Mouse
// Donald Duck
// Goofy Goof
?>