James
James

Reputation: 2283

Why isn't file_put_contents overwriting?

I have a page with a WYSIWYG editor the user can use. After editing, they can press a button, and the javascript should POST the current page to a save.php file and refresh the page with new information.

There are two problems. The first is that initially the page doesn't load with the updated file. The user has to refresh the page to see it updated (maybe it just takes an extra second to write the file?). The second problem, is that after the first time the temporary file was created, it cannot be overwritten, so the page never updates after the first refresh. Here are the snippets I'm working with:

Javascript function on the WYSIWYG editor page (editor.php):

function refresh(html,username,info)
{
    $.post("save.php", { html: html, username: username } );
    window.location = 'editor.php?info=' + info;
}

save.php file

$html = $_POST['html'];
$username = $_POST['username']; 
file_put_contents('temp/' . $username . '.txt', $html);

Upvotes: 0

Views: 2492

Answers (3)

steveukx
steveukx

Reputation: 4368

As the browser may not have issued the POST request before navigating to the next page, use the success callback from the post to do the relocate:

function refresh(html,username,info) {
  $.post("save.php", { html: html, username: username }, function() {
    window.location = 'editor.php?info=' + info;
  });
}

As other people have already commented, using data directly from a form post without sanitising it is a really bad plan and opens your server up to all kinds of malicious attacks. Have a look at some of these questions: https://stackoverflow.com/search?q=sanitize+php

If the data is getting to your server ok, make sure that the access permissions on the directory 'temp' allow write access from the web server user (if you have access to SSH to your server, run chmod go+w /path/to/temp, otherwise most FTP programs allow you to set file permissions too).

Upvotes: 1

Johni
Johni

Reputation: 2959

The ajax request is asynchrone so the writing operation can be in progress when the redirection is started. You have to listen to the finished exent of the $.post action to do the redirect.

Upvotes: 0

CKKiller
CKKiller

Reputation: 1422

why not use fopen and fwrite?

simply use:

$html = $_POST['html'];
$username = $_POST['username']; 
$file = "temp/" . $username . ".txt";

if (!file_exists($file)) {
  $files = fopen($file, "x+");
} else {
  $files = fopen($file, "w+");
}

if(fwrite($files, $html)) {
  echo "Success!";
} else {
  echo "Failure!";
}

for the php and to make the refresh work in js, try putting the statement in the success function like this:

function refresh(html,username,info) {
    $.post("save.php", { html: html, username: username }, 
            function (response) {
             window.location = 'editor.php?info=' + info;
             console.log(response);// for debugging :) 
           });
}

Upvotes: 0

Related Questions