Return explicit cross-origin response permissions and handle OPTIONS preflight requests. The examples separate the essential operation from the conditions a production implementation must enforce.
What It Does
Return explicit cross-origin response permissions and handle OPTIONS preflight requests.
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
The first example isolates the core operation so its result is easy to understand.
<?php
$origin=$_SERVER['HTTP_ORIGIN']??''; $allowed=['https://app.example.test'];
if (in_array($origin,$allowed,true)) {header('Access-Control-Allow-Origin: '.$origin); header('Vary: Origin');}
echo 'CORS policy checked';
Example 2: Alternative or Failure Case
The second example demonstrates an alternative outcome, rule or failure condition.
<?php
if (($_SERVER['REQUEST_METHOD']??'')==='OPTIONS') {header('Access-Control-Allow-Methods: GET, POST');header('Access-Control-Allow-Headers: Content-Type, Authorization');http_response_code(204);exit;}
echo 'Regular request';
Practical Example: Applying the Rule
The practical example shows how to carry the same constraint into application code.
<?php
$origin=$_SERVER['HTTP_ORIGIN']??'';
if ($origin==='https://app.example.test') {header('Access-Control-Allow-Origin: '.$origin);header('Access-Control-Allow-Credentials: true');header('Vary: Origin');}
echo 'Explicit credential origin';
Important Behavior and Edge Cases
Never combine Access-Control-Allow-Origin: * with credentialed browser requests.
Comparison with Related Functions or Patterns
| Approach | When it differs |
|---|---|
| Handling CORS for PHP APIs | Return explicit cross-origin response permissions and handle OPTIONS preflight requests. |
| Related API or pattern | CORS controls browser reads; it is not authentication or CSRF protection. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Combining wildcard origins with credentialed cross-origin browser requests | Never combine Access-Control-Allow-Origin: * with credentialed browser requests. |
| Substituting a related API without checking its semantics | CORS controls browser reads; it is not authentication or CSRF protection. |
Key Takeaways
- Return explicit cross-origin response permissions and handle OPTIONS preflight requests.
- Never combine Access-Control-Allow-Origin: * with credentialed browser requests.
- CORS controls browser reads; it is not authentication or CSRF protection.
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.