Build an explicit allowlist-based CORS layer with preflight responses. The examples separate the essential operation from the conditions a production implementation must enforce.
What It Does
Build an explicit allowlist-based CORS layer with preflight responses.
Prerequisites
Use a dedicated development environment with test accounts and records. Separate authorization, validation and error handling from response formatting; never copy demonstration-only secrets into production.
Example 1: Core Behavior
This scenario applies the exact rule described in the guide, with controlled sample values.
<?php
$origin="https://app.example.test"; $allow=["https://app.example.test"]; if(in_array($origin,$allow,true)){header("Access-Control-Allow-Origin: ".$origin);header("Vary: Origin");}
Example 2: Alternative or Failure Case
This scenario applies the exact rule described in the guide, with controlled sample values.
<?php
$method="OPTIONS"; $allowedHeaders=["Content-Type","Authorization"]; if($method==="OPTIONS"){http_response_code(204);header("Access-Control-Allow-Headers: ".implode(", ",$allowedHeaders));}
Practical Example: Applying the Rule
This scenario applies the exact rule described in the guide, with controlled sample values.
<?php
$allowCredentials=true; $origin="https://app.example.test"; if($allowCredentials){header("Access-Control-Allow-Origin: ".$origin);header("Access-Control-Allow-Credentials: true");header("Vary: Origin");}
Important Behavior and Edge Cases
Handle Vary: Origin for cache correctness and verify requested methods and headers.
Comparison with Related Functions or Patterns
| Approach | When it differs |
|---|---|
| Implementing CORS for PHP APIs | Build an explicit allowlist-based CORS layer with preflight responses. |
| Related API or pattern | A reverse proxy can enforce the same CORS policy outside PHP. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Combining wildcard origins with credentialed cross-origin browser requests | Handle Vary: Origin for cache correctness and verify requested methods and headers. |
| Substituting a related API without checking its semantics | A reverse proxy can enforce the same CORS policy outside PHP. |
Key Takeaways
- Build an explicit allowlist-based CORS layer with preflight responses.
- Handle Vary: Origin for cache correctness and verify requested methods and headers.
- A reverse proxy can enforce the same CORS policy outside PHP.
Select this API or pattern based on its documented behavior and the trust boundaries in your own application, and test all external integrations against their actual deployments.