PHP

Configuring Cross-Origin Resource Sharing (CORS) in PHP

Properly configure CORS in your PHP application to control which external origins can access your resources, preventing cross-domain security issues.

<?php
header("Access-Control-Allow-Origin: https://example.com"); // Restrict to a specific origin
// header("Access-Control-Allow-Origin: *"); // ALLOWS ALL ORIGINS - Use with caution!

header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); // Allowed methods
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With"); // Allowed headers
header("Access-Control-Allow-Credentials: true"); // Allow sending cookies/auth headers
header("Access-Control-Max-Age: 86400"); // Cache preflight requests for 24 hours

// Handle preflight requests (OPTIONS method)
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

// Your actual API logic goes here
echo json_encode(['message' => 'Data from secure PHP API']);
?>
How it works: This PHP snippet demonstrates how to configure Cross-Origin Resource Sharing (CORS) using HTTP headers. `Access-Control-Allow-Origin` specifies which origins are permitted to make requests; using `*` is convenient but less secure. `Access-Control-Allow-Methods` lists accepted HTTP methods, and `Access-Control-Allow-Headers` specifies headers that can be sent. `Access-Control-Allow-Credentials` allows cookies and HTTP authentication. `Access-Control-Max-Age` caches preflight `OPTIONS` requests. The `if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS')` block ensures preflight requests are handled correctly without executing main API logic.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs