0

我在网上找到了 [此 URL 缩短代码][1]。

现在我想添加一些东西。如果用户输入来自 bit.ly、TinyURL.com 或 tr.im 的链接,我想向用户抛出错误。我想让它说,“抱歉,我们不缩短短 URL。” 我知道我需要创建一个ifandelse语句,但我不知道我需要调用什么。

编辑:

非常感谢您的输入!不幸的是,我完全糊涂了。我在哪里放置这些代码建议?在 index.php 的顶部。现在我有以下php代码..

<?php
require_once('config.php');
require_once('functions.php');

if ($url = get_url())
{
    $conn = open_connection();
    $res = mysql_query("SELECT `id` FROM `urls` WHERE `url`='$url' LIMIT 1", $conn);
    if (mysql_num_rows($res))
    {
        // this URL entry already exists in the database
        // get its ID instead
        $row = mysql_fetch_object($res);
        $id = $row->id;
    }
    else
    {
        // a new guy, insert it now and get its ID
        mysql_query("INSERT INTO `urls`(`url`) VALUES('$url')", $conn);
        $id = mysql_insert_id($conn);
    }

    // now convert the ID into its base36 instance
    $code = base_convert($id, 10, 36);
    $shorten_url = "{$config['host']}/$code";

    // and beautifully display the shortened URL
    $info = sprintf('
<span class="long-url" style="visibility: hidden;">%s</span>
<span style="visibility: hidden">%d</span> <br>
    Link to drop:
    <a class="shorteen-url" href="%s">%s</a>
    <span style="visibility: hidden">%d</span>',
        $_GET['url'], strlen($_GET['url']),
        $shorten_url, $shorten_url,
        strlen($shorten_url));
}

?>

我没有使用$info = sprintf...也许我应该$info = sprintf用以下建议之一替换?

4

3 回答 3

3
if(preg_match('!^(?:http://)?(?:www\.)?(?:bit\.ly|tinyurl\.com|tr\.im)/!i', $url))
    die("Sorry, we do not shorten short URLs.");
于 2009-08-03T16:39:00.880 回答
2

您可以使用以下方法检查 URL 是否已被缩短:

if(preg_match('#^https?://[^/]*?(tinyurl\.com|tr\.im|bit\.ly)#i', $myUrl) {
    echo "Sorry, we do not shorten short URLs.";
} else {
    echo "We can shorten that!";
}
于 2009-08-03T16:39:26.793 回答
1

对于这些情况,您确切知道要匹配的 url,它们不是模式,strpospreg函数简单。

strpos接受要检查的字符串、匹配项、可选的偏移量,如果匹配项不在字符串中,则返回 FALSE。

$url_chk = strtolower($original_url);
if (strpos($url_chk, 'bit.ly') === FALSE
 || strpos($url_chk, 'tinyurl.com')  === FALSE
 || strpos($url_chk, 'tr.im') === FALSE) {
    echo "Sorry, we do not shorten short URLs.";
} else {
    echo "We can shorten that!";
}

编辑:例如,我将原始 url 更改为小写以简化匹配,因为用户可能已将 url 提交为 tinyURL.com。

第二次编辑回答您的跟进:似乎带有缩短网址的字符串是在该行中创建的

$shorten_url = "{$config['host']}/$code";

这意味着$config['host']应该包含 URL 的相关部分。但目前尚不清楚这是从哪里来的。猜测一下,它是在 config.php 中创建的。

我们的建议使用die()orecho()只是建议,不要将其直接嵌入到您的 sprintf 或您的代码中,而无需实际调整它们。

于 2009-08-03T16:43:10.407 回答