-
Notifications
You must be signed in to change notification settings - Fork 0
/
shorten.php
40 lines (34 loc) · 1018 Bytes
/
shorten.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
// Database connection
$host = "HOSTNAME";
$username = "DBUSERNAME";
$password = "DBPPASSWORD";
$database = "DBNAME";
// Validate and sanitize the input
if (!isset($_POST['long_url']) || empty($_POST['long_url'])) {
die("Error: Long URL is required");
}
$longURL = filter_var($_POST['long_url'], FILTER_SANITIZE_URL);
if (!$longURL) {
die("Error: Invalid long URL");
}
// Generate a unique short code using SHA-256
$shortCode = substr(hash('sha256', $longURL), 0, 6);
// Create a prepared statement to prevent SQL injection
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO urls (long_url, short_code) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
if (!$stmt) {
die("Error: " . $conn->error);
}
$stmt->bind_param("ss", $longURL, $shortCode);
if (!$stmt->execute()) {
die("Error: " . $stmt->error);
}
$stmt->close();
echo "http://tinyurl.rf.gd/$shortCode";
$conn->close();
?>