user3933935
user3933935

Reputation:

Images as cookies php

I'm trying to display images choosen by the user with a form

Form.php

<form method="post" action="vars.php" target="FrameUPcache">
<p><label for="nomlogo1">Nom logo 1 :</label><input type="text" id="nomlogo1" name="nomlogo1" />
<p><label for="nomlogo2">Nom logo 2 :</label><input type="text" id="nomlogo2" name="nomlogo2" /></p></br>    
<input type="submit" style="margin-left: 80px;"  value="Valider" />
</form>
<iframe name="FrameUPcache" class="FrameUPcache"></iframe>

vars.php

<?php
$cookie_valuelog1 = $_POST['nomlogo1'];
$cookie_valuelog2 = $_POST['nomlogo2'];
setcookie("logo1", $cookie_valuelog1, time() + ((86400*2) * 30), "/"); 
setcookie("logo2", $cookie_valuelog2, time() + ((86400*2) * 30), "/");
?>

display.php

<?php
echo 
'<img style=display:block;width:150;height:150;float:right;padding:10px; src="logos/'.$_COOKIE["logo1"].'" alt="Logo1">'.
'<img style=display:block;width:150;height:150;float:right;padding:10px; src="logos/'.$_COOKIE["logo2"].'" alt="Logo2">';
?>

the code works well, when the user enter the image name and click submit, the image is shown on display.php after a refresh

but when a new user navigate for the first time to display.php, images are not shown

How can i make images visible to a new visitor ?

Upvotes: 0

Views: 434

Answers (1)

John Conde
John Conde

Reputation: 219834

Those cookies are not available to your code until after a page load as the browser cannot send them until they are already set. Do a redirect after setting those cookies to solve this:

<?php
$cookie_valuelog1 = $_POST['nomlogo1'];
$cookie_valuelog2 = $_POST['nomlogo2'];
setcookie("logo1", $cookie_valuelog1, time() + ((86400*2) * 30), "/"); 
setcookie("logo2", $cookie_valuelog2, time() + ((86400*2) * 30), "/");
header('Location: display.php');
exit;
?>

Upvotes: 2

Related Questions