Mar 16, 2026

I recently had a client whose project required putting a basic REST API in place to handle data-oriented requests. The target language was PHP for a LAMP deployment. Here is a basic PHP "Hello, World" REST API endpoint example that includes CORS with an allowed list.

<?php
$allowed_origins = [
  'https://example.com',
  'https://www.example.com',
];

// CORS headers — only enforced when browser sends an Origin header (cross-origin requests).
// Empty origin means same-origin browser request or a non-browser client (curl, etc.).
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if ($origin !== '') {
  if (in_array($origin, $allowed_origins, true)) {
    header("Access-Control-Allow-Origin: {$origin}");
    header("Vary: Origin");
  } else {
    http_response_code(403);
    header("Content-Type: application/json; charset=UTF-8");
    echo json_encode(['error' => 'Origin not allowed']);
    exit;
  }
}
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

// Handle CORS preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  http_response_code(204);
  exit;
}

// Check method
$method = $_SERVER['REQUEST_METHOD'];

// Handle GET
if ($method === 'GET') {
  header("Content-Type: text/plain; charset=UTF-8");
  $name = isset($_GET['name']) && $_GET['name'] !== '' ? $_GET['name'] : null;
  echo $name ? "Hello, {$name}" : "Hello, World";
  exit;
}

// Handle POST
if ($method === 'POST') {
  header("Content-Type: application/json; charset=UTF-8");
  $raw = file_get_contents('php://input');
  $data = json_decode($raw, true);
  $name = isset($data['name']) && $data['name'] !== '' ? $data['name'] : null;
  echo json_encode(['message' => $name ? "Hello, {$name}" : "Hello, World"]);
  exit;
}

// Other methods not allowed
header("Content-Type: application/json; charset=UTF-8");
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
Back to Notes