PHP File Handling Practice Questions with Solutions

Introduction

File handling in PHP allows you to create, open, read, write, append, and delete files directly through your PHP programs. It is useful for storing information such as student records, employee details, website logs, and application data. In this chapter, you will practise important PHP file handling operations through practical solved questions.

Question 1: Create and Open a File in PHP

Problem Statement:
Write a PHP program to create a new text file named student.txt and open it in write mode.

PHP Solution:

<?php

$file = fopen("student.txt", "w");

if ($file) {
    echo "File created and opened successfully.";
    fclose($file);
}

?>

Sample Output:

File created and opened successfully.

Explanation:

  • fopen() opens a file in the specified mode.
  • The "w" mode creates a new file if it does not exist.
  • If the file already exists, its previous content is erased.
  • fclose() closes the opened file.

Concepts Covered: fopen(), write mode, fclose().


Question 2: Write Data into a File

Problem Statement:
Write a PHP program to store student information inside a text file named student.txt.

PHP Solution:

<?php

$file = fopen("student.txt", "w");

fwrite($file, "Name: Rahul\n");
fwrite($file, "Course: PHP\n");
fwrite($file, "Marks: 85");

fclose($file);

echo "Student information saved successfully.";

?>

Sample Output:

Student information saved successfully.

Content of student.txt:

Name: Rahul
Course: PHP
Marks: 85

Explanation:

  • fopen() opens the file in write mode.
  • fwrite() writes information into the file.
  • \n moves the next information to a new line.
  • fclose() closes the file after writing.

Concepts Covered: fwrite(), writing text files, newline character.


Question 3: Read Data from a File

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

PHP Solution:

<?php

$file = fopen("student.txt", "r");

$content = fread($file, filesize("student.txt"));

echo $content;

fclose($file);

?>

Sample Output:

Name: Rahul
Course: PHP
Marks: 85

Explanation:

  • "r" opens the existing file in read-only mode.
  • filesize() returns the size of the file in bytes.
  • fread() reads the specified number of bytes.
  • echo displays the file content.
  • fclose() closes the file.

Concepts Covered: fopen(), read mode, fread(), filesize().


Question 4: Append Data to an Existing File

Problem Statement:
Write a PHP program to add new student information to the end of an existing student.txt file without deleting its previous content.

PHP Solution:

<?php

$file = fopen("student.txt", "a");

fwrite($file, "\nName: Priya");
fwrite($file, "\nCourse: Python");
fwrite($file, "\nMarks: 90");

fclose($file);

echo "New student information added successfully.";

?>

Sample Output:

New student information added successfully.

Updated Content of student.txt:

Name: Rahul
Course: PHP
Marks: 85
Name: Priya
Course: Python
Marks: 90

Explanation:

  • "a" opens the file in append mode.
  • fwrite() adds new information at the end of the file.
  • Existing content remains unchanged.
  • If the file does not exist, append mode creates it.

Concepts Covered: Append mode, fwrite(), preserving existing content.


Question 5: Check Whether a File Exists

Problem Statement:
Write a PHP program to check whether a file named student.txt exists.

PHP Solution:

<?php

$filename = "student.txt";

if (file_exists($filename)) {

    echo "File exists.";

} else {

    echo "File does not exist.";

}

?>

Sample Output:

File exists.

Explanation:

  • file_exists() checks whether the specified file or directory exists.
  • If the file is available, it returns true.
  • Otherwise, it returns false.
  • The if-else statement displays the appropriate message.

Concepts Covered: file_exists(), file checking, conditional statements.


Question 6: Read a File Line by Line

Problem Statement:
Write a PHP program to read and display the contents of student.txt one line at a time.

PHP Solution:

<?php

$file = fopen("student.txt", "r");

while (!feof($file)) {

    $line = fgets($file);

    echo $line;

}

fclose($file);

?>

Sample Output:

Name: Rahul
Course: PHP
Marks: 85
Name: Priya
Course: Python
Marks: 90

Explanation:

  • fopen() opens the file in read mode.
  • feof() checks whether the end of the file has been reached.
  • fgets() reads one line at a time.
  • The while loop continues reading until the end of the file.
  • fclose() closes the file.

Concepts Covered: fgets(), feof(), reading files line by line, while loop.


