SQLSTATE[HY000]: General error: 8 attempt to write a readonly database

(maybe this question is suited for SO, but I don't think it's linked to my code).

I'm using SQLite3 as a database engine for my Web app.

I freshly deployed it on the production server, and it's not working as expected.

I'm using PDO (a PHP DB interface) to access this DB, but whenever I try to write something in it, I get the error:

SQLSTATE[HY000]: General error: 8 attempt to write a readonly database

The production server is a Centos 8 running Httpd (so Apache). I've set the rights to 777 for the whole folder (this is just a test, don't blame me), but still getting the error.

I've read many things about this error, but none of them worked for me.

Funny thing, when running:

php -r 'var_dump(
  $db=new PDO("sqlite:/var/www/myProjetFolder/db/myProjetDb.sqlite"),
  $q=$db->query("SELECT * FROM sqlite_master"),
  $q->fetchAll()); '

At the root of the Web server, I get the content of my database, so I guess the rights are good.

As a precision, my project is stored in /var/www/myProjectFolder/.

I did not create any vHost for the moment, I simply edited httpd.conf and changed the DocumentRoot.

Why is this happening?


By default SELinux doesn't allow the web server to write any files (uploads, your SQLite database, etc). You need to tell it which files and directories should be writable by the web server.

To make a single file writable:

semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/myProjetFolder/db/myProjetDb.sqlite"

To make a whole directory writable:

semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/uploads(/.*)?"

Then reset the file contexts on the affected file or directory.

restorecon -rv /var/www/uploads
restorecon -v /var/www/myProjetFolder/db/myProjetDb.sqlite