如何创建一个PHP旋转重定向系统


How to create a PHP rotational redirect system?

假设有3个链接:

    http://example.com/1
  • http://example.com/2
  • http://example.com/3

我该如何创建一个基于旋转的重定向系统?

下面是它的工作原理:

  • 用户打开http://example.com,然后被重定向到http://example.com/1

  • URL http://example.com/1(用户被重定向到的URL存储在文本文件中,URL作为文本文件的值)

  • 当另一个用户访问http://example.com时,他将被重定向到http://example.com/2,而不是重定向到http://example.com/1。代码应该知道重定向到http://example.com/2而不是/1,因为/1存储在文本文件中。重定向用户后,文本文件的值从…/2.

  • 同样的事情发生在下一个用户访问,但被转发到…/3。

  • 第四个用户被重定向到…/1

  • 等等

    <?php
    $link[0] = array('link' => 'http://example.com/1', 'percent' => 33);
    $link[1] = array('link' => 'http://example.com/2', 'percent' => 33);
    $link[2] = array('link' => 'http://example.com/3', 'percent' => 33);
    $percent_arr = array();
    foreach($link as $k => $_l) {
        $percent_arr = array_merge($percent_arr, array_fill(0, $_l['percent'], $k));
    }
    $random_key = $percent_arr[mt_rand(0,count($percent_arr)-1)];
    $redirectlink = $link[$random_key]['link'];
    ?>
    <a href="<?php $redirectlink ?>">Click to redirect</a>
    

我目前正在使用这个代码,但它没有提供我所需要的。

如果您在脚本中使用数据库,我建议使用时间戳:

  • 创建一个有3列的表,id siteurl lastvisit

  • 创建一个查询,获取访问时间最长的站点

  • 当用户进入你的网站时,他会被重定向到他所属的位置。更新站点时间戳

如果你没有数据库,就使用。txt文件。

如果我没理解错的话,你不需要加权路由,所以

只需在文本文件中存储下一个路由的索引,并在每次调用时旋转它。

阅读文件:

$link[0] = array('link' => 'http://example.com/1');
$link[1] = array('link' => 'http://example.com/2');
$link[2] = array('link' => 'http://example.com/3');
$next = intval(file_get_contents('next.txt')); // $next -> 0
$redirectTo = $link[$next];

现在旋转并写入文件:

$next = ($next === 2) ? 0 : next +1;
file_put_contents('next.txt', $next);
//redirect ...