I am trying to send some text from my webpage to a webserver and save it within a file but I can't seem to get it working and I don't have any errors being produced to tell me why.
I'm trying to use JavaScript to send a post request to the server and then have the PHP process the request and save the contents into a file. The code I'm using is below:
JavaScript
function sendCode() {
const copyCode = document.getElementById("terraCode").textContent;
const textArea = document.createElement('textarea');
textArea.textContent = copyCode; //The text being sent
var code = new FormData();
code.append("code", copyCode);
var xhr = new XMLHttpRequest();
xhr.open('post', './test.php', true); //Request and location of PHP
xhr.send(code);
}
document.getElementById("TestCode").addEventListener("click", sendCode); //Execute function above based on button click
PHP
<?php
if (!empty($_POST['code'])) {
$data = $_POST['code'];
$fname = "test" . ".tf"; //generates file name
$file = fopen("./file" . $fname, 'w'); //creates new file
fwrite($file, $data);
fclose($file);
}
?>
I am pretty confident it is getting the text correctly as it is present when I check inspect element on the page, but nothing seems to be happening server side and I'm not sure if the data is even reaching the server.
Can anyone explain why this wouldn't be working?
Edit:
I'm running an Nginx web server and PHP7.4 is installed and enabled on the server
question from:
https://stackoverflow.com/questions/66065459/trying-to-send-file-to-webserver-from-webpage 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…