Home > database >  fopen() works properly in a debug session, but doesn't work when I call the file through the br
fopen() works properly in a debug session, but doesn't work when I call the file through the br

Time:06-27

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?

CodePudding user response:

to write and read permission

chown -R www-data:www-data /var/www/dicrctoy 
chmod -R 775 /var/www/dicrctoy

CodePudding user response:

I have tested in my local environment no error was found if you're using mac you should check the file permission use chmod command to change permission

What is the meaning of chmod 777? readable, writable and executable Setting 777 permissions to a file or directory means that it will be readable, writable and executable by all users

CodePudding user response:

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

<?php echo `whoami`; ?>

It outputs to me

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.

  • Related