0

I am working on linux (raspbian). Code works locally, but not on the server.

I can't understand what the problem is in the code. The addLineToFile function works perfectly, while deleteLineFromFile does not.

I call the functions with:

if (isset($_POST['delete'])){
    $valTemp = $array[$_POST['delete']];
    addLineToFile($directory."linkOffline.txt",$valTemp);
    deleteLineFromFile($directory."output.txt",$valTemp);
}

where

$directory = "/home/pi/linkFinder/server/";

then

function addLineToFile($dirFile, $line){
    $myfile = fopen($dirFile, "a") or die("Unable to open file!");
    fwrite($myfile, "\n". $line);
    fclose($myfile);
}

function deleteLineFromFile($dirFile, $line){
    $contents = file_get_contents($dirFile);
    $contents = str_replace($line."\r\n", '', $contents);
    file_put_contents($dirFile, $contents);
}

I tried to assign all the permissions to the txt files, with chmod 777.

I also thought there might be some problem with file_get_contents and file_put_contents. So I rewrote the function like this, but it still doesn't work.

function fileGetContents2($url) { //alternativa a file_get_contents
    $file = fopen($url, 'r');
    $data = stream_get_contents($file);
    fclose($file);
    return $data;
 }


function deleteLineFromFile($dirFile, $line){
    $contents = fileGetContents2($dirFile);
    $contents = str_replace($line."\r\n", '', $contents);
    $myfile = fopen($dirFile, "w") or die("Unable to open file!");
    fwrite($myfile, $contents);
    fflush($myfile);
    fclose($myfile);
}

The txt files are in a /home/user/... folder and are generated by a python script.

Thanks in advance

  • 1
    Might depend on your system, some use `\r\n` some don't, to make it compatible you can use `PHP_EOL` - try `str_replace($line.PHP_EOL, '', $contents);` – Nigel Ren Mar 15 '20 at 16:51
  • 1
    I believe the problem is created by having the `\r` on the `str_replace` method. Try removing it `$contents = str_replace($line."\n", '', $contents);`. Also check this https://stackoverflow.com/questions/15433188/r-n-r-and-n-what-is-the-difference-between-them – Claudio Mar 15 '20 at 16:52
  • 2
    New lines are different on windows and linux. Windows uses `\r\n` while linux uses `\n`. Use the `PHP_EOL` constant for consistent results. – Alex Barker Mar 15 '20 at 16:53

0 Answers0