Advertisement
Guest User

Untitled

a guest
Feb 16th, 2016
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.02 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Script to query a MySQL database. This script is not safe against SQL-injection.
  4.  * Please do not use it for real applications.
  5.  *
  6.  * PHP version 5.6
  7.  *
  8.  * @category None
  9.  * @package  None
  10.  * @author   Ludger Martin <lumartin@hs-rm.de>
  11.  * @license  Apache License 2.0 http://www.apache.org/licenses/LICENSE-2.0
  12.  * @version  1.0
  13.  * @link     none
  14.  */
  15. // configuration
  16. $database = 'wba...';
  17. $dbuser = 'wba...';
  18. $dbpassword = 'password';
  19.  
  20. // handle query algorithm
  21. if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  22.  
  23.     try {
  24.         // initialize database
  25.         $db = new PDO("mysql:host=localhost;dbname=$database", $dbuser, $dbpassword);
  26.         $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  27.         $stmt = $db->prepare('SET NAMES utf8');
  28.         $stmt->execute();
  29.         $stmt = $db->prepare('SET CHARACTER SET utf8');
  30.         $stmt->execute();
  31.  
  32.         // handle post body
  33.         $body = file_get_contents('php://input');
  34.        
  35.         // execute database query
  36.         $stmt = $db->prepare($body);
  37.         $stmt->execute();
  38.         $result = $stmt->fetchAll(PDO::FETCH_CLASS);
  39.  
  40.         // encode to json
  41.         header('Content-Type: application/json; charset=utf-8');
  42.         echo json_encode($result);
  43.     } catch (Exception $e) {
  44.         // error handling
  45.         header('HTTP/1.0 500 Internal Server Error');
  46.         echo $e->getMessage();
  47.     }
  48. } else if ($_SERVER['REQUEST_METHOD'] == 'GET') {
  49.     // print documentation  
  50.     echo '<DOCTYPE html>
  51. <html>
  52. <head>
  53.    <title>MySQL Web Service</title>
  54. </head>
  55. <body>
  56.    <h1>MySQL Web Service</h1>
  57.    <p>To call this service use the <em>post</em>-method.
  58.       Provide the MySQL-query in the post body. The result will be
  59.       JSON-encoded with <em>utf-8</em> encoding.
  60.    </p>
  61.    <p>This script is not safe against SQL-injection.
  62.       Please do not use it for real applications.
  63.    </p>
  64. </body>
  65. </html>';
  66. } else {
  67.     // no other function is implemented
  68.     header('HTTP/1.0 501 Not Implemented');
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement