Zum Inhalt springen

PHP Proxy

Nutzen Sie einen kleinen PHP-Proxy, wenn kein Framework verfügbar ist, aber PHP auf dem Server läuft.

  1. Script-Proxy erstellen

    public/cvs.js.php anlegen (oder Webserver so konfigurieren, dass /cvs.js auf diese Datei zeigt):

    <?php
    header('Content-Type: application/javascript');
    header('Cache-Control: public, max-age=86400');
    $cacheFile = sys_get_temp_dir() . '/usertrax-cvs.js';
    $maxAge = 86400;
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $maxAge) {
    readfile($cacheFile);
    exit;
    }
    $script = file_get_contents('https://usertrax.io/cvs.js');
    if ($script !== false) {
    file_put_contents($cacheFile, $script);
    echo $script;
    } else {
    http_response_code(502);
    }
  2. Events-Proxy erstellen

    public/api/usertrax/events.php anlegen:

    <?php
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
    }
    $body = file_get_contents('php://input');
    $headers = [
    'Content-Type: application/json',
    'Accept: application/json',
    'User-Agent: ' . ($_SERVER['HTTP_USER_AGENT'] ?? ''),
    'X-Auth-Key: ' . ($_SERVER['HTTP_X_AUTH_KEY'] ?? ''),
    ];
    $context = stream_context_create([
    'http' => [
    'method' => 'POST',
    'header' => implode("\r\n", $headers),
    'content' => $body,
    'ignore_errors' => true,
    ],
    ]);
    $response = file_get_contents('https://api.usertrax.io/api/events', false, $context);
    if ($response === false) {
    http_response_code(502);
    exit;
    }
    preg_match('/HTTP\/\d\.\d\s+(\d+)/', $http_response_header[0] ?? '', $matches);
    http_response_code((int) ($matches[1] ?? 200));
    header('Content-Type: application/json');
    echo $response;
  3. URL-Rewriting konfigurieren

    Apache (.htaccess):

    RewriteEngine On
    RewriteRule ^cvs\.js$ cvs.js.php [L]
    RewriteRule ^api/usertrax/events$ api/usertrax/events.php [L]

    Nginx:

    location = /cvs.js {
    fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /path/to/public/cvs.js.php;
    }
    location = /api/usertrax/events {
    fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /path/to/public/api/usertrax/events.php;
    }
  4. HTML anpassen

    <script>
    window.usertraxConfig = {
    endpoint: "/api/usertrax/events",
    };
    </script>
    <script src="/cvs.js" data-key="IHR_API_SCHLÜSSEL" defer></script>
  1. Website besuchen
  2. Network-Tab öffnen
  3. Prüfen, dass Anfragen über Ihre Domain laufen
  • 502-Fehler: allow_url_fopen aktivieren oder cURL statt file_get_contents nutzen
  • 401 Unauthorized: HTTP_X_AUTH_KEY-Weiterleitung in Nginx prüfen