Skip to content
The Chat Archive
claude-sonnet-4-20250514-thinking-32k· Anthropic LMArena Human Preference 140K

I want to make a cors proxy using php that i can deploy vercel

  1. User

    I want to make a cors proxy using php that i can deploy vercel

  2. Assistant

    Creating a CORS proxy using PHP on Vercel is possible, but since Vercel doesn't natively support PHP, you'll need to use a community builder. Here's how to build and deploy a PHP CORS proxy:

    Method 1: PHP CORS Proxy on Vercel

    Step 1: Project Structure

    cors-proxy/
    ├── api/
    │   └── proxy.php
    ├── vercel.json
    └── README.md
    

    Step 2: Create the PHP CORS Proxy (api/proxy.php)

    <?php
    // Enable CORS for all origins (adjust as needed for security)
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
    
    // Handle preflight OPTIONS request
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(200);
        exit();
    }
    
    // Get the target URL from query parameter
    $targetUrl = $_GET['url'] ?? '';
    
    if (empty($targetUrl)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing URL parameter']);
        exit();
    }
    
    // Validate URL
    if (!filter_var($targetUrl, FILTER_VALIDATE_URL)) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid URL']);
        exit();
    }
    
    // Get request method
    $method = $_SERVER['REQUEST_METHOD'];
    
    // Initialize cURL
    $ch = curl_init();
    
    // Basic cURL options
    curl_setopt_array($ch, [
        CURLOPT_URL => $targetUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false, // For development only
        CURLOPT_USERAGENT => 'CORS-Proxy/1.0'
    ]);
    
    // Handle different HTTP methods
    switch ($method) {
        case 'POST':
            curl_setopt($ch, CURLOPT_POST, true);
            $postData = file_get_contents('php://input');
            if ($postData) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            }
            break;
            
        case 'PUT':
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
            $putData = file_get_contents('php://input');
            if ($putData) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $putData);
            }
            break;
            
        case 'DELETE':
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
            break;
    }
    
    // Forward headers (excluding some that shouldn't be forwarded)
    $headers = [];
    $skipHeaders = ['host', 'connection', 'content-length'];
    
    foreach (getallheaders() as $name => $value) {
        if (!in_array(strtolower($name), $skipHeaders)) {
            $headers[] = "$name: $value";
        }
    }
    
    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    
    // Execute request
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    
    // Check for cURL errors
    if (curl_error($ch)) {
        http_response_code(500);
        echo json_encode(['error' => 'Request failed: ' . curl_error($ch)]);
        curl_close($ch);
        exit();
    }
    
    curl_close($ch);
    
    // Set response headers
    http_response_code($httpCode);
    if ($contentType) {
        header("Content-Type: $contentType");
    }
    
    // Output the response
    echo $response;
    ?>
    

    Step 3: Configure Vercel (vercel.json)

    {
      "functions": {
        "api/proxy.php": {
          "runtime": "vercel-php@0.6.0"
        }
      },
      "routes": [
        {
          "src": "/api/proxy",
          "dest": "/api/proxy.php"
        }
      ]
    }
    

    Step 4: Deploy

    1. Install Vercel CLI:

      npm i -g vercel
      
    2. Deploy:

      vercel --prod
      

    Step 5: Usage

    Once deployed, you can use your CORS proxy like this:

    // Frontend JavaScript
    const proxyUrl = 'https://your-vercel-app.vercel.app/api/proxy';
    const targetUrl = 'https://api.example.com/data';
    
    fetch(`${proxyUrl}?url=${encodeURIComponent(targetUrl)}`)
      .then(response => response.json())
      .then(data => console.log(data));
    
    // POST request example
    fetch(`${proxyUrl}?url=${encodeURIComponent(targetUrl)}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ key: 'value' })
    })
    .then(response => response.json())
    .then(data => console.log(data));
    

    Method 2: Alternative - Node.js CORS Proxy (Recommended)

    Since Vercel has native Node.js support, you might consider using Node.js instead for better reliability:

    Create api/proxy.js:

    export default async function handler(req, res) {
      // Enable CORS
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
      res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
    
      if (req.method === 'OPTIONS') {
        return res.status(200).end();
      }
    
      const { url: targetUrl } = req.query;
    
      if (!targetUrl) {
        return res.status(400).json({ error: 'Missing URL parameter' });
      }
    
      try {
        const response = await fetch(targetUrl, {
          method: req.method,
          headers: {
            ...req.headers,
            host: undefined,
            connection: undefined,
          },
          body: req.method !== 'GET' ? JSON.stringify(req.body) : undefined,
        });
    
        const data = await response.text();
        
        res.status(response.status);
        res.setHeader('Content-Type', response.headers.get('content-type') || 'text/plain');
        res.send(data);
      } catch (error) {
        res.status(500).json({ error: 'Request failed: ' + error.message });
      }
    }
    

    Security Considerations

    For production use, consider adding:

    1. URL whitelist to restrict which domains can be proxied
    2. Rate limiting to prevent abuse
    3. Authentication if needed
    4. Input validation and sanitization
    // Example URL whitelist
    $allowedDomains = [
        'api.github.com',
        'jsonplaceholder.typicode.com',
        'httpbin.org'
    ];
    
    $parsedUrl = parse_url($targetUrl);
    if (!in_array($parsedUrl['host'], $allowedDomains)) {
        http_response_code(403);
        echo json_encode(['error' => 'Domain not allowed']);
        exit();
    }
    

    The Node.js version would be more reliable on Vercel, but the PHP version should work with the community PHP runtime. Choose based on your familiarity and requirements!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.