我在网上找到[此网址缩短代码] [1]。
现在我想添加一些东西。如果他们从bit.ly,TinyURL.com或tr.im输入链接,我想向用户抛出错误。我想要它说:“抱歉,我们不会缩短短网址。”我知道我需要创建if
和else
语句,但我不知道需要调用哪些内容。
非常感谢您的投入!不幸的是我完全糊涂了。我在哪里放置这些代码建议?在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
?
答案 0 :(得分:3)
if(preg_match('!^(?:http://)?(?:www\.)?(?:bit\.ly|tinyurl\.com|tr\.im)/!i', $url))
die("Sorry, we do not shorten short URLs.");
答案 1 :(得分:2)
您可以使用以下内容检查网址是否已缩短:
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!";
}
答案 2 :(得分:1)
对于这些情况,您确切地知道要匹配的网址,而且它们不是模式,strpos
比preg
函数更简单。
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!";
}
编辑:我将原始网址更改为小写以简化匹配,因为用户可能已将网址提交为tinyURL.com,例如。
第二次编辑要回答您的跟进:似乎在行中创建了缩短网址的字符串
$shorten_url = "{$config['host']}/$code";
表示$config['host']
应包含网址的相关部分。但目前尚不清楚它的来源。猜测一下,它是在config.php中创建的。
我们使用die()
或echo()
的建议只是建议,不要将其直接嵌入到您的sprintf或您的代码中,而不实际调整它们。