【发布时间】:2011-09-06 06:12:03
【问题描述】:
我有一个项目,用户可以导航到提供的短 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 的人会看到一个表单> 看到相同的表格,但名称不同。
something like this 会是最好的方法吗?如果没有,怎么办?
链接脚本使用PHP regex 获取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;
}
?>
【问题讨论】:
-
当您在外部单击 url 链接时,拥有一个 form.php 页面并在顶部设置一个 GET var 会不会更容易?例如,您从页面 index.php > form.php?busName=someBussiness 开始,在该页面上使用 $_GET["busName"];?
-
我不这么认为。用户不是来自该站点,因此应使用短 URL 直接重定向到预先填写的表单。
标签: php mysql redirect url-rewriting short-url