I want to save simple string data as a simple text file (.txt) on the server (together with the IP), but I cannot find any clear guideline on how to do this correctly/efficiently/safely. (Maybe I'm searching with the wrong keywords..)
Here is a code I came up with, it works well for storing but I'm not sure whether it's ideal otherwise.
<?php
ini_set("display_errors", 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// get IP
if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$user_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$user_ip = $_SERVER['REMOTE_ADDR'];
}
// sanitize IP -- not sure if necessary, but why not
$user_ip = test_input($user_ip);
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
// assign and sanitize input values
$file_name = './' . test_input($request->fname_post);
$user_data = test_input($request->results_post);
$user_data = str_replace("UNKNOWN_IP", $user_ip, $user_data);
file_put_contents($user_ip . $file_name, $user_data);
// check if successfully saved, plus sanity check for file name (extension)
if ($outcome > 500 AND substr($file_name, -4) === ".txt") {
echo "Success";
} else {
echo "Failed"; // (here I'll actually include more info, but that's not important for the main question)
}
?>
Is this a sensible and correct way to do it?
EDIT:
Some more details about the use case.
- I need to be able to rewrite the file (when the same user resends the data), hence I cannot use random file name. Randomization does happen though on the client side, so others can hardly guess the file names. Including IP in the file name is another way to make this less problematic (plus its a convenience for management reasons). Also, losing this data would not be catastrophic; when the user finalizes the whole form, the full data is saved separately in another file via
file_put_contents($file_name, $user_data, FILE_APPEND | LOCK_EX);
, so it cannot be overwritten. If there are other issues with fixed files names apart from potential overwriting, please explain. - I need to save the file as
.txt
with the content in a specific structure (as sent from the user). - Even if the data is not as expected, it should be saved, hence the
$outcome > 500
should not prevent saving, it's used only for feedback, also because, as far as I understand,$outcome
could still exist e.g. if the server space ran out and only an empty file was "stored".