📜  php cors - PHP (1)

📅  最后修改于: 2023-12-03 15:18:19.606000             🧑  作者: Mango

PHP CORS

CORS (Cross-Origin Resource Sharing) is a security feature implemented in web browsers to prevent malicious websites from accessing data from other websites without permission.

In a PHP application, it's crucial to implement CORS correctly so that it doesn't break the security of the application. In this guide, we'll explore how to enable CORS in PHP.

Enabling CORS in PHP

To enable CORS in PHP, you need to add the appropriate headers to your response. The headers you need to add depend on the type of request and the origin of the request. Here is an example of how to add CORS headers to a PHP script:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Authorization');

This code adds the Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers headers to the response. The Access-Control-Allow-Origin header specifies which origins are allowed to make requests to the server. The * value allows any origin to make requests. You can also restrict the origins to specific ones by listing them explicitly.

The Access-Control-Allow-Methods header specifies which methods are allowed for the request. The OPTIONS method is also included to handle pre-flight requests.

The Access-Control-Allow-Headers header specifies which headers are allowed in the request. The Authorization header is included for HTTP authentication.

Handling pre-flight requests

When a request is made from a different origin or with different headers, the browser first sends an OPTIONS pre-flight request to check if the server allows the request. To handle pre-flight requests in PHP, you need to check for the OPTIONS method and add the appropriate headers:

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Authorization');
    exit;
}

This code checks if the request method is OPTIONS and exits the script if it is. The headers are then added to the response.

Conclusion

Enabling CORS in PHP is essential to make sure your application is secure and doesn't break the same-origin policy implemented in browsers. By adding the appropriate headers, you can allow specific origins, methods, and headers to make requests to your server.