0
0
PHPprogramming~30 mins

Writing files (fwrite, file_put_contents) in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Writing files with fwrite and file_put_contents in PHP
📖 Scenario: You are creating a simple PHP script to save user notes into a text file on the server. This is like writing a diary entry or saving a shopping list.
🎯 Goal: Build a PHP script that writes a string into a file using two methods: fwrite and file_put_contents.
📋 What You'll Learn
Create a variable with the filename 'notes.txt'.
Create a variable with the text content to save.
Use fwrite to write the content into the file.
Use file_put_contents to write the content into the file.
Print a confirmation message after writing.
💡 Why This Matters
🌍 Real World
Writing files is common when saving user data, logs, or configuration settings on a server.
💼 Career
Many web developers need to handle file operations safely and efficiently to store and retrieve data.
Progress0 / 4 steps
1
Create filename and content variables
Create a variable called $filename and set it to the string 'notes.txt'. Then create a variable called $content and set it to the string 'Today I learned how to write files in PHP.'.
PHP
Need a hint?

Use = to assign the string values to the variables.

2
Open file and write content using fwrite
Add code to open the file $filename for writing using fopen with mode 'w'. Then use fwrite to write the $content into the file. Finally, close the file with fclose.
PHP
Need a hint?

Use fopen to open the file, then fwrite to write, and fclose to close it.

3
Write content using file_put_contents
Add code to write the $content into the file $filename using the function file_put_contents. This function writes the entire string to the file in one step.
PHP
Need a hint?

Use file_put_contents with the filename and content as arguments.

4
Print confirmation message
Add a print statement to display the message 'File written successfully.' after writing the content.
PHP
Need a hint?

Use print('File written successfully.'); to show the message.