Avatar of shadow_shooter
shadow_shooter
 asked on

Why does setcookie function not work?

Hello,

I am trying to edit a PHP script and now it started to feel tired. What I'm trying to do is setting a cookie but it was not possible because of a headers already sent error. Then, I added "obstart()" at the beginning of the page to solve the problem. It worked flawless but the problem is now I cannot delete these cookies by setting them to a prior date when users log out.

It looks like PHP totally ignores the setcookie() function. The same thing happened while creating them but was solved after adding obstart() at the start. Same trick doesn't work in my logout.php

Any ideas?
PHP

Avatar of undefined
Last Comment
Ray Paseur

8/22/2022 - Mon
phpmonkey

After your headers have been sent you need to reload the page to be able to use set_cookie again since it all happens in the headers.
A possible solution is to inject your page with javascript that handles everything when the page load complete's.
Though i have found this though when using output buffering.
shadow_shooter

ASKER
Sorry, I'm not sure if I understood you. How come can ob_start() work for one page but not for another page?
phpmonkey

Oh you are not using ob_clear/flush in a loop somewhere?
In that case you shouldn't need ob_start()
The error usually means that you allready sent something to the browser forcing headers to be sent (as they are the first thing to go to a browser, and thats what php uses to set cookies).

Put it all the way on top of your script before anything else (even html, css and whatever).
Then it should be working.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
phpmonkey

drakeshe

Pretty much, you cant have any HTML or echo's before the setcookie()
shadow_shooter

ASKER
This is really what I do but hopelessly even setting them as a first thing on my page, it doesn't work.

I don't use flush or clear functions because simply ob_start() always worked for other related problems (but not this time though). The problem is I am using frames and what I'm editing is only a part of three separate pages. So, there is no way I can prevent others outputting (at least I don't know how to do so)

Isn't there a reason ob_start() works for one page but not for another page?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
drakeshe

Is this PHP file being included/required? or is it running on it's own page?
shadow_shooter

ASKER
It works on its own. The user is redirected to this page when s/he clicks "sign out".

Let me attach the code snippet

<?php
ob_start();
include "inc/baglan.php";
if ($verified_kat == "admin") {
$gnick = "&$verified_user";
$sorgu = "DELETE FROM online WHERE nick = '$gnick' LIMIT 1";
mysql_query($sorgu);
}
else if ($verified_kat == "mod") {
$gnick = "+$verified_user";
$sorgu = "DELETE FROM online WHERE nick = '$gnick' LIMIT 1";
mysql_query($sorgu);
}
else {
$sorgu = "DELETE FROM online WHERE nick = '$verified_user' LIMIT 1";
mysql_query($sorgu);
}  
setcookie('user_name','', (time()-192000), '/', '.kayiprihtim.org', 0);
setcookie('sec_user','', (time()-192000), '/', '.kayiprihtim.org', 0);
     
?>
<SCRIPT src="images/top.js" type=text/javascript></SCRIPT>
<SCRIPT language=javascript src=\"images/sozluk.js\"></SCRIPT>
<META content="bar ortamlari" name=keywords>
<META content="bar ortamlari" name=description><LINK href="favicon.ico"
rel="shortcut Icon"><LINK href="favicon.ico" rel=icon><LINK
href="images/sozluk.css" type=text/css rel=stylesheet>
<META http-equiv=Content-Type content="text/html; charset=iso-8859-9">
<SCRIPT language=javascript src="images/sozluk.js"></SCRIPT>
 
<center>Bizi tercih ettiiniz için te_ekkürler..<br>

Open in new window

shadow_shooter

ASKER
By the way, $verified_user is a session variable that is defined by session_register function.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
drakeshe

setting sessions I think can interfere with setting cookies.
shadow_shooter

ASKER
Well, even putting the part of session variables out of my code doesn't help either. This is what I thought first too...
drakeshe

Prety much if you set a session it sets the header and you cant set a cookie after thats done.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
shadow_shooter

ASKER
But there are examples of websites using both even on my another website, i both use session variables and cookies? Is there a source verifying this?
ASKER CERTIFIED SOLUTION
Ray Paseur

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Ray Paseur

Here is a sample "logout" script.
<?php // RAY_logout.php
 
// CLEAR THE INFORMATION FROM THE SESSION
$_SESSION = array();
 
// IF THE SESSION IS KEPT IN A COOKIE, FORCE IT TO EXPIRE
if (isset($_COOKIE[session_name()]))
{
   setcookie(session_name(), '', time()-42000, '/');
}
 
// TELL PHP TO ELIMINATE THE SESSION
session_destroy();
 
// REDIRECT TO THE HOME PAGE
header("Location: /");
exit;
 
?>

Open in new window

Ray Paseur

Here is another sample logout script that teaches how to eliminate all the cookies.

Please post back here if you have any questions, ~Ray
<?php // RAY_logout.php
error_reporting(E_ALL);
 
 
define('COOKIE_LIFE', 60*60*24); // A 24-HOUR DAY IN SECONDS ( = 86,400 )
$cookie_expires	= time() - date('Z') - COOKIE_LIFE;
 
 
// CLEAR THE INFORMATION FROM THE $_SESSION ARRAY
$_SESSION = array();
 
// IF THE SESSION IS KEPT IN COOKIE, FORCE SESSION COOKIE TO EXPIRE
if (isset($_COOKIE[session_name()]))
{
   setcookie(session_name(), '', $cookie_expires, '/');
}
 
// TELL PHP TO ELIMINATE THE SESSION
session_destroy();
 
 
 
 
 
 
// CLEAR ALL COOKIES WITH THIS CODE
foreach ($_COOKIE as $key => $value)
{
   setcookie($key, '', $cookie_expires, '/');
}
 
 
 
 
 
// REDIRECT TO THE HOME PAGE
header("Location: /");
exit;
 
?>

Open in new window

Your help has saved me hundreds of hours of internet surfing.
fblack61
shadow_shooter

ASKER
Ray Paseur, It worked like a miracle. Thanks for the efforts.
shadow_shooter

ASKER
Thank you.
Ray Paseur

Thanks for the points!  It's a great question and one that confuses a lot of developers.  Best regards, ~Ray
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.