Search code examples
phpfopen

PHP function.fopen failed to open stream: Permission denied


I'm running apache on ubuntu 12 and i can't open a specific file with the fopen function. I can open other files in the same php file. Here is the error:

Warning: fopen(file.txt) [function.fopen]: failed to open stream: Permission denied in /.../.../.../.../....php on line 10
Warning: fwrite() expects parameter 1 to be resource, boolean given in /.../.../.../.../....php on line 11
Warning: fclose() expects parameter 1 to be resource, boolean given in /.../.../.../.../....php on line 12
Warning: Cannot modify header information - headers already sent by (output started at /.../.../.../.../....php:10) in /.../.../.../.../....php on line 20

My Code:

<?php
    session_start();
    $username = $_SESSION['username'];
    $amount = $_SESSION['amount'];
    $message = $_SESSION['message'];
    $send = "$username donated $amount";
    $Vdata = file_get_contents('donation.txt');
    $cumoney = file_get_contents('money.txt');
    $newmoney = $amount + $cumoney;
    $handle4 = fopen("money.txt", "w");
    fwrite($handle4, $newmoney);
    fclose($handle4);
    if($Vdata == $send){
        $handle = fopen("donation.txt", "w");
        fwrite($handle, $username ." donated  ". $amount);
        fclose($handle);
        $handle2 = fopen("donationmsg.txt", "w");
        fwrite($handle2, $message);
        fclose($handle2);
        header ("Location: ...");
    }else{
        $handle = fopen("donation.txt", "w");
        fwrite($handle, $username ." donated ". $amount);
        fclose($handle);
        $handle2 = fopen("donationmsg.txt", "w");
        fwrite($handle2, $message);
        fclose($handle2);
        header ("Location: ...");
    }
?>

Solution

  • Obviously PHP doesn't have write access to the file. This being on Ubuntu PHP runs as the same user as Apache, so make sure the file is writable by the www-data group.

    user@host:/path/to/your/file# chgrp www-data yourfile.txt
    user@host:/path/to/your/file# chmod g+w yourfile.txt