I could need some help securing some data transfers and I'm not familiar with ajax and php. Sorry for mistakes, happy to receive some more help.
In an ajax action, users share (send POST-) data to a write.php script. The data contains a randomized foldername (shared foldername) and some values that get written to a txt file inside the foldername. The index.html file will get copied to the share-folder and a string replaced with a shared data value. A read.php script gets copied to the share-folder as well, so the values can be computed for other users, once they open the index.html inside the share-folder.
I tried to sanitize through regex count and test_input function and setting a basepath. The script works but I'm not sure if all this is correct and enough protection to prevent malicious attacks? Making and copying folders and files, replacing strings, all this makes me get stomach ache... I'd be happy if someone could suggest edits.
Thanks!
write.php receiving $foldername, $value1, $value2:
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST['foldername'],$_POST['value1'],$_POST['value2'])){
$foldername = test_input($_POST['foldername']);
$value1 = test_input($_POST['value1']);
$value2 = test_input($_POST['value2']);
$regex_foldername = "/^([a-z]{10})$/";
$regex_value1 = "/^([a-z]{5})$/";
$regex_value2 = "/^([a-z]{5})$/";
preg_match($regex_foldername, $foldername, $matches);
$result = count($matches) > 0;
preg_match($regex_value1, $value1, $matches);
$result = $result + (count($matches) > 0);
preg_match($regex_value2, $value2, $matches);
$result = $result + (count($matches) > 0);
if($result == 3){
$basepath = '/var/www/abc/basepath/';
mkdir($basepath . 'share/' . $foldername, 0755);
$sharepath = $basepath . 'share/' . $foldername . '/';
copy($basepath . "index.html", $sharepath . "index.html");
copy($basepath . "read.php", $sharepath . "read.php");
$newindex = $sharepath . "index.html";
$oldcodetl = file_get_contents($newindex);
$strtl = str_replace("no_value_set", $value1,$oldcodetl,$resulttl);
$myfiletl = fopen($newindex, "w");
fwrite($myfiletl, $strtl);
$file = $sharepath . 'file.txt';
if (is_readable($file)) {
file_get_contents($file);
}
file_put_contents($file, "$value1;$value2;\n", FILE_APPEND);
}
}
die();
?>