|
- <?php
-
- declare(strict_types=1);
-
- namespace App\Controllers;
-
- use Core\Controller;
- use Core\Request;
- use Core\Response;
-
- class ApiProxyController extends Controller
- {
- public function fetch(): Response
- {
- $request = Request::capture();
- $url = trim((string) ($request->input('url') ?? ''));
-
- if ($url === '' ||
- !filter_var($url, FILTER_VALIDATE_URL) ||
- !in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'], true)
- ) {
- return Response::json(['error' => 'Invalid or missing URL.'], 400);
- }
-
- $ch = curl_init();
- curl_setopt_array($ch, [
- CURLOPT_URL => $url,
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_TIMEOUT => 10,
- CURLOPT_FOLLOWLOCATION => true,
- CURLOPT_MAXREDIRS => 3,
- CURLOPT_SSL_VERIFYPEER => true,
- CURLOPT_USERAGENT => 'CampaignTracker-ApiProxy/1.0',
- CURLOPT_HTTPHEADER => ['Accept: application/json, application/xml, text/xml, text/plain, */*'],
- ]);
-
- $body = curl_exec($ch);
- $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $curlErr = curl_error($ch);
- curl_close($ch);
-
- if ($body === false) {
- return Response::json(['error' => $curlErr ?: 'Outbound request failed.'], 502);
- }
-
- return Response::json(['body' => (string) $body, 'http_status' => $httpCode]);
- }
- }
|