首页 > 解决方案 > 使用带有随机 ID 的 PHP 标头打开页面适用于 Edge,但不适用于 chrome

问题描述

我正在尝试生成一个随机数(1 - 151 之间),以便我可以根据随机生成的 ID 打开一个页面。这里的问题在于浏览器兼容性,因为预期的功能适用于 Edge,但不适用于 Chrome 或 FireFox。

pokedex.php:

<form action='randomPokemon.php' >
    <button type="submit" class="toolsBtn">Random</button>
</form>

随机口袋妖怪.php:

<?php
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'pokedex.php?pid=';
$randomid = rand(1, 151);
header("HTTP/1.1 303 See Other");
header("Location: http://$host$uri/$extra" . mt_rand(1, 151));
unset($randomid);
exit;
?>

现场演示: http: //fraserprovan.co.uk/projects/pokedex/pokedex.php

我不知道为什么它适用于 Microsoft Edge 而不是其他浏览器。在 chrome 上,它每次都会打开相同的页面,就好像变量 $randomid 没有改变一样。任何建议或其他资源的链接将不胜感激。

更新:决定用 Javascript 代替使用以下函数,感谢您的建议。

function randomPokemon(){
    var randomNum = Math.floor(Math.random() * 151) + 1;  
    document.location.replace('pokedex.php?pid=' + randomNum);
}

标签: phphtml

解决方案


尝试使用绝对URI,也不要在 header-statement 之前留下任何空格或换行符。请参阅php-docs中的此注释

笔记:

大多数当代客户端接受相对 URI 作为 » Location: 的参数,但一些较旧的客户端需要一个绝对 URI,包括方案、主机名和绝对路径。您通常可以使用 $_SERVER['HTTP_HOST']、$_SERVER['PHP_SELF'] 和 dirname() 自己从相对的 URI 中创建绝对 URI:

<?php
/* Redirect to a different page in the current directory that was requested */
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>

推荐阅读