Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 8 of 10 · RESTful API Development in PHP
Interview question

What is CORS and how do you handle it in a PHP API? CORS क्या है और PHP API में इसे कैसे handle करें?

Answer

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that blocks JavaScript from making requests to a different domain unless the server explicitly allows it via response headers.

header('Access-Control-Allow-Origin: https://myfrontend.com');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}
HeaderPurpose
Access-Control-Allow-OriginWhich domains can access this API
Access-Control-Allow-MethodsWhich HTTP methods are permitted

In Laravel, this is typically handled via the built-in cors middleware and config/cors.php rather than manual headers.

CORS एक browser security mechanism है जो JavaScript को दूसरे domain पर requests भेजने से रोकता है जब तक server headers से इजाज़त न दे।

header('Access-Control-Allow-Origin: https://myfrontend.com');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

Laravel में यह built-in cors middleware और config/cors.php से handle होता है।

Was this answer clear?