简体   繁体   中英

using PHP inside HTML tags

I'm in the middle of learning PHP right now and I'm stuck on this:

<?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>

I want the page to redirect to either google or reddit randomly, but I don't understand what the problem is. Any solutions?

Missed $ for links variable ...Change code as

links[0]="https://www.google.co.in/";
links[1]="http://www.reddit.com/";

to

$links[0]="https://www.google.co.in/";
$links[1]="http://www.reddit.com/";
<?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");
?>

If you want to redirect automatically:

1- Use HTML META tag

<meta http-equiv="refresh" content="0;URL='<?php echo $select; ?>'">

2- or use PHP Header

header("Location: $select");
exit();

Full code:

<?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();
?>
<?php
$links = array(
  "https://www.google.co.in/",
  "http://www.reddit.com/",
// ...
);
$randomLink = $links[rand(0, count($links)-1)];
header("Location: {$randomLink}");
exit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM