Error: Cannot create 'links.json'.
Please give your folder Write Permissions (chmod 777 or 755).");
}
}
// Handle Shortening Logic (POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['url'])) {
// FIXED: Get the URL correctly from POST
$longUrl = $_POST['url'];
if (filter_var($longUrl, FILTER_VALIDATE_URL)) {
// Generate Code
$code = substr(md5(time() . rand()), 0, 6);
// Load existing data
$jsonContent = file_get_contents($dbFile);
$data = json_decode($jsonContent, true);
// If json is empty/corrupt, reset it
if (!is_array($data)) { $data = []; }
// Save new link
$data[$code] = $longUrl;
if (file_put_contents($dbFile, json_encode($data))) {
$shortLink = $baseUrl . '?c=' . $code;
$success = true;
} else {
$error = "Error saving link. Check file permissions.";
}
} else {
$error = "Invalid URL provided.";
}
}
// Handle Redirection Logic (GET)
$code = isset($_GET['c']) ? $_GET['c'] : null;
$viewMode = false;
$targetUrl = '';
if ($code) {
if (file_exists($dbFile)) {
$jsonContent = file_get_contents($dbFile);
$data = json_decode($jsonContent, true);
if (is_array($data) && isset($data[$code])) {
$viewMode = true;
$targetUrl = $data[$code];
} else {
$error = "Link not found in database.";
}
} else {
$error = "Database file missing.";
}
}
?>