【问题标题】:using PHP inside HTML tags在 HTML 标记中使用 PHP
【发布时间】:2013-03-31 06:45:15
【问题描述】:
我现在正在学习 PHP,但我一直坚持:
<?php
$links= array();
links[0]="https://www.google.co.in/";
links[1]="http://www.reddit.com/";
$n= rand(0,1);
$select= $links[$n];
?>
<body>
<a href="<?php echo $select; ?>">Random</a>
</body>
我希望页面随机重定向到 google 或 reddit,但我不明白问题出在哪里。有什么解决办法吗?
【问题讨论】:
标签:
php
html
arrays
hyperlink
tags
【解决方案1】:
链接变量缺少$ ...更改代码为
links[0]="https://www.google.co.in/";
links[1]="http://www.reddit.com/";
到
$links[0]="https://www.google.co.in/";
$links[1]="http://www.reddit.com/";
【解决方案2】:
<?php
$links= array();
$links [0] = "https://www.google.co.in/";
$links [1] = "http://www.reddit.com/";
$n = rand (0, 1);
$select = $links [$n];
header ("Location: $select");
?>
【解决方案3】:
如果你想自动重定向:
1- 使用 HTML META 标签
<meta http-equiv="refresh" content="0;URL='<?php echo $select; ?>'">
2- 或使用 PHP Header
header("Location: $select");
exit();
完整代码:
<?php
$links= array();
$links [0] = "https://www.google.co.in/";
$links [1] = "http://www.reddit.com/";
$n = rand (0, 1);
$select = $links [$n];
header("Location: $select");
exit();
?>
【解决方案4】:
<?php
$links = array(
"https://www.google.co.in/",
"http://www.reddit.com/",
// ...
);
$randomLink = $links[rand(0, count($links)-1)];
header("Location: {$randomLink}");
exit();