How to handle CORS (Cross-Origin Resource Sharing) in PHP
Oct 12, 2025 am 12:24 AMProperly setting up CORS requires sending allowed origins, methods, and headers, handling preflight requests, and supporting credentials when needed. Specifically: use header() to set header information such as Access-Control-Allow-Origin, return 200 status code for OPTIONS requests, avoid using wildcards in the production environment, and verify and limit specific sources to ensure safe and reliable communication between the front and back ends.
When building web applications that involve sending requests from a frontend (like JavaScript in a browser) to a backend on a different domain, you'll likely run into CORS (Cross-Origin Resource Sharing) issues. These are security features enforced by browsers to prevent unauthorized cross-origin requests. In PHP, handling CORS properly means setting the correct HTTP headers so that your API allows safe access from specified origins.
Set Basic CORS Headers
To allow cross-origin requests, your PHP script needs to send specific headers before any output. The most important one is Access-Control-Allow-Origin , which defines which domains can access your resources.
Add these lines at the top of your PHP file (or in a middleware/bootstrap file if using a framework):
header("Access-Control-Allow-Origin: https://yourfrontend.com"); header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); header("Access-Control-Allow-Headers: Content-Type, Authorization");
If you're in development and want to allow all origins (not recommended for production), use:
header("Access-Control-Allow-Origin: *");
Handle Preflight OPTIONS Requests
Browsers send an OPTIONS request (preflight) before certain types of requests (eg, those with custom headers or methods like PUT/DELETE). Your PHP script must respond to these correctly.
Add this check at the beginning of your script:
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }
This returns a 200 OK response for preflight checks without executing the rest of your logic.
Include Credentials (If Needed)
If your frontend sends cookies or uses authentication (eg, withCredentials: true in fetch), you need additional configuration.
On the client side:
fetch('https://yourapi.com/data', { method: 'GET', credentials: 'include' });
On the server side, update your headers:
header("Access-Control-Allow-Origin: https://yourfrontend.com"); header("Access-Control-Allow-Credentials: true");
Note: When allowing credentials, you cannot use * for Access-Control-Allow-Origin . You must specify the exact origin.
Centralize CORS Logic
Instead of repeating CORS headers across multiple files, place them in a single entry point (eg, index.php or api.php) or use a middleware pattern.
Example of a simple CORS setup at the top of your API entry:
// cors.php or at start of API script $allowedOrigins = ['https://yourfrontend.com', 'https://admin.yoursite.com']; $origin = $_SERVER['HTTP_ORIGIN'] ?? ''; if (in_array($origin, $allowedOrigins)) { header("Access-Control-Allow-Origin: $origin"); } header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); header("Access-Control-Allow-Headers: Content-Type, Authorization"); header("Access-Control-Allow-Credentials: true"); if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit(); }
Handling CORS in PHP comes down to sending the right headers and responding properly to preflight requests. Keep it secure by avoiding wildcard origins in production and validating incoming origins explicitly. With these steps, your PHP backend will work smoothly with modern frontend applications.
Basically just set headers early, handle OPTIONS, and validate origins — not complex, but easy to get wrong.
The above is the detailed content of How to handle CORS (Cross-Origin Resource Sharing) in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Usefilter_var()tovalidateemailsyntaxandcheckdnsrr()toverifydomainMXrecords.Example:$email="user@example.com";if(filter_var($email,FILTER_VALIDATE_EMAIL)&&checkdnsrr(explode('@',$email)[1],'MX')){echo"Validanddeliverableemail&qu

Useunserialize(serialize($obj))fordeepcopyingwhenalldataisserializable;otherwise,implement__clone()tomanuallyduplicatenestedobjectsandavoidsharedreferences.

Usearray_merge()tocombinearrays,overwritingduplicatestringkeysandreindexingnumerickeys;forsimplerconcatenation,especiallyinPHP5.6 ,usethesplatoperator[...$array1,...$array2].

NamespacesinPHPorganizecodeandpreventnamingconflictsbygroupingclasses,interfaces,functions,andconstantsunderaspecificname.2.Defineanamespaceusingthenamespacekeywordatthetopofafile,followedbythenamespacename,suchasApp\Controllers.3.Usetheusekeywordtoi

ToupdateadatabaserecordinPHP,firstconnectusingPDOorMySQLi,thenusepreparedstatementstoexecuteasecureSQLUPDATEquery.Example:$pdo=newPDO("mysql:host=localhost;dbname=your_database",$username,$password);$sql="UPDATEusersSETemail=:emailWHER

The__call()methodistriggeredwhenaninaccessibleorundefinedmethodiscalledonanobject,allowingcustomhandlingbyacceptingthemethodnameandarguments,asshownwhencallingundefinedmethodslikesayHello().2.The__get()methodisinvokedwhenaccessinginaccessibleornon-ex

Usepathinfo($filename,PATHINFO_EXTENSION)togetthefileextension;itreliablyhandlesmultipledotsandedgecases,returningtheextension(e.g.,"pdf")oranemptystringifnoneexists.

Use the ZipArchive class to create a ZIP file. First instantiate and open the target zip, add files with addFile, support custom internal paths, recursive functions can package the entire directory, and finally call close to save to ensure that PHP has write permissions.
