简体   繁体   中英

How to save html code generated in php?

I am using the php to generate some html codes

It is in the now ,

<textarea>
<html>
....
</html>
</textarea>

what i would like to do is create a button 'save as html'

When i press on it, it has a windows save as dialog, allow user choose the place to store,

then save to that place when confirm (the dialog should not be create by me, using the windows one.)

Is the workflow is : first i saved a temp html file in my server, then the user open dialog, (I do not need to worry about the 'saving to part' , just need to specific the temp html file path), and when the user close, i delete the temp file. So , how can it be realize? thanks

Thank you again.

You cannot just put an <html> tag into a <textarea> tag, it does not work that way.

I would suggest you use a premade solution such as TinyMCE which will take care of most things for you. Also use something like HTML Purifier to sanitize user input before you save it, as someone could save a malicious script.

The TinyMCE websites has lots of example on how to use it.

You can do that using php header function, like this (assuming your html is posted to this page:

<?php

header('Content-Disposition: attachment; filename="filename.html"');
echo $_POST['html'];
?>

set this php page to be the target of that form and i guess you will be done

EDIT: but you should watch out for possible XSS attacks like Damien Pirsy noted in the comment, you always can sanitize the input though, strip things that are not needed like scripts.

PHP is on the server-side don't forget. Once the page is generated, it is on the client. I think it makes more sense to do this sort of thing with javascript, although you could also post the data to a PHP page which would then obtain the data.

Send the 'input' data to a PHP page by POST method:

<form action="savedata.php">
     <input id="someElement" name="someElementName" type="textarea" />
     <input type="submit" />
</form>

Receive it on the PHP end:

# savedata.php

$inputdata = $_POST["someElementName"];
$filename = "somefile.html";
file_put_contents($filename, $inputdata);

Then you could have a link in PHP to download the file.

echo "<a href='".$filename."'>Right-click, Save Target As...</a>";

After that you can delete the file from your server like this:

unlink($filename);

To open a save file dialog - redirect to the file, your browser should open up a save file dialog:

header('Content-type: text/plain'); 
header('Content-disposition: attachment; filename="$filename"'); 

To view a preview of the file, make an iframe:

echo "<iframe src='$filename' width=600 height=200 frameborder=0 />";

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