Creating a CORS proxy using PHP and deploying it on Vercel is a great way to handle cross-origin requests. Below, I'll guide you through the steps to create a simple CORS proxy and deploy it on Vercel.
Step 1: Create the PHP CORS Proxy
Create a new directory for your project and add the following files:
1.1 api/proxy.php
This file will handle the proxy requests.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
// Preflight request
http_response_code(204);
exit();
}
$url = $_GET['url'] ?? '';
if (empty($url)) {
http_response_code(400);
echo json_encode(['error' => 'URL parameter is required']);
exit();
}
// Initialize cURL
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'User-Agent: CORS Proxy',
'Accept: application/json'
]);
// Execute the cURL request
$response = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
http_response_code(500);
echo json_encode(['error' => curl_error($ch)]);
exit();
}
// Get the HTTP status code
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
http_response_code($statusCode);
// Set the content type based on the response headers
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
header("Content-Type: $contentType");
// Output the response
echo $response;
// Close the cURL session
curl_close($ch);
?>
Step 2: Configure Vercel
2.1 vercel.json
Create a vercel.json file to configure your Vercel deployment.
{
"functions": {
"api/*.php": {
"runtime": "vercel-php@0.6.0"
}
}
}
Step 3: Deploy to Vercel
-
Install the Vercel CLI (if you haven't already):
npm install -g vercel
-
Navigate to your project directory:
cd path/to/your/project
-
Deploy your project to Vercel:
vercel
Follow the prompts to link your project to a Vercel account and deploy it. Once deployed, Vercel will provide you with a URL where your CORS proxy is live.
Step 4: Using the CORS Proxy
Once deployed, you can use your CORS proxy by making requests to the Vercel-provided URL. For example:
fetch('https://your-vercel-app.vercel.app/api/proxy.php?url=https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Security Considerations
- Validate URLs: Ensure that the URLs being proxied are safe and from trusted sources. You may want to whitelist domains or use a allowlist.
- Rate Limiting: Implement rate limiting to prevent abuse.
- Logging: Consider logging requests for monitoring and debugging purposes.
- Environment Variables: Use Vercel environment variables to store sensitive information, if needed.
Example: Whitelisting Domains
To whitelist domains, you can modify the proxy.php file:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
// Preflight request
http_response_code(204);
exit();
}
$url = $_GET['url'] ?? '';
if (empty($url)) {
http_response_code(400);
echo json_encode(['error' => 'URL parameter is required']);
exit();
}
// Whitelist of allowed domains
$allowedDomains = ['api.example.com', 'another-api.com'];
// Parse the URL to get the host
$parsedUrl = parse_url($url);
$host = $parsedUrl['host'] ?? '';
if (!in_array($host, $allowedDomains)) {
http_response_code(403);
echo json_encode(['error' => 'Invalid or unallowed domain']);
exit();
}
// Initialize cURL
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'User-Agent: CORS Proxy',
'Accept: application/json'
]);
// Execute the cURL request
$response = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
http_response_code(500);
echo json_encode(['error' => curl_error($ch)]);
exit();
}
// Get the HTTP status code
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
http_response_code($statusCode);
// Set the content type based on the response headers
$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
header("Content-Type: $contentType");
// Output the response
echo $response;
// Close the cURL session
curl_close($ch);
?>
This will ensure that only requests to allowed domains are proxied.
And that's it! You now have a CORS proxy running on Vercel using PHP.