我在 URL 缩短系统的一半。我从用户那里获取 URL,然后在 MySQL 中为此创建代码。然后我必须将即将到来的代码附加到我的域名(现在我正在使用 localhost),例如http://localhost/a5c3,然后将其重定向到真实域。
我卡在这里。一个代码片段至少对我有好处,可以理解我要做什么,或者你可以解释我要做什么。
我在 URL 缩短系统的一半。我从用户那里获取 URL,然后在 MySQL 中为此创建代码。然后我必须将即将到来的代码附加到我的域名(现在我正在使用 localhost),例如http://localhost/a5c3,然后将其重定向到真实域。
我卡在这里。一个代码片段至少对我有好处,可以理解我要做什么,或者你可以解释我要做什么。
您需要让服务器将不存在的 URL 重定向到现有页面(例如,在 Apache 上使用mod_rewrite )。这个“catch-all”页面将读取 URL,检查给定的代码是否存在于数据库中,如果存在,则重定向到正确的 URL。Ainab 的伪代码解释了最后一部分。
如果您没有将短代码与 URL 关联,那么您需要这样做,并且重定向会很容易。
SELECT url from Table where code=code
header("Location: $url")
如果您没有将短代码与 URL 关联,那么您需要这样做,并且重定向会很容易。
算法:
将表单中的 URL 和生成的代码保存到数据库中以供以后使用。
$url = $_POST['url']
Generate code
Concatenate your URL with the code
$full_url = $url.$code
向用户显示缩短的 URL。
如果您想重定向用户,在他/她将 URL 放入浏览器地址之后,请执行以下操作:
创建一个 .htaccess 文件,向其中添加以下行并将其拖放到您的根文件夹中:
RewriteEngine on
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php?code=$1 [L]
.htaccess 文件会将所有内容重定向到您的 index.php。例如,如果用户键入http://example.com/ujijui ,那么 .htaccess 将调用http://example.com/index.php?code=ujijui。因此,您可以使用 $_GET 捕获 URL 中的查询字符串。
在您的 index.php 文件中:
$code = $_GET['code']
mysql_connect('localhost', 'user', 'password')
mysql_select_db('your_db')
$sql = "SELECT url from Table where code=$code"
$result = mysql_query($sql)
Loop through result and get the URL
header("Location: $url")
明白了,这只是一个算法。
对于重定向问题,您应该尝试以下操作:
.htaccess 文件:
RewriteEngine on
RewriteCond $1 !^(index\.php)
RewriteRule ^(.*)$ index.php?url=$1 [L]
在 index.php 文件中:
<?php
$url = $_GET['url'];
// These will be taken from database
$urls_associations = array(
'1234' => "http://www.example.com",
'5678' => "http://www.google.com",
'90AB' => "http://stackoverflow.com",
);
// Redirect
if (isset($urls_associations[$url])) {
$redirect = $urls_associations[$url];
header("Location: $redirect");
echo "<a href='$redirect'>Go To : $redirect</a>";
}
else {
echo "Unknown URL code.";
}
然后,当用户访问例如http://localhost/1234时,他/她会被重定向到http://example.com等。当然,您应该在数据库上运行查询而不是从一个数组,但它看起来很简单,只需使用类似的东西:
$code = mysql_escape_string($url);
$res = mysql_query("SELECT url FROM mytable WHERE code='$code'");
if ($redirect = mysql_result($res)) {
header("Location: $redirect");
echo "<a href='$redirect'>Go To : $redirect</a>";
}
else {
echo "Unknown URL code.";
}