我有一个项目,用户可以导航到提供的短 URL,这会将每个人重定向到具有不同公司名称的相似外观表单。
目前我有一个MySQL数据库,如下所示:
tbl_Codes
- shortURL (string of 5 alphanumeric characters)
- businessID (ID of business which matches the ID in the table below)
tbl_Business
- businessID
- businessName
- other fields....
因此,导航到example.com/12345的人会看到一个带有与 businessID 匹配的企业名称的表单,而导航到example.com/abcde的人会看到一个相同的表单,但具有不同的企业名称。
这样的事情会是最好的方法吗?如果没有,怎么办?
链接脚本使用PHP 正则表达式获取 shortURL,匹配数据库中的字符串,然后执行301 重定向。如果不匹配,它会重定向到 404 页面(尽管我可能不会执行 404 位)。
提前致谢。
这是您不想点击链接的代码。它来自一个教程:
<?php
$expectedURL = trim($_SERVER['URL']);
$split = preg_split("{:80\/}",$expectedURL);
$shortURL = $split[1];
// security: strip all but alphanumerics & dashes
$shortURL = preg_replace("/[^a-z0-9-]+/i", "", $shortURL);
// Check this string to see if it matches a short URL in our database.
$isShortURL = false;
$result = getLongURL($shortURL);
if ($result) { $isShortURL = true; }
$longURL = $result['longURL'];
// Finally, we check to see if our $isShortURL flag is set.
// If a matching short URL was found, we’ll redirect to it.
// If not, we’ll display our standard 404.
if ($isShortURL)
{
redirectTo($longURL, $shortURL);
} else {
show404(); // no shortURL found, display standard 404 page
}
//The primary function:
// Get the long URL associated with the passed short URL, if it exists.
function getLongURL($s)
{
// define these variables for your system
$host = ""; $user = ""; $pass = ""; $db = "";
$mysqli = new mysqli($host, $user, $pass, $db);
// you may just want to fall thru to 404 here if connection error
if (mysqli_connect_errno()) { die("Unable to connect !"); }
$query = "SELECT * FROM urls WHERE shorturl = '$s';";
if ($result = $mysqli->query($query)) {
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
return($row);
}
} else {
return false;
}
} else {
return false;
}
$mysqli->close();
}
//Perform the URL redirection.
function redirectTo($longURL)
{
// change this to your domain
header("Referer: http://www.your-domain-here.com");
// use a 301 redirect to your destination
header("Location: $longURL", TRUE, 301);
exit;
}
//Finally, display your standard 404 page here.
function show404()
{
// display/include your standard 404 page here
echo "404 Page Not Found.";
exit;
}
?>