annotate save.php @ 824:cfe755cc2bc2

Feature #1456. PHP server adds a six character 'hash' to the end of the file.
author Nicholas Jillings <nicholas.jillings@eecs.qmul.ac.uk>
date Mon, 23 Nov 2015 16:02:37 +0000
parents 7b0ce3a9ddc1
children 1b6fa37d46a4
rev   line source
n@816 1 <?php
n@820 2 header('Access-Control-Allow-Origin: *');
n@820 3 header("Content-type: text/xml");
n@816 4 $postText = file_get_contents('php://input');
n@816 5 $datetime = date('ymdHis');
nicholas@824 6 $xmlfile = "save".$datetime."-".generateRandomString(6).".xml";
n@816 7 $fileHandle = fopen("saves/".$xmlfile, 'w');
n@820 8 if ($fileHandle == FALSE)
n@820 9 {
n@820 10 // Filehandle failed
n@820 11 $xml = '<response state="error"><message>Could not open file</message></response>';
n@820 12 echo $xml;
n@820 13 return;
n@820 14 }
n@820 15 $wbytes = fwrite($fileHandle, $postText);
n@820 16 if ($wbytes == FALSE)
n@820 17 {
n@820 18 // FileWrite failed
n@820 19 $xml = '<response state="error"><message>Could not write file "saves/'.$xmlfile.'"</message></response>';
n@820 20 echo $xml;
n@820 21 return;
n@820 22 }
n@816 23 fclose($fileHandle);
n@820 24
n@820 25 // Return JSON confirmation data
n@820 26 $xml = '<response state="OK"><message>OK</message><file bytes="'.$wbytes.'">"saves/'.$xmlfile.'"</file></response>';
n@820 27 echo $xml;
nicholas@824 28
nicholas@824 29 // Random String generator from http://stackoverflow.com/questions/4356289/php-random-string-generator
nicholas@824 30 function generateRandomString($length = 10) {
nicholas@824 31 $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
nicholas@824 32 $charactersLength = strlen($characters);
nicholas@824 33 $randomString = '';
nicholas@824 34 for ($i = 0; $i < $length; $i++) {
nicholas@824 35 $randomString .= $characters[rand(0, $charactersLength - 1)];
nicholas@824 36 }
nicholas@824 37 return $randomString;
nicholas@824 38 }
n@816 39 ?>