Advertisement
olcayertas

PHP web service that accepts JSON and return JSON

Jan 21st, 2015
365
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.98 KB | None | 0 0
  1. <?php
  2. header('Content-type: application/json; charset=utf-8');
  3.  
  4. use Psr\Log\LogLevel;
  5.  
  6. require 'vendor/autoload.php';
  7.  
  8. /**
  9.  *
  10.  * Author - Olcay Ertaş
  11.  *
  12.  */
  13. class ArendiWebServices {
  14.  
  15.     private $db;
  16.     private $host = "localhost";
  17.     private $userName = "yourUserName";
  18.     private $password = "yourPassword";
  19.     private $database = "yourDatabaseName";
  20.     private $logger;
  21.  
  22.     // Constructor - open DB connection
  23.     function __construct() {
  24.         $this->db = new mysqli($this->host, $this->userName, $this->password, $this->database);
  25.         $this->db->autocommit(FALSE);
  26.         $stmt1 = $this->db->prepare("SET NAMES 'utf8'");
  27.         $stmt1->execute();
  28.         $stmt2 = $this->db->prepare('SET CHARACTER SET "utf8"');
  29.         $stmt2->execute();
  30.         $this->logger = new Katzgrau\KLogger\Logger("log.txt", LogLevel::DEBUG);
  31.     }
  32.  
  33.     // Destructor - close DB connection
  34.     function __destruct() {
  35.         $this->db->close();
  36.     }
  37.  
  38.     /**
  39.      * Proje listesini veren method.
  40.      */
  41.     function getProjects() {
  42.         $this->logger->debug("GetProjects: Entrance\n");
  43.         $stmt = $this->db->prepare('SELECT * FROM yourProjectsTable');
  44.         $id = $no = $title = $subject = $description = $attachment = $status = NULL;
  45.         $stmt->bind_result($id, $no, $title, $subject, $description, $attachment, $status);
  46.  
  47.         if ($stmt->execute()) {
  48.             $this->logger->debug("GetProjects: If\n");
  49.             $result = array();
  50.  
  51.             while ($stmt->fetch()) {
  52.                 $row = array("id" => $id, "no" => $no, "title" => $title,
  53.                     "subject" => $subject, "description" => $description,
  54.                     "attachment" => $attachment, "status" => $status);
  55.                 $result[] = $row;
  56.             }
  57.  
  58.             echo json_encode($result);
  59.         }
  60.  
  61.         $stmt->close();
  62.         $this->logger->debug("GetProjects: Exit\n");
  63.     }
  64.  
  65.     /**
  66.      * Method for login, returns user information if user name and password are correct.
  67.      * @param type $email User email address
  68.      * @param type $password User account password.
  69.      */
  70.     function getUser($email, $password) {
  71.         $this->logger->debug("GetUser: Entrance\n");
  72.         $stmt = $this->db->prepare("SELECT * FROM yourUsersTable WHERE email=? && password=?");
  73.         $stmt->bind_param("ss", $email, $password);
  74.         $id = $companyid = $name = $surname = $email2 = $password2 = NULL;
  75.         $stmt->bind_result($id, $companyid, $name, $surname, $email2, $password2);
  76.  
  77.         if ($stmt->execute()) {
  78.             if ($stmt->fetch()) {
  79.                 $stmt->close();
  80.                 $log = $id . " - "
  81.                         . $companyid . " - "
  82.                         . $name . " - "
  83.                         . $surname . " - "
  84.                         . $email2 . " - "
  85.                         . $password2 . "\n";
  86.                 $this->logger->debug("GetUser: " . $log);
  87.                 $stmt2 = $this->db->prepare("SELECT * FROM yourCompanyTable WHERE id=" . $companyid);
  88.                 $cid = $cname = $caddress = $cphone = $cwebpage = NULL;
  89.                 $stmt2->bind_result($cid, $cname, $caddress, $cphone, $cwebpage);
  90.                 $stmt2->execute();
  91.                 $stmt2->fetch();
  92.                 $result = "{\"success\":\"1\",";
  93.                 $result = $result . "\"id\":\"" . $id . "\",";
  94.                 $result = $result . "\"companyid\":\"" . $cid . "\",";
  95.                 $result = $result . "\"companyname\":\"" . $cname . "\",";
  96.                 $result = $result . "\"name\":\"" . $name . "\",";
  97.                 $result = $result . "\"surname\":\"" . $surname . "\",";
  98.                 $result = $result . "\"email\":\"" . $email2 . "\",";
  99.                 $result = $result . "\"password\":\"" . $password2 . "\"}";
  100.                 $stmt2->close();
  101.                 echo $result;
  102.                 $log = $cid . " - "
  103.                         . $cname . " - "
  104.                         . $caddress . " - "
  105.                         . $cphone . " - "
  106.                         . $cwebpage . "\n";
  107.                 $this->logger->debug("GetUser: " . $log);
  108.             } else {
  109.                 echo "{\"success\":\"0\",\"errorMessage\":\"User name or password is wrong.\",\"email\":\"" . $email . "\",\"password\":\"" . $password . "\"}";
  110.             }
  111.         } else {
  112.             echo "{\"success\":\"0\",\"errorMessage\":\"User name or password is wrong.\"}";
  113.         }
  114.     }
  115.  
  116.     /**
  117.      * Saves new idea.
  118.      * @param 1 - companyid - User's company id.
  119.      * @param 2 - employeeid - User id
  120.      * @param 3 - title - Idea title
  121.      * @param 4 - description - Idea description.
  122.      * @param 5 - privacy - Idea visibility: 0 everbody can see,
  123.      *            1  Only people in same company can see.
  124.      * @param 6 - attachment - Atachment url
  125.      */
  126.     function saveIdea($ideaData) {
  127.         $this->logger->debug("SaveIdea: Entrance");
  128.         $data = $ideaData;
  129.         $company = $data['company'];
  130.         $employeeName = $data['employeeName'];
  131.         $employeeSurname = $data['employeeSurname'];
  132.         $title = $data['title'];
  133.         $description = $data['description'];
  134.         $privacy = intval($data['privacy']);
  135.         $vote = 0;
  136.         $attachment = $data['attachment'];
  137.         $stmt = $this->db->prepare("INSERT INTO yourIdeaTable VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?)");
  138.  
  139.         if ($stmt) {
  140.             $stmt->bind_param("sssssiis", $company, $employeeName, $employeeSurname, $title, $description, $privacy, $vote, $attachment);
  141.         } else {
  142.             echo "{\"success\":\"0\",\"error_message\":\"Error while generating query!\"}";
  143.             return;
  144.         }
  145.  
  146.         if ($stmt === FALSE) {
  147.             $code = $stmt->errorCode();
  148.             $errInfo = $stmt->errorInfo();
  149.             error_log("PREPARE of INSERT query, FAILED\nCode: $code ErrorMessage: $errInfo\n", 3, "php.log");
  150.         } else {
  151.             if ($stmt->execute()) {
  152.                 $this->logger->debug("GetUser: Idea saved!");
  153.                 echo "{\"success\":\"1\",\"success_message\":\"Idea saved.\"}";
  154.             } else {
  155.                 $code = $stmt->errorCode();
  156.                 $errInfo = $stmt->errorInfo();
  157.                 $this->logger->error("GetUser: Failed to save idea!");
  158.                 $this->logger->error("GetUser: Code: $code ErrorMessage: $errInfo\n");
  159.                 echo "{\"success\":\"0\",\"error_message\":\"Failed to save idea!\"}";
  160.             }
  161.         }
  162.     }
  163.  
  164. }
  165.  
  166. $arendiService = new ArendiWebServices();
  167. $post = file_get_contents('php://input');
  168. $post = json_decode($post, true);
  169.  
  170. $logger = new Katzgrau\KLogger\Logger("log", LogLevel::DEBUG);
  171. $logger->debug("Arendi Web Services");
  172. $logger->debug("Post data loaded");
  173. $logger->debug("Service instance created");
  174.  
  175. if (isset($post['request'])) {
  176.  
  177.     if ($post['request'] == 'login') {
  178.         $logger->debug("Requested service - login");
  179.         $logger->debug($post['userName'] . " - " . $post['password']);
  180.         $arendiService->getUser($post['userName'], $post['password']);
  181.     } else if ($post['request'] == 'getprojects') {
  182.         $logger->debug("Requested service - getprojects");
  183.         $arendiService->getProjects();
  184.     } else if ($post['request'] == 'getMenu') {
  185.         $logger->debug("Requested service - getMenu");
  186.         $arendiService->getMenu();
  187.     } else if ($post['request'] == 'saveIdea') {
  188.         $logger->debug("Requested service - saveIdea");
  189.         //error_log("Incoming data: ".$post."\n", 3, "php.log");
  190.         $arendiService->saveIdea($post);
  191.     } else {
  192.         $logger->debug("Requested service - undefined\n");
  193.         echo '{"success":0,"error_message":"Undefined service!"}';
  194.     }
  195. } else {
  196.     $logger->error("Invalid service request!");
  197.     $logger->error("Request must have a 'request' field!");
  198.     $response = '{"success":0,"error_message":"Invalid service request! Request must have a \'request\' field!"}';
  199.     $jsonResponse = json_encode($response);
  200.     echo $jsonResponse;
  201. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement