admin管理员组

文章数量:1389768

I want to redirect to a random URL from a list.

Example : I have 3 URLs: Google, Facebook, yahoo.

<a href="<?php $sites[array_rand($sites)] ?>">Visit here</a>

So whenever users click the link they will be redirected to one of the 3 URLs in the array. I have tried this code but not working as needed:

$sites = array(
'/',
'/',
'/'
);
die();

I want to redirect to a random URL from a list.

Example : I have 3 URLs: Google., Facebook., yahoo..

<a href="<?php $sites[array_rand($sites)] ?>">Visit here</a>

So whenever users click the link they will be redirected to one of the 3 URLs in the array. I have tried this code but not working as needed:

$sites = array(
'http://www.google./',
'http://www.facebook./',
'http://www.yahoo./'
);
die();
Share Improve this question edited Feb 27, 2020 at 21:29 svelandiag 4,3301 gold badge43 silver badges80 bronze badges asked Nov 11, 2018 at 15:21 Rajeev Ranjan SharmaRajeev Ranjan Sharma 2155 silver badges15 bronze badges 2
  • 2 you're missing a semi-colon after $sites = array(...); – Emissary Commented Nov 11, 2018 at 15:29
  • Also not clear if that href is legitimate or not. You haven't identified where the current redirect takes you – charlietfl Commented Nov 11, 2018 at 15:38
Add a ment  | 

2 Answers 2

Reset to default 7

The same functionality using javascript:

<a href='javascript:openUrl()'>Visit here</a>
<script>
var sites=['http://www.google./',
'http://www.msn./',
'http://www.yahoo./'
];

function openUrl(){
    var i = Math.round(Math.random()*(sites.length-1));
    window.location.href=sites[i];
    return false;
}
</script>

I got my code working.

<?php
$addresses = [
    'http://www.google.',
    'http://www.facebook.',
    'http://www.youtube.'
];
$size = count($addresses);
$randomIndex = rand(0, $size - 1);
$randomUrl = $addresses[$randomIndex];
?>


<a href="<?php echo $randomUrl; ?>">random url</a>

If you have a better code, Please make a suggestion.

Thank you

本文标签: Random URL Redirect On click php or JavascriptStack Overflow