亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Set Basic CORS Headers
Handle Preflight OPTIONS Requests
Include Credentials (If Needed)
Centralize CORS Logic
Home Backend Development PHP Tutorial How to handle CORS (Cross-Origin Resource Sharing) in PHP

How to handle CORS (Cross-Origin Resource Sharing) in PHP

Oct 12, 2025 am 12:24 AM

Properly 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.

How to handle CORS (Cross-Origin Resource Sharing) in PHP

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

How to check if an email address is valid in PHP? How to check if an email address is valid in PHP? Sep 21, 2025 am 04:07 AM

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

How to make a deep copy or clone of an object in PHP? How to make a deep copy or clone of an object in PHP? Sep 21, 2025 am 12:30 AM

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

How to merge two arrays in PHP? How to merge two arrays in PHP? Sep 21, 2025 am 12:26 AM

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

How to use namespaces in a PHP project? How to use namespaces in a PHP project? Sep 21, 2025 am 01:28 AM

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

How to update a record in a database with PHP? How to update a record in a database with PHP? Sep 21, 2025 am 04:47 AM

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

What are magic methods in PHP and provide an example of `__call()` and `__get()`. What are magic methods in PHP and provide an example of `__call()` and `__get()`. Sep 20, 2025 am 12:50 AM

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

How to get the file extension in PHP? How to get the file extension in PHP? Sep 20, 2025 am 05:11 AM

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

How to create a zip archive of files in PHP? How to create a zip archive of files in PHP? Sep 18, 2025 am 12:42 AM

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.

See all articles