35787-vm/shorten.php
Flatlogic Bot 9d71ce33bd qwe1.0
2025-11-17 07:30:48 +00:00

39 lines
1.1 KiB
PHP

<?php
require_once 'db/config.php';
header('Content-Type: application/json');
$url = $_POST['url'] ?? null;
if (!$url || !filter_var($url, FILTER_VALIDATE_URL)) {
echo json_encode(['error' => '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.']);
}