【问题标题】:Create shorter version of url in php在 php 中创建较短版本的 url
【发布时间】:2014-11-20 10:39:26
【问题描述】:

我有一个这样的网址:

http://domain.com/key1=00998833&key2=8666886&par3=testing&page=2

url中有很多参数,但是当页面在浏览器上显示时,我需要显示一个较短版本的url。为了更清楚,我需要网址类似于: http://domain.com/link123456 或以稍微不同的方式。

有什么办法吗?

我搜索了很多,但还没有找到任何解决方案。

谢谢

【问题讨论】:

  • link123456与key1=00998833&key2=8666886&par3=testing&page=2有什么关系? link123456可以是key1的值吗?

标签: php url url-rewriting short


【解决方案1】:

放入您的 htaccess 文件:

RewriteRule   ^link123456/?$   index.php?key1=00998833&key2=8666886&par3=testing&page=2 [L,QSA]

【讨论】:

  • 我会有很多这样的网址。实际上,网址将由简码生成。每个 url 的参数设置会有所不同。谢谢
  • @AbdulAwal 然后使用路由器并在数据库中找到 $_GET 的 URL,然后重定向到那里。
【解决方案2】:

如果您需要所有变量,则不能缩短它们。您可以做的是将密钥本地存储在数据库中,并将数据库中的行 ID 放在 url 中。

然后在加载 url 时,您只需检查数据库中带有 vars 的行。

【讨论】:

    【解决方案3】:

    实际上,网址将由简码生成。每个 url 的参数设置会有所不同 - Comment Source

    这让我相信你想要一个数据库来存储短网址和长网址。

    您可以使用index.php 作为您的路由器,并将短 URL 与长 URL 存储在数据库中。

    创建.htaccess重写规则

    RewriteEngine On
    RewriteRule ^(.*)$ index.php?q=$1 [NC,QSA]
    

    这将使http://example.com/short123456“重定向”到http://example.com/index.php?q=short123456

    创建你的数据库(假设是 MySQL)

    CREATE TABLE `urls` (
      `short_url` varchar(50) NOT NULL,
      `long_url` varchar(500) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

    我们将在这里存储短网址和长网址。

    创建你的路由器

    .htaccess 重写规则中,我们将转到index.php。因此,在您的index.php 中,我们可以执行以下操作;

    <?php
    if( isset($_GET['q']) ) { //See if there is any query string
      $short_code = ctype_alnum( (string) $_GET['q']) ? (string) $_GET['q'] : ''; //Filter out any potential nasty characters.
      /**
       * Query database
       * SELECT `long_url` FROM `urls` WHERE `short_url` = $short_code
       * Best to use PDO or MySQLi to do this (and I'm assuming you're using a MySQL database to store these)
       */
       if($query->num_rows) { //There is a result
          $result = $query->fetch(PDO::FETCH_ASSOC); //Assuming you've used PDO
          header('Location: '. $result['long_url']); //Redirect to the long url
          die;
       } else {
          //Short code doesn't exist
          http_response_code(404); //No result, return with 404 Not Found
          die;
       } 
    } else {
       //Do other logic...
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 2015-08-31
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 2012-03-19
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多