-4

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>
  • The question is not at all clear. Be more descriptive – kawadhiya21 Apr 11 '22 at 15:21
  • 1
    By "regular javascript", do you mean in a browser? – qrsngky Apr 11 '22 at 15:22
  • 2
    JavaScript has no mechanisms for writing files at all. It depends on the host environment to provide them. If you were using Node.js then Node.js would provide the `fs` module. Since you aren't using Node.js then it depends on what you are using (a ` – Quentin Apr 11 '22 at 15:23
  • That said, if you want to write a PHP file then you *probably* should be looking to write data to a database that an existing PHP file reads from. – Quentin Apr 11 '22 at 15:23
  • @qrsngky yes I want to run it in a browser – windows.sys Apr 11 '22 at 15:25
  • If your using php, you just need to return the file as a file stream using HTTP and with the correct headers. You don't need JS at all. – Liam Apr 11 '22 at 15:27
  • @Liam I want the file to download in the same folder as the HTML file is – windows.sys Apr 11 '22 at 15:27
  • 1
    That makes no sense, the HTML file is on the server, the javascript runs on the browser. the internet is inbetween... – Liam Apr 11 '22 at 15:28
  • A browser shouldn't allow it to happen. Otherwise someone can put a JS file in his homepage, and when you visit the homepage, the browser writes a file to your computer, without you even knowing. – qrsngky Apr 11 '22 at 15:29
  • @qrsngky I have a server that has a link to an HTML file – windows.sys Apr 11 '22 at 15:32

1 Answers1

0

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).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335