1

我有一个项目,用户可以导航到提供的短 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;
}
?>
4

2 回答 2

3

你发布的那个链接是……好吧……是的。不过有更好的方法可以做到这一点。但是,就您而言,我认为这不是您需要的吗?

如果不深入查看您的代码,请不要使用正则表达式。使用您的 htaccess 文件并执行 mod_rewrite 以将“短 url”作为查询参数传递。使用 $_GET 超级全局变量通过 PHP 脚本访问它。看起来您甚至根本不需要进行重定向?只需使用业务 ID 提取必要的数据。

此外,在您继续之前,如果可能,请开始使用 PDO,并为其构建一个 DB 类(包装器)。从长远来看,更多的 OOP 方法将为您提供更好的服务。

于 2011-06-01T12:33:52.153 回答
1

也许我发布的太频繁了:这条线

$query = "SELECT * FROM urls WHERE shorturl = '$s';";

对我来说看起来像是完美的Little Bobby Tables候选人

在此处输入图像描述

(也称为SQL 注入

于 2011-06-01T12:39:37.007 回答