Toolsnip

Javascript: Handling CORS in RESTful APIs

Implement CORS handling in your PHP-based RESTful APIs to manage cross-origin requests securely. Learn how to set up CORS headers and handle preflight requests effectively.

This PHP snippet demonstrates how to handle Cross-Origin Resource Sharing (CORS) for RESTful APIs. It allows you to specify which domains can access your API, enhancing security by preventing unauthorized requests.

The code sets up appropriate CORS headers based on the origin of the request and supports preflight checks with options for methods like GET, POST, and PUT.

Error handling includes rejecting requests from disallowed origins and providing meaningful error messages to assist with debugging and compliance with security policies.

The snippet is essential for API developers looking to ensure their APIs are accessible from specified client-side applications without exposing them to cross-site scripting risks.

This setup is crucial for any web application that interacts with multiple domains and needs to securely manage data exchange across different origins.

Snippet Code

PHP Version

8.1

Use Cases

  • API development
  • web security
  • cross-origin requests