Reading and Writing Files in PHP Practice Questions with Solutions

Introduction

Reading and writing files in PHP allows you to store information permanently and retrieve it whenever needed. These operations are useful for managing student records, employee details, website logs, and other application data. In this chapter, you will practise reading, writing, appending, updating, and processing file content through practical PHP examples.

Question 1: Write Text into a File Using file_put_contents()

Problem Statement:
Write a PHP program to create a file named student.txt and store a student name inside it using file_put_contents().

PHP Solution:

<?php

$content = "Student Name: Rahul";

file_put_contents("student.txt", $content);

echo "Data written successfully.";

?>

Sample Output:

Data written successfully.

Content of student.txt:

Student Name: Rahul

Explanation:

  • file_put_contents() writes data into a file.
  • If the file does not exist, PHP creates it.
  • If the file already exists, its previous content is replaced by default.

Concepts Covered: file_put_contents(), writing files, file creation.


Question 2: Read Complete File Content Using file_get_contents()

Problem Statement:
Write a PHP program to read and display the complete content of student.txt.

PHP Solution:

<?php

$content = file_get_contents("student.txt");

echo $content;

?>

Sample Output:

Student Name: Rahul

Explanation:

  • file_get_contents() reads the complete file content.
  • The returned content is stored in $content.
  • echo displays the stored information.

Concepts Covered: file_get_contents(), reading files, file content.


Question 3: Write Multiple Lines into a File

Problem Statement:
Write a PHP program to store multiple student details in students.txt, with each student’s information on a separate line.

PHP Solution:

<?php

$students = "Rahul - PHP\n";
$students .= "Priya - Python\n";
$students .= "Amit - Java";

file_put_contents("students.txt", $students);

echo "Student records saved successfully.";

?>

Sample Output:

Student records saved successfully.

Content of students.txt:

Rahul - PHP
Priya - Python
Amit - Java

Explanation:

  • $students stores the student records.
  • \n adds a new line between records.
  • .= adds additional text to the existing variable.
  • file_put_contents() saves all records in the file.

Concepts Covered: Multiple-line writing, string concatenation, file storage.


Question 4: Append New Data Without Removing Existing Content

Problem Statement:
Write a PHP program to add a new employee record to employees.txt without deleting existing records.

PHP Solution:

<?php

$employee = "Rahul - Developer\n";

file_put_contents("employees.txt", $employee);

$newEmployee = "Priya - HR Executive\n";

file_put_contents("employees.txt", $newEmployee, FILE_APPEND);

echo "New employee record added.";

?>

Sample Output:

New employee record added.

Content of employees.txt:

Rahul - Developer
Priya - HR Executive

Explanation:

  • The first file_put_contents() creates the file and stores the first record.
  • FILE_APPEND adds new content at the end of the file.
  • Existing records remain unchanged.

Concepts Covered: FILE_APPEND, appending data, file writing.


Question 5: Read a File Line by Line Using file()

Problem Statement:
Write a PHP program to read all student records from students.txt and display them one by one.

PHP Solution:

<?php

$students = file("students.txt");

foreach ($students as $student) {

    echo $student;

}

?>

Sample Output:

Rahul - PHP
Priya - Python
Amit - Java

Explanation:

  • file() reads a file and returns its lines as an array.
  • Each line becomes an individual array element.
  • foreach processes each student record.
  • The records are displayed one by one.

Concepts Covered: file(), arrays, foreach loop, reading lines.


Question 6: Count Words in a Text File

Problem Statement:
Write a PHP program to count the total number of words stored in message.txt.

PHP Solution:

<?php

file_put_contents("message.txt", "PHP makes web development easy");

$content = file_get_contents("message.txt");

$totalWords = str_word_count($content);

echo "Total Words: " . $totalWords;

?>

Sample Output:

Total Words: 5

Explanation:

  • file_put_contents() stores a sentence in the file.
  • file_get_contents() reads the sentence.
  • str_word_count() counts the words in the text.
  • The total word count is displayed.

Concepts Covered: File reading, file writing, word counting.


Question 7: Search for a Word in a File

Problem Statement:
Write a PHP program to search for the word PHP inside course.txt.

PHP Solution:

<?php

file_put_contents(
    "course.txt",
    "PHP is a server-side programming language."
);

$content = file_get_contents("course.txt");

if (strpos($content, "PHP") !== false) {

    echo "Word found in the file.";

} else {

    echo "Word not found.";

}

?>

Sample Output:

Word found in the file.

