John
John

Reputation: 2033

PHP random image script troubles

Hi I create random php image script but it does not work. It echos the links but it does not include the random variable.

$f_contents = file ("random1.txt", FILE_USE_INCLUDE_PATH);
$link = $f_contents[array_rand ($f_contents)]; /*Line 6*/


echo '<a href="http://www.site.com/view.php?t='.$link.'"><img src="http://www.site.com/images/'.$link.'.jpg" /></a>';
echo "</center>";

Upvotes: 0

Views: 93

Answers (1)

Giacomo1968
Giacomo1968

Reputation: 26066

The PHP function array_rand returns an array. So you need to change this:

$link = $f_contents[array_rand($f_contents)]; /*Line 6*/

Into this:

$link = $f_contents[array_rand($f_contents)[0]]; /*Line 6*/

Or perhaps this instead:

$rand_value = array_rand($f_contents);
$link = $f_contents[$rand_value[0]]; /*Line 6*/

I would also suggest error proofing your code to be like this to always check if $f_contents has content or not:

$f_contents = file ("random1.txt", FILE_USE_INCLUDE_PATH);
if (!empty($f_contents)) {
  $rand_value = array_rand($f_contents);
  $link = $f_contents[$rand_value[0]]; /*Line 6*/

  echo '<a href="http://www.site.com/view.php?t='.$link.'"><img src="http://www.site.com/images/'.$link.'.jpg" /></a>';
  echo "</center>";
}

EDIT Also array_rand accepts a second argument connected to how many random items are returned. So if you set that value to 1 then it will return a string instead of an array so the code would look like this:

$f_contents = file ("random1.txt", FILE_USE_INCLUDE_PATH);
if (!empty($f_contents)) {
  $rand_value = array_rand($f_contents, 1);
  $link = $f_contents[$rand_value]; /*Line 6*/

  echo '<a href="http://www.site.com/view.php?t='.$link.'"><img src="http://www.site.com/images/'.$link.'.jpg" /></a>';
  echo "</center>";
}

Upvotes: 2

Related Questions