Question 7: Count the Number of Lines in a File

Problem Statement:
Write a PHP program to count the total number of lines in student.txt.

PHP Solution:

<?php

$file = fopen("student.txt", "r");

$count = 0;

while (!feof($file)) {

    $line = fgets($file);

    if ($line !== false) {
        $count++;
    }

}

fclose($file);

echo "Total Lines: " . $count;

?>

Sample Output:

Total Lines: 6

Explanation:

  • The file is opened in read mode.
  • $count starts from 0.
  • fgets() reads one line during each loop iteration.
  • The counter increases when a valid line is returned.
  • Finally, the total number of lines is displayed.

Concepts Covered: Line counting, fgets(), feof(), counters.


Question 8: Copy a File in PHP

Problem Statement:
Write a PHP program to copy student.txt into a new file named student_backup.txt.

PHP Solution:

<?php

if (copy("student.txt", "student_backup.txt")) {

    echo "File copied successfully.";

} else {

    echo "File copying failed.";

}

?>

Sample Output:

File copied successfully.

Explanation:

  • copy() creates a duplicate of an existing file.
  • The first argument is the source file.
  • The second argument is the destination file.
  • It returns true when copying succeeds and false when it fails.

Concepts Covered: copy(), file duplication, file paths.


Question 9: Rename a File in PHP

Problem Statement:
Write a PHP program to rename student_backup.txt to student_records.txt.

PHP Solution:

<?php

if (rename("student_backup.txt", "student_records.txt")) {

    echo "File renamed successfully.";

} else {

    echo "File renaming failed.";

}

?>

Sample Output:

File renamed successfully.

Explanation:

  • rename() changes the name or location of a file.
  • The first argument is the existing file name.
  • The second argument is the new file name.
  • The function returns true if the operation succeeds.

Concepts Covered: rename(), file management, file paths.


Question 10: Delete a File in PHP

Problem Statement:
Write a PHP program to delete a file named student_records.txt after checking whether it exists.

PHP Solution:

<?php

$filename = "student_records.txt";

if (file_exists($filename)) {

    if (unlink($filename)) {

        echo "File deleted successfully.";

    } else {

        echo "Unable to delete the file.";

    }

} else {

    echo "File does not exist.";

}

?>

Sample Output:

File deleted successfully.

Explanation:

  • file_exists() checks whether the file is available.
  • unlink() deletes the specified file.
  • If deletion succeeds, it returns true.
  • Always check the file name and path before deleting files because deletion can be permanent.

Concepts Covered: unlink(), file_exists(), deleting files, conditional statements.


Key Takeaways

  • PHP file handling allows programs to manage files.
  • fopen() opens or creates files.
  • fwrite() writes data into files.
  • fread() reads file content.
  • fgets() reads a file one line at a time.
  • fclose() closes an opened file.
  • file_exists() checks whether a file exists.
  • copy() creates a copy of a file.
  • rename() changes a file name or location.
  • unlink() deletes a file.
  • Always close files after opening them and check whether file operations succeed.

FAQs

1. What is file handling in PHP?

File handling in PHP allows developers to create, open, read, write, update, copy, rename, and delete files using built-in functions.

2. Which function is used to open a file in PHP?

The fopen() function is used to open a file in PHP.

3. What is the difference between w and a modes in PHP?

The w mode opens a file for writing and removes its existing content. The a mode adds new content at the end without removing existing content.

4. Which function is used to read a file in PHP?

The fread() function reads a specified number of bytes from an opened file. The fgets() function reads one line at a time.

5. Which function is used to write data into a file?

The fwrite() function writes data into an opened file.

6. What is the purpose of fclose() in PHP?

The fclose() function closes an opened file and releases its associated resources.

7. How can we check whether a file exists in PHP?

The file_exists() function checks whether a specified file or directory exists.

8. How can we delete a file using PHP?

The unlink() function deletes a specified file.

9. What is the difference between fread() and fgets()?

fread() reads a specified number of bytes, while fgets() reads one line from a file.

10. What are the different file modes in PHP?

Some commonly used file modes are:

ModePurpose
rRead an existing file
wWrite and clear existing content
aAppend data to the end
r+Read and write an existing file
w+Read and write, clearing existing content
a+Read and append to the end

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

Scroll to Top