Explanation:

  • file_put_contents() stores course information.
  • file_get_contents() reads the file content.
  • strpos() searches for the specified word.
  • If the word exists, its position is returned.
  • The strict comparison !== false also handles a match at position 0.

Concepts Covered: File searching, strpos(), conditional statements.


Question 8: Replace Text Inside a File

Problem Statement:
Write a PHP program to replace the word PHP with Python in a text file named course.txt.

PHP Solution:

<?php

file_put_contents(
    "course.txt",
    "PHP is a popular programming language."
);

$content = file_get_contents("course.txt");

$updatedContent = str_replace(
    "PHP",
    "Python",
    $content
);

file_put_contents("course.txt", $updatedContent);

echo "File content updated successfully.";

?>

Sample Output:

File content updated successfully.

Updated Content of course.txt:

Python is a popular programming language.

Explanation:

  • The original content is stored in course.txt.
  • file_get_contents() reads the existing content.
  • str_replace() replaces PHP with Python.
  • file_put_contents() saves the updated content back into the same file.

Concepts Covered: File updating, str_replace(), reading and writing files.


Question 9: Read a File and Display Its Size

Problem Statement:
Write a PHP program to display the content and size of a file named report.txt.

PHP Solution:

<?php

file_put_contents("report.txt", "Monthly Sales Report");

$content = file_get_contents("report.txt");

$size = filesize("report.txt");

echo "File Content: " . $content . "\n";

echo "File Size: " . $size . " bytes";

?>

Sample Output:

File Content: Monthly Sales Report
File Size: 20 bytes

Explanation:

  • file_put_contents() creates the file and stores the report.
  • file_get_contents() reads the stored content.
  • filesize() returns the file size in bytes.
  • Both the content and file size are displayed.

Concepts Covered: filesize(), file reading, file information.


Question 10: Create and Read an Employee Report

Problem Statement:
Create an employee report containing employee names, departments, and salaries. Save the records in a text file and read the complete report.

PHP Solution:

<?php

$employees = [
    "Rahul, IT, 35000",
    "Priya, HR, 40000",
    "Amit, Sales, 30000"
];

$report = "";

foreach ($employees as $employee) {

    $report .= $employee . "\n";

}

file_put_contents("employee_report.txt", $report);

$storedReport = file_get_contents("employee_report.txt");

echo "Employee Salary Report\n\n";

echo $storedReport;

?>

Sample Output:

Employee Salary Report

Rahul, IT, 35000
Priya, HR, 40000
Amit, Sales, 30000

Explanation:

  • The $employees array stores employee information.
  • foreach processes each employee record.
  • .= combines all records into one string.
  • file_put_contents() saves the report in a text file.
  • file_get_contents() reads the saved report.
  • Finally, the complete employee report is displayed.

Concepts Covered: Arrays, loops, file writing, file reading, report generation.


Key Takeaways

  • file_put_contents() writes data into a file.
  • file_get_contents() reads the complete content of a file.
  • FILE_APPEND adds new data without replacing existing content.
  • file() reads a file and returns its lines as an array.
  • str_word_count() counts words in text.
  • strpos() searches for text inside a file’s content.
  • str_replace() replaces existing text.
  • filesize() returns the file size in bytes.
  • Always check file paths and permissions before performing file operations.

FAQs: Reading and Writing Files in PHP

1. How do you read a file in PHP?

You can use file_get_contents() to read the complete content of a file.

2. How do you write data into a file in PHP?

You can use file_put_contents() to create a file and write data into it.

3. What is the difference between file_get_contents() and file()?

file_get_contents() returns the complete file content as a string, while file() returns the file lines as an array.

4. How can you append data to a file in PHP?

Use file_put_contents() with the FILE_APPEND flag to add data without replacing existing content.

5. Does file_put_contents() create a new file?

Yes. If the specified file does not exist, file_put_contents() creates it, provided the directory is writable.

6. How can you replace text inside a file?

Read the file using file_get_contents(), replace the required text using str_replace(), and save the updated content using file_put_contents().

7. How can you count words in a file?

Read the file content using file_get_contents() and pass the returned string to str_word_count().

8. How can you check the size of a file in PHP?

Use the filesize() function to get the file size in bytes.

9. What is FILE_APPEND in PHP?

FILE_APPEND is a flag used with file_put_contents() to add new content at the end of an existing file.

10. What is the difference between file handling and reading/writing files?

File handling is the broader process of managing files, including creating, opening, copying, renaming, and deleting them. Reading and writing focus specifically on retrieving and storing file content.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top