PHP fopen for writing fails

2019-08-14 07:06发布

问题:

I am having some trouble with a PHP file I have. My fopen() call is failing and I can't work out why. I have full permissions to the file (currently set to 777), and the only thing I can think of is that the file is already open, but I can't work out why this would be. My code is made up of a landing PHP page and an action PHP page. The landing page is below:

<!DOCTYPE HTML>
<html>
<head>
    <title>Canteen Manager</title>
    <link type="text/css" rel="stylesheet" href="style_common.css"/>
    <link type="text/css" rel="stylesheet" href="style_addstock.css"/>
</head>
<body>
<div class="header">
    <img src="images/aafclogo.png" class="aafclogo">
    <h3>Add Stock</h3>
</div>
<p>Select Product:</p>
<form action="addstockaction.php" method="post" name="formExistingProduct">
    <input type='hidden' name='productType' value='existing'> 
    <select name="products">
        <?php
            class Product {
                public $name = "";
                public $amount = "";
            }

            $myfile = fopen("stock.txt", "r") or die("Unable to open file!");
            while(!feof($myfile)) {
              $fileContents = $fileContents . fgets($myfile);
            }
            fclose($myfile);
            $dictionary = json_decode($fileContents, true);

            for ($i = 0; $i < count($dictionary); ++$i) {
                echo "<option value=" . $i . ">" . $dictionary[$i]['name'] . "    </option>";
            }
        ?>
    </select>
    <input type="number" name="txtNumber" min="1"><br><br>
    <input type="submit" value="Update Amount">
</form>

When the user submits the form, it calls the following PHP file:

<!DOCTYPE HTML>
<html>
<head>
    <title>Canteen Manager</title>
    <link type="text/css" rel="stylesheet" href="style_common.css"/>
</head> 
<body>
<?php
        /*$myfile = fopen("stock.txt", "r") or die("Unable to open file!");
        while(!feof($myfile)) {
          $fileContents = $fileContents . fgets($myfile);
        }
        fclose($myfile);*/
        $fileContents = file_get_contents("stock.txt");
        echo $fileContents;
        $dictionary = json_decode($fileContents, true);

        $dictionary[$_POST['products']]['amount'] = $dictionary[$_POST['products']]['amount'] + $_POST['txtNumber'];
        $json = json_encode($dictionary, true);

        $writeFile = fopen("stock.txt", "w") or die("Unable to open file for writing!");
        $txt = $json;
        fwrite($writeFile, $txt);
        fclose($writeFile);
        echo "<p><strong>Added " . $_POST['txtNumber'] . " items to " . $dictionary[$_POST['products']]['name'] . "</strong></p><br><br>";
?>

<br><br><div class="buttonContainer">
    <a href="addstock.php"><div class="button">
        <p>Add More Items</p>
    </div></a>
    <a href="index.php"><div class="button">
        <p>Home</p>
    </div></a>
</div>

The action PHP file falls over during the $writeFile = fopen("stock.txt", "w") or die("Unable to open file for writing!"); line, when it comes up with the 'Unable to open file for writing!' line.

What am I doing wrong?

EDIT
I created a test PHP file (called test.php) and placed in the same location on the server as my current files. The file contained just the following code:

<!DOCTYPE HTML>
<html>
<head>
    <title>Canteen Manager</title>
    <link type="text/css" rel="stylesheet" href="style_common.css"/>
    <link type="text/css" rel="stylesheet" href="style_addstock.css"/>
</head>
<body>
<?php
        $writeFile = fopen("stock.txt", "w") or die("Unable to open file for writing!");
        $txt = $json;
        fwrite($writeFile, '[{"name":"Boost","amount":10},{"name":"Chicken Noodles","amount":10},{"name":"Twix","amount":10}]');
        //fwrite($writeFile, "test");
        fclose($writeFile);
        echo "<strong>Success</strong>";
?>
</body>
</html>

When I ran this initially, it succeeded in opening the file, but would not write to it. Instead it would clear it. Since copying that code over to my live file, both files get the error I was getting before. For me, this supports the theory that the file is open somewhere and therefore can't be opened again. I thought it might be my FTP client, so I closed that and tried, but same error. I have confirmed that the file (stock.txt) isn't open in my browser, nor in use by any programs on my laptop.

I am really stuck on this. Does anyone have a better way to write to a file (keep in mind I am over-writing the file at this point). I would really appreciate any advice, whether in regards to fixing my issues, or a different way to tackle the problem.

EDIT 2
I found the file permissions were set to 644 despite me setting them to 777, so I set them back to 777 and didn't receive the die warning. However, when I ran the code, I found it didn't write to the file, instead it just cleared it (emptied it of characters). My writing code is above, but I will copy it below for clarity:

$fileContents = file_get_contents("stock.txt");
echo $fileContents;
$dictionary = json_decode($fileContents, true);

$dictionary[$_POST['products']]['amount'] = $dictionary[$_POST['products']]['amount'] + $_POST['txtNumber'];
$json = json_encode($dictionary, true);

    $writeFile = fopen("stock.txt", "w") or die("Unable to open file for writing!");
$txt = $json;
fwrite($writeFile, $txt);
fclose($writeFile);
echo "<p><strong>Added " . $_POST['txtNumber'] . " items to " . $dictionary[$_POST['products']]['name'] . "</strong></p><br><br>";

Any suggestions?

回答1:

Make sure the owner of the file is apache.

Command is chown apache:apache stock.txt

It works for me.



回答2:

I ended up getting this fixed, largely thanks to the help of @ParrisVarney. The issue was in the file permissions. Each time I uploaded a new version of my file (either PHP or TXT), or edited the online version of the stock.txt file in my FTP client, it would reset the file permissions back to 644. I had to manually change them back to 777 before continuing after each upload, and then was able to open the file.

As for the writing issue, where the text file was cleared, it was because my json_encode call was incorrect. I had a boolean value included as an attribute which was causing it to fail. By removing the true from $json = json_encode($dictionary, true); and making it just $json = json_encode($dictionary);, I was able to get the script to write data.

Thanks for everyone's help, it is much appreciated.

I hope this answer can help anyone else having similar issues.



标签: php html fopen