插件44:建立URL断地址

本文介绍了一款PHP插件,用于将长链接转换为短链接。该插件通过生成随机字符串并将其与原始长链接对应,从而实现短链接的创建。支持自定义短链接长度及重定向页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php // Plug-in 44: Create Short URL

// This is an executable example with additional code supplied
// To obtain just the plug-ins please click on the Download link

$long     = "http://pluginphp.com/longfoldername/index.html";
$redirect = "go.php";
$len      = 5;
$file     = "shorturls.txt";
$result   = PIPHP_CreateShortURL($long, $redirect, $len, $file);

echo      "The URL '$long' can now be accessed from: ";
echo      "<a href='/$result'>/$result</a>";

function PIPHP_CreateShortURL($url, $redirect, $len, $file)
{
   // Plug-in 44: Create Short URL
   //
   // This plug-in takes a long URL and shortens it. The
   // arguments required are:
   //
   //    $url:      A URL including the preceding http://
   //    $redirect: A PHP page on the server to use for URL
   //               redirection, It should have a short
   //               name, such as /go.php.
   //    $len:      The number of characters to use in the
   //               short URL's tail.
   //    $file:     Location of a file containing the data
   //               for the redirects.

   $contents = @file_get_contents($file);
   $lines    = explode("\n", $contents);
   $shorts   = array();
   $longs    = array();

   if (strlen($contents))
      foreach ($lines as $line)
         if (strlen($line))
            list($shorts[], $longs[]) = explode('|', $line);

   if (in_array($url, $longs))
      for ($j = 0 ; $j < count($longs) ; ++$j)
         if ($longs[$j] == $url) return $redirect .
            "?u=" . $shorts[$j];

   do $str = substr(md5(rand(0, 1000000)), 0, $len);
   while (in_array($str, $shorts));
   
   file_put_contents($file, $contents . $str . '|' . $url .
      "\n");
   return $redirect . "?u=$str";
}

?>

插件说明:

插件接受一个需要简化的URL地址和其他数据,返回一个URL断地址,他需要以下参数:

$url:需要简化的URL地址

$redirect:服务器上一个PHP程序的名字,它会把URL短地址重定向到原来的目标地址。

$len:可以出现在URL短地址里面的字符个数,这个数值越大,支持的URL地址越多。例如3个字符可以支持4096个URL地址,

因为,本插件使用十六进制的0~0和a~f共16个字符

$file 用来保存URL短地址的文件名。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值