简体   繁体   中英

PHP doesn't save to files

I have Apache 2 and PHP installed on a Raspberry Pi 1 B+ (RASPBIAN STRETCH LITE ). I have a website running on it with a textbox and a PHP script that is supposed to save the contents of the textbox to a text file on the server when the user submits. I tryed basically everything but the php script just wont save. PHP does get the textbox-content (I tested it - it works just fine).

This is my PHP:

<?php
include "code/multiPage/topBar.html";
$dir = "/data/searches.txt";
if ($_REQUEST) {
    $input = $_REQUEST["search"];
    file_put_contents($dir, $input, FILE_APPEND);
}
?>

PHP is working properly aside from this problem.

The folder has read-write permissions for everyone. I have also tryed to let PHP create its own folder with code similar to this:

if (!file_exists('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);
}

PHP can't even do that.

Thanks in advance for any help!

First just try this separately from other code

<?php

file_put_contents("/data/searches.txt", "bla", FILE_APPEND);

?>

if it's not working try to get a last error

echo print_r( error_get_last (  ), true)

In order to make sure that you can write to the file you can always check if it's writable

if(is_writable($dir))

Also for debugging it's nice to see how much bites was written by file_put_contents

so the final code easy to debug will be like this:

<?php
include "code/multiPage/topBar.html";
$dir = "/data/searches.txt";
if(!is_writable($dir)){
    echo "cannot write to file";
}

if (!empty($_REQUEST["search"])) {
    $input = $_REQUEST["search"];
    $bitecount = file_put_contents($dir, $input, FILE_APPEND);
}
echo $bitecount . " bites were written to the file";
?>

There is a thing. If $_REQUEST["search"]="" or $_REQUEST["search"]=null the if($_REQUEST) will be TRUE anyway

I figured it out. The problem was that the webserver didn't have permission to write to the directory. problem solved by running sudo chown -R www-data var/www/html/data thanks for the help! Have a nice day :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM