Search code examples
javascriptnode.jsfs

How do I replace writeFileSync() with regular JavaScript


I want to make a PHP file without nodeJS but var fs = require('fs') does not work in regular JavaScript so fs.writeFileSync() can't work. Is there a replacement for that? My code:

<script>
fs.writeFileSync('code.php','<?php echo hi ?>')
</script>

Solution

  • I want the file to download in the same folder as the HTML file is

    It would be a major security problem if code running in a browser could arbitrary write files to servers. Google's homepage would be vandalised in a new an exciting way thirty times a second.

    You need to make an Ajax request to the server and have code running on the server process it.

    Given that you want to write PHP, you probably want to write that code in PHP in the first place.

    Don't allow the browser to send arbitrary PHP that you'll execute (that's another security risk if any visitor can write code that your server will execute).

    Working directly with files introduces a bunch of risks so, generally, you should be writing the data to a database (avoiding SQL injection), and then pulling it out on demand with another PHP script (which avoiding XSS).