我有一个项目,用户可以导航到提供的短网址,这会将每个人重定向到具有不同公司名称的相似表单。
目前我有一个 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;
}
?>
最佳答案
您发布的链接是....好吧.... ish。不过有更好的方法可以做到这一点。但是,就您而言,我认为这不是您所需要的吗?
如果不深入查看您的代码,请不要使用正则表达式。使用您的 htaccess 文件并执行 mod_rewrite 以将“短 url”作为查询参数传递。使用 $_GET super 全局变量通过 PHP 脚本访问它。看起来您甚至根本不需要进行重定向?只需使用商家 ID 提取必要的数据即可。
此外,在您继续之前,请尽可能开始使用 PDO,并为其构建一个 DB 类(包装器)。从长远来看,更多的 OOP 方法将为您提供更好的服务。
https://stackoverflow.com/questions/6201003/