Advertisement
Hennotaht

vs17-veebiteenused

Sep 18th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.21 KB | None | 0 0
  1. <?php
  2.  
  3. use PASVL\Traverser\VO\Traverser;
  4. use PASVL\ValidatorLocator\ValidatorLocator;
  5.  
  6. require __DIR__ . '/vendor/autoload.php';
  7. $request_method = $_SERVER['REQUEST_METHOD'];
  8. $endpoint = getEndpoint();
  9. $request_body = file_get_contents('php://input');
  10.  
  11. connectDatabase();
  12. switch ($endpoint) {
  13.     case '/pet':
  14.  
  15.         $request_body = json_decode($request_body, true);
  16.         $pet_name = $request_body['name'];
  17.  
  18.         // Validate input
  19.         $traverser = new Traverser(new ValidatorLocator());
  20.         if (!$traverser->check([
  21.             'name' => ':string',
  22.             'id' => ':int',
  23.             'status' => ':string',
  24.             'category' => ['id'=>':int','name'=>':string'],
  25.             'tags' => ['*'=>['id'=>':int','name'=>':string']],
  26.             'photoUrls' => ['*'=>[':int'=>':string']]
  27.         ],
  28.             $request_body)) {
  29.             header("HTTP/1.0 405 Invalid input");
  30.             die();
  31.         }
  32.  
  33.         // Insert data into database
  34.         insert('pets', ['pet_name' => $pet_name]);
  35. }
  36. function getEndpoint()
  37. {
  38.     $project_directory = dirname($_SERVER['SCRIPT_NAME']);
  39.     $project_directory_length = strlen($project_directory);
  40.     $endpoint = substr($_SERVER['REQUEST_URI'], $project_directory_length);
  41.     return $endpoint;
  42. }
  43.  
  44. function connectDatabase()
  45. {
  46.     global $conn;
  47.     $servername = "localhost";
  48.     $username = "admin";
  49.     $password = "asdfasdf";
  50.  
  51.     // Create connection
  52.     $conn = new mysqli($servername, $username, $password);
  53.  
  54.     // Check connection
  55.     if ($conn->connect_error) {
  56.         die("Connection failed: " . $conn->connect_error);
  57.     }
  58.  
  59.     // select database
  60.     if (!mysqli_select_db($conn, 'api')) {
  61.         die("Uh oh, couldn't select database ");
  62.     }
  63. }
  64.  
  65. function insert($table, $data)
  66. {
  67.     global $conn;
  68.     foreach ($data as $field_name => $field_value) {
  69.         $field_value = addslashes($field_value);
  70.         $fields[] = "$field_name = '$field_value'";
  71.     }
  72.     $fields = implode(',', $fields);
  73.     $sql = "INSERT INTO $table SET $fields";
  74.  
  75.     if ($conn->query($sql) === TRUE) {
  76.         echo "New record created successfully";
  77.     } else {
  78.         echo "Error: " . $sql . "<br>" . $conn->error;
  79.     }
  80. }
  81.  
  82. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement