【问题标题】:redirecting to 2 pages 50% at the time in PHP在 PHP 中重定向到 2 个页面 50%
【发布时间】:2014-02-13 04:26:18
【问题描述】:

我试图在加载页面时重定向,但我希望它有 50% 的时间指向 page1.php,50% 的时间指向 page2.php

知道如何用 PHP 编写它吗?我应该将它存储在一个数组中还是我该怎么做?

提前致谢

【问题讨论】:

  • 几个想法,你已经尝试了什么,所以我们不会浪费你的时间让你再试一次?
  • if (rand(0, 1)) header('Location: page1.php'); else header('Location: page2.php');
  • 我还没有尝试任何东西,我不知道从哪里开始
  • 我认为这不会是 50% 的时间吗??

标签: php arrays redirect load


【解决方案1】:

相当短的脚本。使用PHP内置函数mt_rand($min, $max)

if (mt_rand(0,1) == 0) {
    header('Location: http://example.com/redirect1/');
    exit;
} else {
    header('Location: http://example.com/redirect2/');
    exit;
}

或者作为三元组,如果不使用变量,可读性会差一些:

header(mt_rand(0,1) == 0 ? 'Location: http://example.com/redirect1/' : 'Location: http://example.com/redirect2/');
exit;

或者使用变量:

$redirect1 = 'http://example.com/redirect1/';
$redirect2 = 'http://example.com/redirect2/';
header('Location: ' . mt_rand(0,1) == 0 ? $redirect1 : $redirect2);
exit;

【讨论】:

  • 但即使用户同时查看页面,也会加载 50% 吗?
  • 从人类的角度来看,两个用户在同一微秒内点击同一个页面的可能性非常低,即使确实发生了,也会随着时间的推移而趋于平缓。不过,我会用mt_rand 更新我的答案,因为它会产生更好的随机数。 -edit-有人打败了我。
  • rand 不是那么随机,最好使用 mt_rand,除非值被存储,否则它永远不会有 50% 的时间纯。
  • 谢谢洛兹。如果其他人好奇,这里是它的文档页面:us3.php.net/mt_rand
  • 所以如果我想要 50% 我需要在数据库中存储 0 或 1 并在页面加载时不断更新它们?
猜你喜欢
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多