generated from daytonaio/Sample-Template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshorten.php
58 lines (49 loc) · 1.93 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
// Database Connection
$host = "db"; // Docker service name
$username = "urlshortener"; // From docker-compose.yml
$password = "urlshortener"; // From docker-compose.yml
$database = "urlshortener"; // From docker-compose.yml
$conn = new mysqli($host, $username, $password, $database, 3306); // Standard MySQL port
// Check for connection errors
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get the long URL from the form
$long_url = trim($_POST['long_url']);
// Validate URL
if (!filter_var($long_url, FILTER_VALIDATE_URL)) {
die("Error: Invalid URL format");
}
// Generate a random shortcode
$short_code = substr(md5(uniqid(rand(), true)), 0, 6);
// Prepare the SQL query
$stmt = $conn->prepare("INSERT INTO urls (long_url, short_code, created_at) VALUES (?, ?, NOW())");
if (!$stmt) {
die("Error preparing statement: " . $conn->error);
}
$stmt->bind_param("ss", $long_url, $short_code);
// Execute the query and check for errors
if ($stmt->execute()) {
$shortened_url = "http://localhost:8080/redirect.php?code=" . $short_code; // Updated port to 8080
echo '<div class="alert alert-success">
Shortened URL: <a href="' . htmlspecialchars($shortened_url) . '" target="_blank" class="alert-link">' .
htmlspecialchars($shortened_url) . '</a>
</div>';
echo '<button onclick="copyToClipboard()" class="btn btn-secondary w-100" id="copyButton">
Copy Shortened URL
</button>';
echo '<script>
function copyToClipboard() {
const shortUrl = document.querySelector(".alert-link");
navigator.clipboard.writeText(shortUrl.href);
alert("URL copied to clipboard!");
}
</script>';
} else {
echo '<div class="alert alert-danger">Error: ' . htmlspecialchars($stmt->error) . '</div>';
}
// Close the statement and connection
$stmt->close();
$conn->close();
?>