Suppose you want to save data in a file on a client computer. You cannot do this directly, because JS cannot access the local file system. But you can achieve this through the server. You would at the same time send the data to the server and upload it to the client. Downloading opens the usual "Save As ..." dialog, where the client can specify the file name.
A possible concrete implementation uses a form that makes the POST request the save.php URL, passing the data that will be saved to the save_data hidden input save_data . The query result is directed to an invisible <iframe> .
<form action="save.php" method="post" target="save_target" onsubmit="save();"> <input type="hidden" id="save_data" name="save_data" value="" /> </form> <iframe id="save_target" name="save_target" src="#" style="display:none; width:0; height:0; border:0px solid #fff;"> </iframe>
The JS save() function prepares the data for sending:
function save() { document.getElementById("save_data").value = ...; return true;
The PHP save.php on the server processes the POST request and loads the data:
$data = $_POST['save_data']; $size = strlen($data); $contentType = "text/plain"; // MIME type $defaultName = "x.txt"; header("Content-Type: $contentType"); header("Content-Disposition: attachment; filename=$defaultName"); header("Content-Length: $size"); echo $data;
source share