Description: The web server retrieves data from file database (pdf, doc, 3d file, zip and rar) and financial program such as inventory, price, indexes, order status and so on.
I'm doing REST API PHP for the first time, I've never used this API with PHP, I am an absolute beginner to REST.
Code returns data to cooperate with a www site.
First, I will test for a product that exists.
Output code 200:get_id2.php?id=39
id "39"
caption "product01"
filename "http://localhost/photo_gallery/public/files/images/image01.jpg"
description "testing Api"
Next, I will test for a product that does not exist.
Output code 404:get_id2.php?id=99999
message "No product."
I need your opinions.
- Are there any code smells (can it be done better)?
- Better to use prepared statement or not?
- Use htmlspecialchars and urlencode for output?
- What is good practice for REST API (PHP)?
Thank you in advance for your opinion.
File: get_id2.php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8");
include_once('config_setup.php');
//$id = $_GET['id'];
$id = isset($_GET['id']) ? $_GET['id'] : die();
$sql = "SELECT * ";
$sql .= "FROM photographs ";
$sql .= "WHERE id='" . db_escape($db, $id) . "'";
$result = mysqli_query($db, $sql);
confirm_db_connect($result);
$url = 'http://localhost/photo_gallery/public/files/images/';
$allowed_tags = '<div><img><h1><h2><p><br><strong><em><ul><li><table><td><tr><th><tbody>';
$photo = mysqli_fetch_assoc($result);
$id = $photo['id'];
$caption = $photo['caption'];
$filename = $photo['filename'];
$description2 = $photo['description2'];
if ($photo['caption'] != null) {
// create array
$product_arr = array(
"id" => u(h($id)),
"caption" => h($caption),
"filename" => $url . h($filename),
"description2" => strip_tags($description2, $allowed_tags)
);
// set response code - 200 OK
http_response_code(200);
echo json_encode( $product_arr );
} else {
// set response code - 404 Not found
http_response_code(404);
// tell the user product does not exist
echo json_encode(array("message" => "No product."));
}
mysqli_free_result($result);
db_disconnect($db);
Functions
function h($string="") {
return htmlspecialchars($string);
}
function u($string="") {
return urlencode($string);
}
function confirm_result_set($result_set) {
if (!$result_set) {
exit("Database query failed.");
}
}
function db_escape($connection, $string) {
return mysqli_real_escape_string($connection, $string);
}
function db_disconnect($connection) {
if(isset($connection)) {
mysqli_close($connection);
}
}