Search code examples
javascriptphphtmldebuggingfopen

PHP fopen() inside javascript logic bug


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>```

Solution

  • 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);
                  ?>