0

I want to create a text file stole to localhost directory. below is my code.

below app.php

            document.getElementById("save_button").addEventListener("click", function() {
          
              var content =  document.getElementById("final_span").value();

              var file_name =document.getElementById("filename").value();
              <?php
              $fn = strstr($file_name,'.', true);

              $dir = "../project/Record";

              $file = fopen($dir."/".$fn.".txt","w+");

              fwrite($file, $content);

              fclose($file);
              ?>
            });
      </script>```
1
  • You make some misunderstanding with server side code and client side code... Commented Jan 24, 2021 at 6:07

1 Answer 1

1

Your js will execute in browser and php is server side language. You can't control php within js as you've done. You can do it by ajax call from you js to php file and create a file.

    <script>  document.getElementById("save_button").addEventListener("click", function() {
              
                  var content =  document.getElementById("final_span").value;
    
                  var file_name =document.getElementById("filename").value;
    
    var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;
          }
        };
        xmlhttp.open("GET", "app.php?file_name=" + file_name, true);
        xmlhttp.send();
    
    </script>

app.php

<?php $file_name= $_GET['file_name'];
              $fn = strstr($file_name,'.', true);

              $dir = "../project/Record";

              $file = fopen($dir."/".$fn.".txt","w+");

              fwrite($file, $content);

              fclose($file);
              ?>
Sign up to request clarification or add additional context in comments.

6 Comments

why no respond on app.php ? this.readyState == 4 && this.status == 200 it is true
you can echo any response you want but it seems you didn't set any response message.
Okay solve thank you. if i also want to pass the var content = document.getElementById("final_span").value(); also ?
Pls replace with below line "app.php?file_name=" + file_name +"&content="+content
can hide the content ? not send with this method?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.