PHP code to receive data on the server

Note that:

  • Throughout all the examples, this file is given the name save_data.php.

  • The line $outfile = fopen($path, FILE_APPEND); opens the file in “append” mode, which means results will always be appended to the file. If you want this code to always write a new file, possibly replacing the old one, remove FILE_APPEND (and the comma before it).

<?php
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$username = explode("/", dirname(__FILE__))[2];
$server_data = '/home/'.$username.'/server_data';
$path = $server_data."/".$obj["filename"];
if (substr(realpath(dirname($path)), 0, strlen($server_data))!=$server_data) {
    error_log("attempt to write to bad path: ".$path);
} else {
    file_put_contents($path, $obj["filedata"], FILE_APPEND);
}
?>