我可以为你提供一个PHP短网址生成器的源码示例,这个示例将包括数据库连接、URL缩短逻辑以及基本的前端界面。

数据库设置
我们需要创建一个MySQL数据库和一个表来存储长URL和对应的短URL。
CREATE DATABASE shorturl;
USE shorturl;
CREATE TABLE urls (
id INT AUTO_INCREMENT PRIMARY KEY,
long_url TEXT NOT NULL,
short_url VARCHAR(6) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
); 数据库连接
我们编写一个文件db.php 来处理数据库连接。
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "shorturl";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?> URL 缩短逻辑
我们编写一个文件shorten.php 来处理URL缩短的逻辑。

<?php
include 'db.php';
function generateShortUrl() {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$randomString = '';
for ($i = 0; $i < 6; $i++) {
$index = rand(0, strlen($characters) 1);
$randomString .= $characters[$index];
}
return $randomString;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$longUrl = $_POST['long_url'];
$shortUrl = generateShortUrl();
$stmt = $conn->prepare("INSERT INTO urls (long_url, short_url) VALUES (?, ?)");
$stmt->bind_param("ss", $longUrl, $shortUrl);
if ($stmt->execute()) {
echo "Short URL created: <a href='http://yourdomain.com/" . $shortUrl . "'>http://yourdomain.com/" . $shortUrl . "</a>";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
}
?> 重定向逻辑
我们还需要一个文件redirect.php 来处理短URL的重定向。
<?php
include 'db.php';
$shortUrl = substr($_SERVER['REQUEST_URI'], 1); // 去掉前面的斜杠
$stmt = $conn->prepare("SELECT long_url FROM urls WHERE short_url = ?");
$stmt->bind_param("s", $shortUrl);
$stmt->execute();
$stmt->bind_result($longUrl);
if ($stmt->fetch()) {
header("Location: " . $longUrl);
exit();
} else {
echo "URL not found!";
}
$stmt->close();
?> 前端界面
我们编写一个简单的HTML表单来输入长URL并生成短URL。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>URL Shortener</title>
</head>
<body>
<h3>URL Shortener</h3>
<form action="shorten.php" method="post">
<label for="long_url">Enter Long URL:</label><br>
<input type="text" id="long_url" name="long_url" required><br><br>
<input type="submit" value="Shorten URL">
</form>
</body>
</html> 代码展示了一个简单的PHP短网址生成器的基本实现,你可以根据需要进一步扩展和优化,例如添加更多的错误处理、用户认证、统计功能等,希望这对你有所帮助!

以上就是关于“php短网址源码_PHP”的问题,朋友们可以点击主页了解更多内容,希望可以够帮助大家!
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/86567.html