Current directory: /home/klas4s23/domains/585455.klas4s23.mid-ica.nl/public_html/Gastenboek/uploads
<?php
/**
* Complete REST API with CRUD Operations
* Supports: Users and Products endpoints
*/
// Enable CORS
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Content-Type: application/json');
// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
// Include configuration
require_once 'config.php';
// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
try {
// Get database connection
$db = Database::getInstance()->getConnection();
// Parse the request
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$pathParts = explode('/', trim($path, '/'));
// Remove 'api' from path if present
if ($pathParts[0] === 'api') {
array_shift($pathParts);
}
$resource = $pathParts[0] ?? '';
$id = $pathParts[1] ?? null;
// Get request body for POST/PUT requests
$input = json_decode(file_get_contents('php://input'), true);
// Route the request
switch ($resource) {
case 'users':
handleUsersAPI($db, $method, $id, $input);
break;
case 'products':
handleProductsAPI($db, $method, $id, $input);
break;
case 'health':
echo ApiResponse::success(['status' => 'OK', 'database' => 'Connected'], 'API is healthy');
break;
default:
echo ApiResponse::error('Invalid endpoint. Available: /users, /products, /health', 404);
break;
}
} catch (Exception $e) {
echo ApiResponse::error('Internal server error: ' . $e->getMessage(), 500);
}
/**
* Handle Users API endpoints
*/
function handleUsersAPI($db, $method, $id, $input) {
switch ($method) {
case 'GET':
if ($id) {
// Get single user
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
$user = $stmt->fetch();
if ($user) {
echo ApiResponse::success($user, 'User retrieved successfully');
} else {
echo ApiResponse::error('User not found', 404);
}
} else {
// Get all users with pagination
$page = $_GET['page'] ?? 1;
$limit = $_GET['limit'] ?? 10;
$offset = ($page - 1) * $limit;
// Get total count
$countStmt = $db->query("SELECT COUNT(*) as total FROM users");
$total = $countStmt->fetch()['total'];
// Get users
$stmt = $db->prepare("SELECT * FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?");
$stmt->execute([$limit, $offset]);
$users = $stmt->fetchAll();
echo ApiResponse::success([
'users' => $users,
'pagination' => [
'page' => (int)$page,
'limit' => (int)$limit,
'total' => (int)$total,
'pages' => ceil($total / $limit)
]
], 'Users retrieved successfully');
}
break;
case 'POST':
// Create new user
if (!$input) {
echo ApiResponse::error('Invalid JSON input', 400);
return;
}
// Validate required fields
$errors = [];
if (!Validator::validateRequired($input['name'] ?? '')) {
$errors[] = 'Name is required';
}
if (!Validator::validateEmail($input['email'] ?? '')) {
$errors[] = 'Valid email is required';
}
if (!empty($errors)) {
echo ApiResponse::error('Validation failed', 400, $errors);
return;
}
try {
$stmt = $db->prepare("INSERT INTO users (name, email, phone) VALUES (?, ?, ?)");
$stmt->execute([
$input['name'],
$input['email'],
$input['phone'] ?? null
]);
$newId = $db->lastInsertId();
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$newId]);
$newUser = $stmt->fetch();
echo ApiResponse::success($newUser, 'User created successfully', 201);
} catch (PDOException $e) {
if ($e->getCode() == 23000) {
echo ApiResponse::error('Email already exists', 409);
} else {
echo ApiResponse::error('Database error: ' . $e->getMessage(), 500);
}
}
break;
case 'PUT':
// Update user
if (!$id) {
echo ApiResponse::error('User ID is required', 400);
return;
}
if (!$input) {
echo ApiResponse::error('Invalid JSON input', 400);
return;
}
// Check if user exists
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
if (!$stmt->fetch()) {
echo ApiResponse::error('User not found', 404);
return;
}
// Validate email if provided
if (isset($input['email']) && !Validator::validateEmail($input['email'])) {
echo ApiResponse::error('Invalid email format', 400);
return;
}
try {
$fields = [];
$values = [];
if (isset($input['name'])) {
$fields[] = "name = ?";
$values[] = $input['name'];
}
if (isset($input['email'])) {
$fields[] = "email = ?";
$values[] = $input['email'];
}
if (isset($input['phone'])) {
$fields[] = "phone = ?";
$values[] = $input['phone'];
}
if (empty($fields)) {
echo ApiResponse::error('No fields to update', 400);
return;
}
$values[] = $id;
$sql = "UPDATE users SET " . implode(", ", $fields) . " WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute($values);
// Return updated user
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
$updatedUser = $stmt->fetch();
echo ApiResponse::success($updatedUser, 'User updated successfully');
} catch (PDOException $e) {
if ($e->getCode() == 23000) {
echo ApiResponse::error('Email already exists', 409);
} else {
echo ApiResponse::error('Database error: ' . $e->getMessage(), 500);
}
}
break;
case 'DELETE':
// Delete user
if (!$id) {
echo ApiResponse::error('User ID is required', 400);
return;
}
// Check if user exists
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
$user = $stmt->fetch();
if (!$user) {
echo ApiResponse::error('User not found', 404);
return;
}
$stmt = $db->prepare("DELETE FROM users WHERE id = ?");
$stmt->execute([$id]);
echo ApiResponse::success($user, 'User deleted successfully');
break;
default:
echo ApiResponse::error('Method not allowed', 405);
break;
}
}
/**
* Handle Products API endpoints
*/
function handleProductsAPI($db, $method, $id, $input) {
switch ($method) {
case 'GET':
if ($id) {
// Get single product
$stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$id]);
$product = $stmt->fetch();
if ($product) {
echo ApiResponse::success($product, 'Product retrieved successfully');
} else {
echo ApiResponse::error('Product not found', 404);
}
} else {
// Get all products with filtering and pagination
$page = $_GET['page'] ?? 1;
$limit = $_GET['limit'] ?? 10;
$category = $_GET['category'] ?? null;
$minPrice = $_GET['min_price'] ?? null;
$maxPrice = $_GET['max_price'] ?? null;
$offset = ($page - 1) * $limit;
// Build WHERE clause
$where = [];
$params = [];
if ($category) {
$where[] = "category = ?";
$params[] = $category;
}
if ($minPrice) {
$where[] = "price >= ?";
$params[] = $minPrice;
}
if ($maxPrice) {
$where[] = "price <= ?";
$params[] = $maxPrice;
}
$whereClause = !empty($where) ? "WHERE " . implode(" AND ", $where) : "";
// Get total count
$countSql = "SELECT COUNT(*) as total FROM products $whereClause";
$countStmt = $db->prepare($countSql);
$countStmt->execute($params);
$total = $countStmt->fetch()['total'];
// Get products
$sql = "SELECT * FROM products $whereClause ORDER BY created_at DESC LIMIT ? OFFSET ?";
$params[] = $limit;
$params[] = $offset;
$stmt = $db->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll();
echo ApiResponse::success([
'products' => $products,
'pagination' => [
'page' => (int)$page,
'limit' => (int)$limit,
'total' => (int)$total,
'pages' => ceil($total / $limit)
]
], 'Products retrieved successfully');
}
break;
case 'POST':
// Create new product
if (!$input) {
echo ApiResponse::error('Invalid JSON input', 400);
return;
}
// Validate required fields
$errors = [];
if (!Validator::validateRequired($input['name'] ?? '')) {
$errors[] = 'Name is required';
}
if (!Validator::validateNumeric($input['price'] ?? '')) {
$errors[] = 'Valid price is required';
}
if (!Validator::validateNumeric($input['stock'] ?? '')) {
$errors[] = 'Valid stock number is required';
}
if (!empty($errors)) {
echo ApiResponse::error('Validation failed', 400, $errors);
return;
}
try {
$stmt = $db->prepare("INSERT INTO products (name, description, price, stock, category) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([
$input['name'],
$input['description'] ?? null,
$input['price'],
$input['stock'],
$input['category'] ?? null
]);
$newId = $db->lastInsertId();
$stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$newId]);
$newProduct = $stmt->fetch();
echo ApiResponse::success($newProduct, 'Product created successfully', 201);
} catch (PDOException $e) {
echo ApiResponse::error('Database error: ' . $e->getMessage(), 500);
}
break;
case 'PUT':
// Update product
if (!$id) {
echo ApiResponse::error('Product ID is required', 400);
return;
}
if (!$input) {
echo ApiResponse::error('Invalid JSON input', 400);
return;
}
// Check if product exists
$stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$id]);
if (!$stmt->fetch()) {
echo ApiResponse::error('Product not found', 404);
return;
}
try {
$fields = [];
$values = [];
if (isset($input['name'])) {
$fields[] = "name = ?";
$values[] = $input['name'];
}
if (isset($input['description'])) {
$fields[] = "description = ?";
$values[] = $input['description'];
}
if (isset($input['price'])) {
$fields[] = "price = ?";
$values[] = $input['price'];
}
if (isset($input['stock'])) {
$fields[] = "stock = ?";
$values[] = $input['stock'];
}
if (isset($input['category'])) {
$fields[] = "category = ?";
$values[] = $input['category'];
}
if (empty($fields)) {
echo ApiResponse::error('No fields to update', 400);
return;
}
$values[] = $id;
$sql = "UPDATE products SET " . implode(", ", $fields) . " WHERE id = ?";
$stmt = $db->prepare($sql);
$stmt->execute($values);
// Return updated product
$stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$id]);
$updatedProduct = $stmt->fetch();
echo ApiResponse::success($updatedProduct, 'Product updated successfully');
} catch (PDOException $e) {
echo ApiResponse::error('Database error: ' . $e->getMessage(), 500);
}
break;
case 'DELETE':
// Delete product
if (!$id) {
echo ApiResponse::error('Product ID is required', 400);
return;
}
// Check if product exists
$stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$id]);
$product = $stmt->fetch();
if (!$product) {
echo ApiResponse::error('Product not found', 404);
return;
}
$stmt = $db->prepare("DELETE FROM products WHERE id = ?");
$stmt->execute([$id]);
echo ApiResponse::success($product, 'Product deleted successfully');
break;
default:
echo ApiResponse::error('Method not allowed', 405);
break;
}
}
?>