|
-
Jul 5th, 2010, 04:11 PM
#1
Thread Starter
Lively Member
Redirect and Random Number Generator
I'm trying to create a php page that creates a random number and then redirects to another page based on that number.
So if the random number is 1, the redirect.php redirects to www.google.com,
if it is 2 then it redirects to www.yahoo.com etc.
I've tried this and failed many times.
Thanks.
-
Jul 5th, 2010, 04:35 PM
#2
Re: Redirect and Random Number Generator
Code:
<?php
$rn = rand(0,1); // first argument is minimum (inclusive), then maximum (inclusive).
$arr = array("http://www.google.com/","http://www.yahoo.com/");
$random_page = $arr[$rn];
header("Location: {$random_page}\r\n");
?>
Just set the rand() arguments and the array values.
-
Jul 5th, 2010, 04:43 PM
#3
Thread Starter
Lively Member
Re: Redirect and Random Number Generator
Thanks, sorry I'm a bit new to this. Where do I put it?
-
Jul 5th, 2010, 04:54 PM
#4
Re: Redirect and Random Number Generator
Wherever you're generating your random URLs. If you do more processing before actually doing the redirect, put it before the header() line. You'll need to modify the highlighted parts:
Code:
$rn = rand(0,1); // first argument is minimum (inclusive), then maximum (inclusive).
$arr = array("http://www.google.com/","http://www.yahoo.com/");
$random_page = $arr[$rn];
For the highlighted "1", just put the number of pages that you will, minus one. For the array, just put a list of pages to redirect to. The URL of the random page is stored in $random_page, and you can redirect using the Location: header, like that in the code I posted.
-
Jul 5th, 2010, 05:14 PM
#5
Re: Redirect and Random Number Generator
it would be easier to do this instead, so that you need only modify the array:
PHP Code:
<?php // Array of URLs $urls = array("http://google.com", "http://yahoo.com");
// Pick a random URL from the array $page = $urls[rand(0, count($urls) - 1)];
// Redirect header("Location: " . $page); exit; ?>
chapperz, assuming you're just linking to this script and it doesn't do anything else, then you just need to create a new PHP file (randomURL.php, for example), and then put that code inside of it. then, whenever it loads it will pick a random URL from $urls and redirect to it.
-
Jul 5th, 2010, 05:39 PM
#6
Thread Starter
Lively Member
Re: Redirect and Random Number Generator
Thanks .
I'm pretty new to PHP coding. What should the PHP file look like?
-
Jul 5th, 2010, 07:40 PM
#7
Re: Redirect and Random Number Generator
Exactly that. If you copied + pasted that code into a blank PHP file, it would work.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|