views:

213

answers:

3

Hey I have dynamic image begin created with imagecreate(), and I have random values being produced, and I want to pass that random number, to a variable, and use that variable inside the page where Im using the image source.

The image is on random.php, and Im using <img src="random.php" /> on page index.php if that matters, and I want to pass from random.php (the image), to index.php. I already tried sessions and cookies but when I refresh, its always 1 step behind what the image is producing...

Im using a for loop to echo random numbers, I need to pass those numbers to a variable. Basicly how do I get numbers outside an image, in real time, not 1 step back.

A: 

The problem you are having is that index.php is requested, then the browser realizes that random.php is needed, so- yes, random.php will be a step AFTER index.php...

If you switch your "random creation" logic around, (have index create the key stored in a session, which can then be read from random.php) it may solve your problem.

gnarf
I know what your saying, but that wont work in this sitation. Im using a for statement, and I tried something sort of like you did, ended up with same results, where I did the random on the page that shows the image. Any other ideas?
David
+1  A: 

What about using a temporary session variable?

On your first page,

<?php
    session_start();
    $_SESSION['mykey'] = 'myrandomval';
    session_write_close(); // Helpful if you're using a header redirect
?>

and on the second page

<?php

    session_start();
    $value = $_SESSION['mykey'];

?>
jnunn
I agree with this - the only way is to set the random data in the index.php load, and not in the random.php load. You can set it into a session variable, and have random.php use that variable. random.php basically becomes image-generator.php, since the random logic should now be in index.php. The only other solution would be to use ajax to grab the random values after the image was generated, but that just sounds like too much.
Jay
A: 

Instead of passing variables from the page to the image, you could set the random number generator seed to the same value on both scripts. Here is a full sample:

<?php

function randomcolor()
{
    srand( $_SERVER['REQUEST_TIME'] );
    $colors = array('red', 'green', 'blue', 'black', 'orange');
    return $colors[ array_rand($colors) ];
}

$color = randomcolor();

if(isset( $_GET['image'] ))
{
    header('Content-type: image/png');
    $im = imagecreate(75, 50);
    imagecolorallocate($im, 0xee, 0xee, 0xee);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagestring($im, 2, 10, 10, $color, $black);
    imagepng($im);
    exit;
}

?>

<p>color: <?php echo $color; ?></p>
<img src="test5.php?image=1" />

This is two separate requests being seeded with the REQUEST_TIME, which means array_rand will return the same value both times.

Kevin