My php code seems fine but there are two similar functions where one fails and other runs successfuly

32 Views Asked by At

Code

<?php
// Function to print the first N lines of a file
function printFirstLines($filename, $lines) {
$file = fopen($filename, 'r');
if ($file) {
    $lineCount = 0;
    while (!feof($file) && $lineCount < $lines) {
        echo fgets($file);
        $lineCount++;
    }
    fclose($file);
} else {
    echo "Error opening the file.";
}
}
function updateFileContent($filename, $content) {
$file = fopen($filename, 'a'); // 'a' mode appends to the file
if ($file) {
    fwrite($file, $content); // Add a new line
    fclose($file);
    echo "Content has been updated/added to the file.";
} else {
    echo "Error opening the file.";
}
}
// Example usage:
// (i) Print the first 5 lines of a file
echo "Printing the first 5 lines of the file:<br>";
printFirstLines("example.txt", 5);
// (ii) Update/Add content to a file
$newContent = "<br>This is a new line added at " . date("Y-m-d H:i:s");
echo "<br>Updating the file with new content:<br>";
updateFileContent("example.txt", $newContent);
?>

the output is as:

Printing the first 5 lines of the file:
He raced to the grocery store. He went inside but realized he forgot his wallet. He raced back home to grab it. Once he found it, he raced to the car again and drove back to the grocery store.
Updating the file with new content:
Error opening the file.

here as you see the printFirstLines function is working fine. But in updateFileContent, if condition fails. i tried write mode and append mode but only if its in read mode then it opens otherwise it fails. whats exactly the problem, is the browser that's not allowing writing into that folder or smtg else?

I was trying to read few lines of the file and then append a line into the file, i was able to read few lines but while opening file in append mode the code isn't working, the if condition is going to false and shows error opening the file

0

There are 0 best solutions below