'Please provide a valid URL.']); exit; } function generateShortCode($length = 6) { return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length); } $short_code = generateShortCode(); // Ensure the short code is unique $pdoconnection = db(); $stmt = $pdoconnection->prepare("SELECT id FROM links WHERE short_code = ?"); $stmt->execute([$short_code]); while ($stmt->fetch()) { $short_code = generateShortCode(); $stmt->execute([$short_code]); } $stmt = $pdoconnection->prepare("INSERT INTO links (original_url, short_code) VALUES (?, ?)"); if ($stmt->execute([$url, $short_code])) { $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http"; $host = $_SERVER['HTTP_HOST']; $short_url = "$protocol://$host/$short_code"; echo json_encode(['short_url' => $short_url]); } else { echo json_encode(['error' => 'Could not create short link.']); }