Tank Vvv Tank Vvv - 3 months ago 45
PHP Question

How to store and get image from a image variable (SESSION)?

here is my code, test1.php works, test2.php not works.

test1.php:

<?php

session_start();

header('Content-type: image/jpeg');

$text = rand(1000,9999);
$font_size = 5;

$image_width = imagefontwidth($font_size) * strlen($text);
$image_height = imagefontheight($font_size);
$image = imagecreate($image_width, $image_height);

imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 0, 0, 0);

imagestring($image, $font_size, 0, 0, $text, $text_color);

$_SESSION['image'] = $image;

$image_session = $_SESSION['image'];
imagejpeg($image_session);

?>


test2.php:

<?php
session_start();

header('Content-type: image/jpeg');
$image_session = $_SESSION['image'];
imagejpeg($image_session);

?>


As you can see, test1.php create a random image.
I can use:

<img src="test1.php">


to show the image from test1.php in any pages.
but, I want to use if else statement in other php files.

for example:

if users click submit button and enter nothing(no answer), the image will still the same, they have to answer the same question. if failed, the image will change.

I don't want to use javascript to prevent users input nothing and store images in disk.

so, I think that I need a variable to store the image that can be used again.
but I found I cannot use above method.

how can I achieve this?

Answer

imagecreate() returns a resource representing given image. PHP's sessions cannot store resource-type variables (more precisely - PHP is unable to serialize them upon script end), see http://php.net/manual/en/function.session-register.php:

Note: It is currently impossible to register resource variables in a session. ...

You may serialize the image to a string and store this string to the session (not tested):

test1.php:

...

ob_start();
imagejpeg($image);
$contents = ob_get_contents();
ob_end_clean();
$_SESSION['image'] = $contents;

test2.php:

header('Content-type: image/jpeg');
die($_SESSION['image']);