I am currently developing a PHP website. I am trying to set a cookie which will store a user id. This is for a logging in system and I need the user id to be able to add it into different tables in a MySQL Database.

When the user successfully logs in it creates a php session and a cookie and then uses a meta tag refresh to direct to the index page.

if ($row = mysql_fetch_array($result))
{
    setcookie('id', $row['use_id']);
    $_SESSION['user'] = $username;
    setcookie('userID', $row['use_id']);
    echo '<meta http-equiv="refresh" content="0;url=../index.php">';
}

If I remove the meta refresh and just echo the cookie using $_COOKIE['userID'] it works fine but when I try and use $_COOKIE['userID'] on the index.php page after it has done the meta refresh it isn't displaying anything.

Any help would be greatly appreciated. Thank you

Comments

Why not send the refresh as a header, too? No need to use a meta tag - if you can send cookie headers, you can also send refresh headers.

Written by ThiefMaster

@ThiefMaster If I use the header redirect it errors because I am outputting HTML to the screen

Written by Boardy

What browser are you testing in? Some browsers only allow you to set cookies in a POST request.

Written by Naatan

@Naatan I've tried Google Chrome Development Build, normal google chrome and IE9

Written by Boardy

Can you show us the response headers for the page that sets the cookie?

Written by Naatan

If you cannot send a header you also cannot set a cookie! Cookies are headers, too.

Written by ThiefMaster

Accepted Answer

setcookie('userID', $row['use_id'], 0, "/");

Edit: zero for expire time.

Your cookie is not visible for index.php because it has been set from script in subdirectory. So it is not visible for pages on upper levels. You should set cookie path (4th parameter) to "/" and the cookie will be available within the entire domain.

This was the reason why your cookie was not visible to index.php.

header('Location: ../index.php');
                  ^^^

You have redirected page to upper directory level, but your cookie was not set for entire domain.

Written by Wh1T3h4Ck5
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki