save-canvas.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /* Receives the email of the user, the name of the canvas and the date
  3. and stores it in the database with a randomly-generated canvas_id,
  4. that is returned. */
  5. session_start();
  6. $params = array();
  7. parse_str($_POST['save_canvas'], $params);
  8. if(!array_key_exists('email_save_canvas', $params) OR
  9. !array_key_exists('name_save_canvas', $params) OR
  10. !array_key_exists('date_save_canvas', $params)) {
  11. echo 400; // Missing parameters
  12. }
  13. else {
  14. if(isset($_SESSION['canvas_id'])) {
  15. // Canvas already exists. Return canvas_id to overwrite JSON file.
  16. echo $_SESSION['canvas_id'];
  17. }
  18. else { // New canvas in the database
  19. // Retrieve user credentials
  20. $email = $params['email_save_canvas'];
  21. $canvas_name = $params['name_save_canvas'];
  22. $date = $params['date_save_canvas'];
  23. require_once('../../../php/db_utils.php');
  24. $conn = db_connect(); // Connect to the database
  25. // Check if the username already exists
  26. if(!($result = mysqli_query($conn, "SELECT name FROM user WHERE username = '$email'"))) {
  27. echo 400; // Wrong query
  28. }
  29. else if(mysqli_num_rows($result) != 1) { // User not registered or duplicated
  30. echo 401;
  31. }
  32. else { // User registered
  33. // Save this canvas
  34. $canvas_id = generateRandomString();
  35. if(!mysqli_query($conn, "INSERT INTO canvas (canvas_id, user_id, canvas_name, canvas_date) VALUES ('$canvas_id', '$email', '$canvas_name', '$date')")) {
  36. echo 400; // Wrong query
  37. echo " #Wrong query :/ ";
  38. }
  39. else { // Return canvas_id and save it in the current session
  40. $_SESSION['canvas_id'] = $canvas_id;
  41. echo $canvas_id;
  42. }
  43. }
  44. }
  45. }
  46. /* Generate a random string of a specific length to be used as canvas_id */
  47. function generateRandomString($length = 10) {
  48. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  49. $charactersLength = strlen($characters);
  50. $randomString = '';
  51. for ($i = 0; $i < $length; $i++) {
  52. $randomString .= $characters[rand(0, $charactersLength - 1)];
  53. }
  54. return $randomString;
  55. }
  56. ?>