Skip to content
Advertisement

fopen() works properly in a debug session, but doesn’t work when I call the file through the browser

I’m new to PHP and just faced the problem with creating and opening a file with fopen(). Here is my code:

<?php
    $new_file = fopen('file.txt', 'w') or die("Cannot create a file");

    $text = <<<_END
Line 1
Line 2
Line 3
_END;

    fwrite($new_file, $text) or die('Cannot write to the file');

    fclose($new_file);

When I try to run the file by opening it in the browser I see the next message: ‘Cannot create a file’. But when I start debug session everithing works as it supposed to. I suspect that there is some issue with permissions and XDebug uses root access unlike the usual interpreter?

Advertisement

Answer

To solve this problem first of all I was needed to check PHP user with the next command:

<?php echo `whoami`; ?>

It outputs:

www-data

This is the default PHP user. Next I checked the owner of the folder with this command:

ls -dl /var/www/html/test

It outputs:

drwxrwxr-x 2 username username 4096 Jun 26 12:49

Next I’ve sat permissions to the PHP user by running:

sudo chown -R www-data /var/www/html/test

Checking once again if the owner changed

ls -dl /var/www/html/test

And now it outputs

drwxrwxr-x 2 www-data username 4096 Jun 26 12:55

Done. Now I’m able to create and write to the file.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement