douningqiu4991 2015-07-09 22:51 采纳率: 0%
浏览 82
已采纳

随机重定向均匀php

I have a simple php code that redirect to random uri from array. However, after a while i've noticed its not evenly load balanced. Can someone suggest tweaking so it will be evenly redirecting between the links ?

<?php 
$urls = array('https://a.com', 
               'http://b.com', 
               'http://c.com', 
               'http://d.com',
               'https://e.com',
               'https://f.com'
               ); 
shuffle($urls);
header('Location: ' . $urls[0]);
exit();
?>

Thanks

  • 写回答

3条回答 默认 最新

  • duanlu9970 2015-07-09 23:44
    关注

    Evenly and randomly are contradictory. But you can use a stack instead of an array to limit the randomness. Drawback is that you then need storage between script calls. For example :

    <?php
    $urls=readStack();
    if(empty($urls)) {
             $urls = shuffle(array('https://a.com', 
                    'http://b.com', 
                    'http://c.com', 
                    'http://d.com',
                    'https://e.com',
                    'https://f.com'
                   )); 
    $url=array_pop($urls);
    storeStack($urls);
    header('Location: ' . $url);
    

    Where storeStack() and readStack() functions are intended to store and retrieve your stack status from persistent storage. This could be done via file system storage, database access, or a memcache mechanism,... whatever is at your disposal and fast enough for your app. Here is a basic example with file system and serialize :

    <?php
    define( 'STOREFILENAME', '/tmp/urlstack');
    
    function storeStack($value){
         file_put_contents(STOREFILENAME, serialize( $value ));
    }
    
    function readStack($varname){
         return unserialize(file_get_contents(STOREFILENAME));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?