Running setcookie()

I have a script i was playing with below. I want to edit it using the setcookie() function to set a cookie with the random image script, using the $_COOKIE array, i want to be able to read the cookie if its available. Finally i want to create a test condition where a new random index is selected if the user has previously viewed the image and the cookie is available. I would love to know how to do this, im trying to familiarize myself on doing different scripts. I would put the script that the php has to go into, but forum wont allow me because it has images and im new to the forum

You need to post code here or people won’t be able to help you.

I tied, the forum wouldnt allow me to. It said new users cannot upload images. Theres images in my code

I’m confused

PHP files are text files. They don’t have images in them.

1 Like

This is an HTML file, with php block in it. Im just new to php and not understanding how to add what i want from first post. It has images in the file and forum keeps saying new users cannot upload images

This is the code

<title>JFQ Turnings</title>
<body bgcolor="#ffffff" text="#000000">
<img src="jfqturnings.gif" alt="JFQ Turnings, coming soon." width="864" height="100">
<br /><img src="<?php echo getRandomImage(); ?>" alt="" width="864" height="567">
echo getRandomImage();
function getRandomImage()
$images = array("candlestick.jpg", "rollingpin.jpg", "table.jpg", "table2.jpg");
$random = rand(0, 3);
return $images[$random];

This post has been reformatted by enclosing the code block in 3 backticks
on their own lines.

A problem with the code as it is now is that

setcookie() must be called before any output is sent to the browser.

But if you move the function to the beginning, you could use setcookie() right before the return

do you not get a ‘headers already sent’ error message when you tried your code?

As @Mittineague said it needs to come before any html is called including spaces. I occasionally forget and have a space between blocks of php eg

//some code

//set cookie

the space in between will cause a headers already sent error. Simply delete the line between the php blocks.
would be the same if you did echo 'something'; in the first block as you have outputted something to the page before setting the cookie. So either you’d have to move the top php block below the set cookie or set a variable and call it later.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.