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 聚类分析或者python进行数据分析
  • ¥15 如何用visual studio code实现html页面
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?