Question

file_put_contents won't write data anywhere

Posted August 9, 2020 143 views
ApachePHP

I have some php scripts that dump certain data to disk so that a user can later, optionally, download them. This worked fine on my local development machine but is not working on my DigitalOcean droplet.

Boiled down, the code looks like

<?php
 file_put_contents("./onedot.txt" , "?");
 file_put_contents("../twodots.txt" , "?");
 file_put_contents("./pro/dotslashpro.txt" , "?");
 file_put_contents("/slash.txt" , "?");
 echo 'tried it';
?>

The code runs but none of these files get created

an alternate implementation based around fopen() and write() resulted in a “can’t open file” error.

I presume there is some setting in Apache or in Debian that I need to change. Any suggestions?

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
3 answers

Hi @nycstern,

It seems to me that you don’t have enough permissions to actually create the files. Check your files’ and directories’ permissions and ownership.

It either too restrictive permissions which you can change by using the chmod command or it’s something wrong with the ownership. Maybe you have root:root as ownership which may cause errors when you load the website via apache and it has to create a file there.

Regards,
KFSys

Presumably that, thank you. I ended up passing the data a different way anyway.

By way of context, this is all being done in PHP. The data in question is logged to a database in addition to being made available to the user. Rather than writing the data to disk and making it available for download via <a href="">, as I had originally intended, the primary PHP page (primary.php) now sets cookies that uniquely identify a database record for the information that is going to be displayed, then links to a second php page (download.php) via the following

$filename = $company . " " . $whichThing . " " . date("Ymd") . ".json";
echo '<a href="./download.php" download="' . $filename . '">Download data</a>';

When the user clicks on this link, download.php renders a page for download. It does this in four steps.

  1. use getcookie() to identify the information it is going to need
  2. SELECTs this data from the database and assigns it to a variable ($json)
  3. sets header("Content-type: application/json");, and
  4. echos $json

It all worked perfectly and I believe this approach provides security advantages over my original solution as well.

One headache — the pages in question had been visible within an iframe on another website of mine, and this caused problems when I switched to new solution, as Safari (and perhaps other browsers) greatly restrict the use of cookies in an iframe between domains. In the end I eliminated the iframe and instead just passed the user off to the second domain.

Submit an Answer