3

我们使用基于 Codeigniter 的 CMS、Fuel,并且经常使用重定向功能。我想知道是否有一种方法可以在此函数中使用概率,以便将一半(或我们设置的任何数量)的时间重定向到一个页面,而将一半的时间重定向到另一个页面。

一般来说,我们将创建一个带有如下所示重定向的页面:

<?=redirect('https://subdomian.onanotherserver.com/asdf')?> 

我们想让它看起来相似:

<?=probabilityRedirect(0.5, 'https://subdomian.onanotherserver.com/asdf', 'https://subdomian.onanotherserver.com/jkl')?> 

解决此问题的最佳方法是什么?我们可以构建重定向还是只编写一个新函数?

4

2 回答 2

2

我会做一个新的功能。可能将其添加到 url_helper.php 使其最容易实现。也可以是一个独立的助手,但你必须确定 url_helper 已加载。

if(!function_exists('randomRedirect'))
{
  /**
   * Randomized Header Redirect
   *
   * @param int $seed value optional
   * @param array $list an indexed array of URL strings
   * @return void
   */
  function randomRedirect($seed = NULL, $list)
  {
    //list needs to be an array
    if(!is_array($list OR ! isset($list)))
    {
      throw new Exception('randomRedirect() requires Array in second parameter');
    }
    if(!empty($seed))
    {
      mt_srand($seed);
    }
    $choice_count = count($list);
    redirect($list[mt_rand(0, $choice_count)]);
  }
}

注意:我没有测试这个!结果不保证。:)

修改后的代码如下。 有一些时间对上述内容进行试验,最终导致了这个结果。

randomURL_helper.php

<?php

if(!function_exists('p_redirect'))
{
  /**
   * Randomized Header Redirect
   *
   * @param array $list an indexed array of URL strings
   * @param bool $seed optional when true, the random number generator will be seeded
   * 
   * @return void
   * 
   * Takes a list of URL strings in an array and randomly selects one as the
   * input to the CodeIgniter function redirect. 

   * If you specify the full site URL that link will be built, 
   * but for local links simply providing the URI segments to the 
   * controller you want to direct to will create the link. 
   * 
   * The function will build the URL based on your config file values.
   * 
   * This function requires the CodeIgniter helper "URL Helper" 
   * to be loaded using the following code: $this->load->helper('url');
   * 
   * Use this line of code $this->load->helper('randomURL'); 
   * to make p_redirect available to your CodeIgniter application.
   * 
   */
  function p_redirect($list, $seed = FALSE)
  {
    if(!is_array($list))
    {
      // $list must be an array
      throw new Exception('randomRedirect() requires Array as first parameter');
    }
    if($seed)
    {
      list($usec, $sec) = explode(' ', microtime());
      $seed_val = (float) $sec + ((float) $usec * 100000);
      mt_srand($seed_val);
    }

    redirect($list[mt_rand(0, count($list) - 1)]);
  }

}

对其进行了足够的测试,以发现它并非完全偏离基础。似乎完成了工作。享受!

于 2015-10-23T19:12:09.427 回答
1

您可以将其包含在 rand 50/50 条件中,

 <?php
 if (mt_rand(0,1)) {
    redirect('https://subdomian.onanotherserver.com/asdf')
 }
 ?>
于 2015-10-23T18:58:25.117 回答