I am trying to write a simple PHP script that writes a string to .txt file.
Simple. For that I have this:
<?php
if(isset(isset($_GET["fileName"]) == true && isset($_GET["output"]) == true){
$fp = fopen($_GET["fileName"], "a+");
if($fp !== null){
fputs($fp, $_GET["output"] . "\r\n");
fclose($fp);
}
}
?>
But I really need to be able to save to a specific location, so I have written this:
<?php
if(isset($_GET["filePath"]) == true && isset($_GET["fileName"]) == true && isset($_GET["output"]) == true){
$fp = fopen($_GET["filePath"] . $_GET["fileName"], "a+");
if($fp !== null){
fputs($fp, $_GET["output"] . "\r\n");
fclose($fp);
}
}
?>
But of course, this doesn’t work.
1. How can I save to a specific location with PHP?
2. Can this path be a relative path? (i just send “/output/” and the save would be done as expected).
Thank you.
Now I am here:
<?php
if(isset($_GET["filePath"]) && isset($_GET["fileName"]) && isset($_GET["output"])){
$filename=preg_replace('/[^a-z0-9]/i', '', $_GET['fileName']).'.txt';
$filepathSanitized='http://thepathtomywebsite/~subdomain/'.$_GET["filePath"].$filename;
echo $filepathSanitized; // i get the correct path, but no file is present there
$fp = fopen($_GET["filepathSanitized"], "a+");
if($fp !== null){
fputs($fp, $_GET["output"] . "\r\n");
fclose($fp);
}
else echo ('Something wrong'); // it never gets to this
}
?>
And i am calling the above like this:
$.get("save_me.php", { filePath: "demo/", fileName: "text", output: 'thing to write into' });
But no file is created. I don’t know what to debug to find out what goes wrong.
Thank you.
You should debug the argument that is passed to fopen().