Меню

Почему setcookie выдает ошибку

I’ve made a login, that sets a cookie with a value of the imputed email address, so in the global.php file, it stores an array of the users data using:

$email = $_COOKIE["PeopleHub"];
$getuserdata = mysqli_query($con, "SELECT * FROM Earth WHERE email='$email'");
$userdata = mysqli_fetch_array($getuserdata, MYSQLI_ASSOC);

The cookie isn’t being set, I know this because I made a test file:

echo $_COOKIE["PeopleHub"];

It just made a blank page.

The login code (where the cookie is set):

<?php 
include "global.php";    
?>
<h2>Login</h2>
<?php 
    echo "We currently have <b>" . $usercount . "</b> members, <b>" . $onlinecount . "</b> of which are online. "; 
?>
<br>
<br>
<?php 
    if(isset($_POST["email"])){ 
        $email = $_POST["email"];
        $password = sha1($_POST["password"]);
        $check = mysqli_query($con, "SELECT * FROM Earth WHERE `email`='$email' AND `password`='$password'");
        $check = mysqli_num_rows($check);
        if($check == 1){
        setcookie("PeopleHub", $email, 0, '/');
        echo "We logged you in!";
        }
        else { 
            echo "We couldn't log you in!";
        }
    }
?>
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
    Email <input name="email" placeholder="Email Address" required="" type="text"><br>
    Password <input name="password" placeholder="Password" required="" type="password"><br>
    <input type="reset" value="Start Over">
    <input type="submit" value="Login">
</form>

За последние 24 часа нас посетили 11484 программиста и 826 роботов. Сейчас ищут 386 программистов …


  1. dimedrol3004

    С нами с:
    5 апр 2020
    Сообщения:
    1
    Симпатии:
    0

    Не получается создать $_COOKIE при помощи функции setcookie(); Я не понимаю почему вылетает ошибка.
    [​IMG]

    setcookie(«TestCookie», ‘да’); Выдаёт ошибку
    Warning: Cannot modify header information — headers already sent by (output started at C:OSPaneldomainslesson7.testindex.php:1) in C:OSPaneldomainslesson7.testindex.php on line 16

    1. var_dump(isset($_COOKIE[«TestCookie»]));
    2. setcookie(«TestCookie», ‘да’);
    3. var_dump($_COOKIE[«TestCookie»]);


  2. mkramer

    Команда форума
    Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.491
    Симпатии:
    1.731

    1. setcookie должно вызываться до первого вывода информации в браузер, это написано в мануале русским языком.
    2. В массиве $_COOKIE те куки, которые пришли от клиента, а setcookie устанавливает те, что уйдут в браузер. Т.е. новая кука будет в массиве $_COOKIE только при следующем запросе.
    — Добавлено —
    3. Скрины кода и всего, что можно скопировать и вставить, здесь очень не приветствуются. Больше не вставляй код скринами.

I am going through some PHP tutorials on how to set cookies. I have noticed that cookies are successfully set on FF4 and IE9, however it does not get set in Chrome (11.0.696.60). The PHP file was served from XAMPP (localhost).

I tried the example from w3schools:

<?php
setcookie("user", "Alex Porter", time()+3600);
?>

And from this site (for localhost environments):

<?php
setcookie("username", "George", false, "/", false);
?>

Thanks in advance.

asked May 1, 2011 at 14:35

Elyas's user avatar

4

Disabling cookies for IP addresses and localhost was a design decision. See also: https://code.google.com/p/chromium/issues/detail?id=56211

Ways to work around the issue include:

  • Set a local domain (e.g., edit /etc/hosts to use 127.0.0.1 localhost.com).
  • Use http://myproject.localhacks.com/ (which points to 127.0.0.1).
  • Use an empty domain value when setting the cookie.

For example, in PHP:

setcookie(
  $AUTH_COOKIE_NAME,
  $cookie_value,
  time() + cookie_expiration(),
  $BASE_DIRECTORY,
  null,
  false,
  true
);

Here the value null indicates that the domain should not be set.

Note: not setting the domain prevents the cookie being visible to sub-domains.

Dave Jarvis's user avatar

Dave Jarvis

29.9k39 gold badges177 silver badges310 bronze badges

answered May 1, 2011 at 15:41

Mike West's user avatar

Mike WestMike West

5,04724 silver badges25 bronze badges

2

Domain should be equal to NULL.

& Should be given an expiry date. i.e.,

setcookie("username", "George", time() + (20 * 365 * 24 * 60 * 60), "/", NULL);

Ankur's user avatar

Ankur

5,07819 gold badges36 silver badges62 bronze badges

answered Apr 18, 2013 at 9:06

John Chornelius's user avatar

1

It seems like this might be a bug with the «Developer Tools» feature of Chrome. The whole time I was trying to set a cookie (but not retrieve it) and it worked with the other browser. It worked, assuming you trust the cookie viewing section of FF or locate the cookie’s file for IE. In Chrome I was relying on the «Cookies» section of the «Developers Tools» (Developer Tools > Resources > Cookies).

I decided to take a step further and actually output the cookie’s value using this script found in WHT (posted by Natcoweb):

<?php
setcookie('test', 'This is a test', time() + 3600);
if(isset($_COOKIE['test'])){
$cookieSet = 'The cookie is ' . $_COOKIE['test'];
} else {
$cookieSet = 'No cookie has been set';
}
?>

<html>
<head><title>cookie</title></head>
<body>

<?php
echo $cookieSet;
?>

</body>
</html>

And it worked on all browsers including Chrome (I get: «The cookie is This is a test»)! However Chrome’s cookie inspector continues showing «This site has no cookies». I also managed to find the list of cookies stored in Chrome’s settings (Options > Under the Hood > Content Settings > All cookies and site data) and finally found the cookie (more steps to check but at least more accurate than developer tools)!

Conclusion: cookies were being set, but Chrome’s development tools can’t see it for some reason.

answered May 2, 2011 at 3:49

Elyas's user avatar

ElyasElyas

5511 gold badge5 silver badges9 bronze badges

1

Did you check your system date?
$ date
And if it is old time then you should change your time
$ date -s 2007.04.08-22:46+0000

I hope this helps. I had the same problem and it worked

answered Apr 12, 2012 at 11:35

Sahin Yanlık's user avatar

Sahin YanlıkSahin Yanlık

1,1332 gold badges11 silver badges21 bronze badges

I faced the same issue when i tried as below

setcookie("gb_role",base64_encode($_SESSION["role"]),time()+60*60*24*30);

when i changed it to below

setcookie("gb_role",base64_encode($_SESSION["role"]),time()+2592000);

I just worked fine, the difference is instead of time()+60*60*24*30 i just did time()+some numeric value work. I know that doesn’t make sense but it worked.

answered Apr 13, 2012 at 10:13

Satya's user avatar

SatyaSatya

2,9782 gold badges19 silver badges25 bronze badges

This code is working for me in IE, Chrome and FF

if($_COOKIE['language']==NULL || empty($_COOKIE['language']))
{


    $dirname = rtrim(dirname($_SERVER['PHP_SELF']), '/').'/';

    $expire=time()+31536000;


    setcookie("language", "English",$expire,"$dirname","mydomain.com",false,false);
}

answered Apr 19, 2014 at 17:59

Dorar's user avatar

DorarDorar

111 bronze badge

I am going through some PHP tutorials on how to set cookies. I have noticed that cookies are successfully set on FF4 and IE9, however it does not get set in Chrome (11.0.696.60). The PHP file was served from XAMPP (localhost).

I tried the example from w3schools:

<?php
setcookie("user", "Alex Porter", time()+3600);
?>

And from this site (for localhost environments):

<?php
setcookie("username", "George", false, "/", false);
?>

Thanks in advance.

asked May 1, 2011 at 14:35

Elyas's user avatar

4

Disabling cookies for IP addresses and localhost was a design decision. See also: https://code.google.com/p/chromium/issues/detail?id=56211

Ways to work around the issue include:

  • Set a local domain (e.g., edit /etc/hosts to use 127.0.0.1 localhost.com).
  • Use http://myproject.localhacks.com/ (which points to 127.0.0.1).
  • Use an empty domain value when setting the cookie.

For example, in PHP:

setcookie(
  $AUTH_COOKIE_NAME,
  $cookie_value,
  time() + cookie_expiration(),
  $BASE_DIRECTORY,
  null,
  false,
  true
);

Here the value null indicates that the domain should not be set.

Note: not setting the domain prevents the cookie being visible to sub-domains.

Dave Jarvis's user avatar

Dave Jarvis

29.9k39 gold badges177 silver badges310 bronze badges

answered May 1, 2011 at 15:41

Mike West's user avatar

Mike WestMike West

5,04724 silver badges25 bronze badges

2

Domain should be equal to NULL.

& Should be given an expiry date. i.e.,

setcookie("username", "George", time() + (20 * 365 * 24 * 60 * 60), "/", NULL);

Ankur's user avatar

Ankur

5,07819 gold badges36 silver badges62 bronze badges

answered Apr 18, 2013 at 9:06

John Chornelius's user avatar

1

It seems like this might be a bug with the «Developer Tools» feature of Chrome. The whole time I was trying to set a cookie (but not retrieve it) and it worked with the other browser. It worked, assuming you trust the cookie viewing section of FF or locate the cookie’s file for IE. In Chrome I was relying on the «Cookies» section of the «Developers Tools» (Developer Tools > Resources > Cookies).

I decided to take a step further and actually output the cookie’s value using this script found in WHT (posted by Natcoweb):

<?php
setcookie('test', 'This is a test', time() + 3600);
if(isset($_COOKIE['test'])){
$cookieSet = 'The cookie is ' . $_COOKIE['test'];
} else {
$cookieSet = 'No cookie has been set';
}
?>

<html>
<head><title>cookie</title></head>
<body>

<?php
echo $cookieSet;
?>

</body>
</html>

And it worked on all browsers including Chrome (I get: «The cookie is This is a test»)! However Chrome’s cookie inspector continues showing «This site has no cookies». I also managed to find the list of cookies stored in Chrome’s settings (Options > Under the Hood > Content Settings > All cookies and site data) and finally found the cookie (more steps to check but at least more accurate than developer tools)!

Conclusion: cookies were being set, but Chrome’s development tools can’t see it for some reason.

answered May 2, 2011 at 3:49

Elyas's user avatar

ElyasElyas

5511 gold badge5 silver badges9 bronze badges

1

Did you check your system date?
$ date
And if it is old time then you should change your time
$ date -s 2007.04.08-22:46+0000

I hope this helps. I had the same problem and it worked

answered Apr 12, 2012 at 11:35

Sahin Yanlık's user avatar

Sahin YanlıkSahin Yanlık

1,1332 gold badges11 silver badges21 bronze badges

I faced the same issue when i tried as below

setcookie("gb_role",base64_encode($_SESSION["role"]),time()+60*60*24*30);

when i changed it to below

setcookie("gb_role",base64_encode($_SESSION["role"]),time()+2592000);

I just worked fine, the difference is instead of time()+60*60*24*30 i just did time()+some numeric value work. I know that doesn’t make sense but it worked.

answered Apr 13, 2012 at 10:13

Satya's user avatar

SatyaSatya

2,9782 gold badges19 silver badges25 bronze badges

This code is working for me in IE, Chrome and FF

if($_COOKIE['language']==NULL || empty($_COOKIE['language']))
{


    $dirname = rtrim(dirname($_SERVER['PHP_SELF']), '/').'/';

    $expire=time()+31536000;


    setcookie("language", "English",$expire,"$dirname","mydomain.com",false,false);
}

answered Apr 19, 2014 at 17:59

Dorar's user avatar

DorarDorar

111 bronze badge

Добрый день! Вот решил поделиться своим открытием насчёт функции Setcookie в PHP. При генерации страницы мне нужно чтобы у клиента установился определённое значение в cookie. Поковырявшись с Setcookie и убедившись что оно не работает, я обычно бросал это неблагодарное дело и пользовался JavaScript`ом, однако если у клиента отключены скрипты, то такой фокус не прокатит. Так почему же Setcookie не работает?

В основном это две причины: очевидная и не очень.

Очевидная причина:

Как пишут нам в инструкции cookie должны передаваться до того как будут выведены какие-либо другие данные скрипта (это ограничение протокола). Это значит, что в скрипте вызовы этой функции должны располагаться прежде остального вывода, включая вывод тэгов <html> и <head>, а также пустые строки и пробельные символы.

Да, это очень важное замечание, поскольку, проигнорировав его, вы получите сообщение об ошибке следующего содержания: Cannot modify header information — headers already sent by (output started at… Типа невозможно изменить заголовки страницы, так как они уже были отправлены.

В той же инструкции приведён пример использования функции Setcookie на PHP:

<?php
 $value = 'что-то где-то';
 setcookie("TestCookie", $value);
 setcookie("TestCookie", $value, time()+3600);  /* срок действия 1 час */
 setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);
?>

Однако, выполнение такого php-скрипта на сервере — привело к ошибкам:

Warning: Cannot modify header information — headers already sent by (output started at Z:…test.php:1) in Z:…test.php on line 4

Warning: Cannot modify header information — headers already sent by (output started at Z:…test.php:1) in Z:…test.php on line 5

Warning: Cannot modify header information — headers already sent by (output started at Z:…test.php:1) in Z:…test.php on line 6

Как же так??? Ведь это пример с официального сайта! Вот тут-то виновата вторая — не очевидная причина.

Не очевидная причина:

Очень просто — кодировка php-файла должна быть UTF-8 без BOM

setcookie

(Просмотрено 2 508 раз, 1 раз за сегодня)

  • #15

Это я тоже проверял.. По Setcookie компилятор проходит..
<?php
$nn = $nickname;
$i = setcookie(«nic», $nickname, time()+3600);
?>

<html>
<head>
<title>123<title>
</head>
<body>
<?
echo $nn.»<br>»;
if($i)
echo «OK!»;
else
echo «BAD!»;
?>
</body>
</html>

При этом он мне говорит что все ок! И значение переменной выводит как пологается.. Переменная передается из формы через POST..

-~{}~ 04.09.06 15:22:

<html>
<head>
<title>123<title>
</head>
<body>

<?php
$nn = $nickname;
$i = setcookie(«nic», $nickname, time()+3600);
?>

</body>
</html>

Ошибки не возникает!

Вот как такое может быть?

-~{}~ 04.09.06 15:24:

<?php
$nn = $nickname;
$i = setcookie(«nic», $nickname, time()+3600);
?>

$nn — это я просто еще одну переменную вводил на всякий случай для последующей проверки.. Основная переменная это $nickname..

-~{}~ 04.09.06 15:28:

ini_set(‘display_errors’,1);
error_reporting(E_ALL);

Все включено… Я не могу понять, паника какаято уже.. Это же ненормально.. Может быть такое что апача которая у них на сервере стоит по каким то причинам игнорирует setcookie?

-~{}~ 04.09.06 15:30:

И есть ли какой либо запрет на использование этой функции?

(PHP 4, PHP 5, PHP 7, PHP 8)

setcookieОтправляет cookie

Описание

setcookie(
    string $name,
    string $value = «»,
    int $expires_or_options = 0,
    string $path = «»,
    string $domain = «»,
    bool $secure = false,
    bool $httponly = false
): bool

setcookie(string $name, string $value = «», array $options = []): bool

После передачи клиенту cookie станут доступны через массив
$_COOKIE при следующей загрузке страницы.
Значения cookie также есть в $_REQUEST.

Список параметров

» RFC 6265 даёт конкретные указания,
как нужно интерпретировать каждый из параметров
setcookie().

name

Название cookie.

value

Значение cookie. Это значение будет сохранено на клиентском компьютере; не
записывайте в cookie секретные данные. Значение, присвоенное cookie c именем
name, допустим, 'cookiename', будет
доступно через $_COOKIE[‘cookiename’].

expires_or_options

Время, когда срок действия cookie истекает. Это метка времени Unix, то есть
количество секунд с начала эпохи.
Один из способов установить значение — добавить количество секунд до истечения срока действия cookie
к результату вызова функции time().
Например, time()+60*60*24*30 установит, что срок действия cookie истекает через 30 дней.
Другой вариант — использовать функцию mktime().
Если задать 0 или пропустить аргумент, срок действия cookie
истечёт с окончанием сессии (при закрытии браузера).

Замечание:

Можно заметить, что expires_or_options принимает в качестве
значения метку времени Unix, а хранит его в формате
Wdy, DD-Mon-YYYY HH:MM:SS GMT. PHP делает это
преобразование автоматически.

path

Путь к директории на сервере, из которой будут доступны cookie. Если задать
'/', cookie будут доступны во всем домене
domain. Если задать '/foo/',
cookie будут доступны только из директории /foo/ и всех
её поддиректорий (например, /foo/bar/) домена
domain. По умолчанию значением является текущая
директория, в которой cookie устанавливается.

domain

(Под)домен, которому доступны cookie. Задание поддомена
(например, 'www.example.com') сделает cookie доступными в нем
и во всех его поддоменах (например, w2.www.example.com). Для того, чтобы
сделать cookie доступными для всего домена (включая поддомены), нужно просто
указать имя домена (то есть 'example.com').

Старые браузеры, следующие устаревшему документу » RFC 2109, могут требовать . перед
доменом, чтобы включались все поддомены.

secure

Указывает на то, что значение cookie должно передаваться от клиента
по защищённому соединению HTTPS. Если задано true, cookie от клиента
будет передано на сервер, только если установлено защищённое соединение.
При передаче cookie от сервера клиенту программист веб-сервера должен следить за тем,
чтобы cookie этого типа передавались по защищённому каналу (стоит обратить внимание на
$_SERVER[«HTTPS»]).

httponly

Если задано true, cookie будут доступны только через HTTP-протокол.
То есть cookie в этом случае не будут доступны скриптовым языкам, вроде
JavaScript. Эта возможность была предложена в качестве меры, эффективно
снижающей количество краж личных данных посредством XSS-атак (несмотря
на то, что поддерживается не всеми браузерами). Стоит однако отметить, что
вокруг этой возможности часто возникают споры о её эффективности и
целесообразности. Может принимать
значения true или false.

options

Ассоциативный массив (array), который может иметь любой из ключей:
expires, path, domain,
secure, httponly и samesite.
При наличии любого другого ключа возникнет ошибка уровня E_WARNING. Значения имеют тот же смысл, как описано в параметрах с соответствующим именем.
Значение элемента samesite должно быть либо None, либо Lax, либо Strict.
Если какая-либо из допустимых опций не указана, её значения по умолчанию
совпадают с значениями по умолчанию для явных параметров.
Если элемент samesite не указан, cookie-атрибут SameSite не установлен.

Возвращаемые значения

Если перед вызовом функции клиенту уже передавался какой-либо вывод (теги,
пустые строки, пробелы, текст и т.п.),
setcookie() потерпит неудачу и вернёт false. Если
setcookie() успешно отработает, то вернёт true.
Это, однако, не означает, что клиентское приложение (браузер) правильно приняло
и обработало cookie.

Список изменений

Версия Описание
8.2.0 Формат даты отправляемых файлов cookie теперь 'D, d M Y H:i:s GMT';
ранее он был 'D, d-M-Y H:i:s T'.
7.3.0 Добавлена альтернативная подпись, поддерживающая массив опций options.
Эта подпись поддерживает также настройку cookie-атрибута SameSite.

Примеры

Ниже представлено несколько примеров, как отправлять cookie:

Пример #1 Пример использования setcookie()


<?php
$value
= 'что-то откуда-то';setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600); /* срок действия 1 час */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);
?>

Стоит отметить, что значение cookie перед отправкой клиенту подвергается
URL-кодированию. При обратном получении значение cookie декодируется и
помещается в переменную, с тем же именем, что и имя cookie. Если вы не хотите,
чтобы значения кодировались, используйте функцию
setrawcookie(). Посмотреть содержимое
наших тестовых cookie можно, запустив один из следующих примеров:


<?php
// Вывести одно конкретное значение cookie
echo $_COOKIE["TestCookie"];// В целях тестирования и отладки может пригодиться вывод всех cookie
print_r($_COOKIE);
?>

Пример #2 Пример удаления cookie посредством setcookie()

Чтобы удалить cookie достаточно в качестве срока действия указать какое-либо
время в прошлом. Это запустит механизм браузера, удаляющий истёкшие cookie.
В примерах ниже показано, как удалить cookie, заданные в предыдущих примерах:


<?php
// установка даты истечения срока действия на час назад
setcookie("TestCookie", "", time() - 3600);
setcookie("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);
?>

Пример #3 setcookie() и массивы

Имеется возможность помещать в cookie массивы. Для этого каждому cookie нужно
дать имя в соответствии с правилами именования массивов. Такая возможность
позволяет поместить столько значений, сколько имеется элементов в массиве.
При обратном получении все эти значения будут помещены в массив с
именем этого cookie:


<?php
// отправка cookie
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");// после перезагрузки страницы, выведем cookie
if (isset($_COOKIE['cookie'])) {
foreach (
$_COOKIE['cookie'] as $name => $value) {
$name = htmlspecialchars($name);
$value = htmlspecialchars($value);
echo
"$name : $value <br />n";
}
}
?>

Результат выполнения данного примера:

three : cookiethree
two : cookietwo
one : cookieone

Замечание:

Использование разделительных символов, таких как [ и ]
как часть имени файла cookie, не соответствует RFC 6265, раздел 4, но предполагается,
что оно поддерживается пользовательскими агентами в соответствии с RFC 6265, раздел 5.

Примечания

Замечание:

Чтобы иметь возможность отправлять вывод скрипта до вызова этой функции,
можно воспользоваться буферизацией. В этом случае весь вывод скрипта помещается
в буфер на сервере и остаётся там, пока вы явно не отправите его браузеру.
Управление буферизацией осуществляется функциями
ob_start() и ob_end_flush() в скрипте,
либо можно задать директиву output_buffering в файле
php.ini или конфигурационных файлах сервера.

Общие замечания:


  • Cookie станут видимыми только после перезагрузки страницы, для которой
    они должны быть видны. Для проверки, правильно ли cookie установились,
    проверьте их при следующей загрузке страницы до истечения срока их
    действия. Срок действия cookie задаётся в параметре
    expires_or_options. Удобно проверять существование cookie простым
    вызовом print_r($_COOKIE);.

  • При удалении cookie должны быть заданы те же параметры, что и при
    установке. Если в качестве значения задать пустую строку,
    а остальные параметры задать соответственно предыдущему вызову,
    установившему cookie, тогда cookie c заданным именем будет удалено с
    клиентской машины. Внутренне это выглядит так: cookie присваивается значение
    'deleted', а срок действия переносится на год в прошлое.

  • Так как установка значения false приведёт к удалению cookie, не следует
    задавать cookie значения булевого типа. Вместо этого можно использовать
    0 для false и 1 для true.

  • Cookie можно именовать, как массивы, и они будут доступны в PHP-скрипте,
    как массивы, но на пользовательской машине они будут храниться в виде
    отдельных записей. Для задания cookie c множеством имён и значений желательно
    использовать функцию explode(). Не рекомендуется для этих
    целей использовать функцию serialize(), так как это
    негативно сказывается на безопасности скрипта.

При многократных вызовах setcookie() функции
выполняются в том порядке, в котором вызывались.

walterquez

10 years ago


Instead of this:

<?php setcookie( "TestCookie", $value, time()+(60*60*24*30) ); ?>



You can this:

<?php setcookie( "TestCookie", $value, strtotime( '+30 days' ) ); ?>

Bachsau

10 years ago


Want to remove a cookie?

Many people do it the complicated way:
setcookie('name', 'content', time()-3600);

But why do you make it so complicated and risk it not working, when the client's time is wrong? Why fiddle around with time();

Here's the easiest way to unset a cookie:
setcookie('name', 'content', 1);

Thats it.


Anonymous

2 years ago


Just an example to clarify the use of the array options, especially since Mozilla is going to deprecate / penalise the use of SameSite = none,  which is used by default if not using array options.

<?php
$arr_cookie_options
= array (
               
'expires' => time() + 60*60*24*30,
               
'path' => '/',
               
'domain' => '.example.com', // leading dot for compatibility or use subdomain
               
'secure' => true,     // or false
               
'httponly' => true,    // or false
               
'samesite' => 'None' // None || Lax  || Strict
               
);
setcookie('TestCookie', 'The Cookie Value', $arr_cookie_options);   
?>


paul nospam AT nospam sitepoint dot com

16 years ago


Note when setting "array cookies" that a separate cookie is set for each element of the array.

On high traffic sites, this can substantially increase the size of subsequent HTTP requests from clients (including requests for static content on the same domain).

More importantly though, the cookie specification says that browsers need only accept 20 cookies per domain.  This limit is increased to 50 by Firefox, and to 30 by Opera, but IE6 and IE7 enforce the limit of 20 cookie per domain.  Any cookies beyond this limit will either knock out an older cookie or be ignored/rejected by the browser.


nacho at casinelli dot com

5 years ago


It's worth a mention: you should avoid dots on cookie names.

<?php
// this will actually set 'ace_fontSize' name:
setcookie( 'ace.fontSize', 18 );
?>


gabe at fijiwebdesign dot com

15 years ago


If you want to delete all cookies on your domain, you may want to use the value of:

<?php $_SERVER['HTTP_COOKIE'] ?>

rather than:

<?php $_COOKIE ?>

to dertermine the cookie names.
If cookie names are in Array notation, eg: user[username]
Then PHP will automatically create a corresponding array in $_COOKIE. Instead use $_SERVER['HTTP_COOKIE'] as it mirrors the actual HTTP Request header.

<?php// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
   
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
    foreach(
$cookies as $cookie) {
       
$parts = explode('=', $cookie);
       
$name = trim($parts[0]);
       
setcookie($name, '', time()-1000);
       
setcookie($name, '', time()-1000, '/');
    }
}
?>


Anonymous

15 years ago


something that wasn't made clear to me here and totally confused me for a while was that domain names must contain at least two dots (.), hence 'localhost' is invalid and the browser will refuse to set the cookie! instead for localhost you should use false.

to make your code work on both localhost and a proper domain, you can do this:

<?php

$domain

= ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie('cookiename', 'data', time()+60*60*24*365, '/', $domain, false);?>


byz

6 years ago


exmaple with test.com;

setcookie('empty_domain','value',time()+3600,'') 
equal       test.com

setcookie('test_com_domain','value',time()+3600,'','test.com')  
equal       .test.com

setcookie('dot_test_com_domain','value',time()+3600,'','.test.com') 
equal       .test.com

ps:   .test.com   has its self    and child domain


user at example.com

3 years ago


As of PHP 7.3.0 the setcookie() method supports the SameSite attribute in its options and will accept None as a valid value.

For earlier versions of PHP,  you can set the header() directly:

header('Set-Cookie: cross-site-cookie=bar; SameSite=None; Secure');


lferro9000 at gmail dot com

6 years ago


Of notice, the cookie when set with a zero expire or ommited WILL not expire when the browser closes.

What happens is that the browser, when closes the window, if it is a well behaved browser, will delete the cookie from the cookie store.

However, the cookie will survive in the server until the garbage collector removes the session, which will happen only when it kicks in and checks the specified session is out of bounds of the setting stated in:

http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime

Please check also:

http://php.net/manual/en/session.security.ini.php

And in case of doubt, PHP runs on the webserver and has no way whatsoever to interact with a browser apart from receiving requests and answering with responses, so assuming that a cookie will be removed from a browser is just an "hint" for the browser. There is no warranty that such will happen as instructed.

That is one of the reasons why the cookie values sent to browsers by some platforms are encrypted and timestamped, to ensure that they are actual and not tampered.


ellert at vankoperen dot nl

8 years ago


Caveat: if you use URL RewriteRules to get stuff like this: domain.com/bla/stuf/etc into parameters, you might run into a hickup when setting cookies.
At least in my setup a change in one of the parameters resulted in the cookie not being 'there' anymore.
The fix is simple: specify the domain. '/' will usualy do fine.

MrXCol

11 years ago


If you're having problem with IE not accepting session cookies this could help:

It seems the IE (6, 7, 8 and 9) do not accept the part 'Expire=0' when setting a session cookie. To fix it just don't put any expire at all. The default behavior when the 'Expire' is not set is to set the cookie as a session one.

(Firefox doesn't complains, btw.)


gareth at gw126 dot com

16 years ago


You can use cookies to prevent a browser refresh repeating some action from a form post... (providing the client is cookie enabled!)

<?php

//Flag up repeat actions (like credit card transaction, etc)

if(count($_POST)>0) {

   
$lastpost= isset($_COOKIE['lastpost']) ? $_COOKIE['lastpost'] : '';

    if(
$lastpost!=md5(serialize($_POST))) {

       
setcookie('lastpost', md5(serialize($_POST)));

       
$_POST['_REPEATED']=0;

    } else {

       
$_POST['_REPEATED']=1;

    }

}
//At this point, if $_POST['_REPEATED']==1, then  the user

//has hit the refresh button; so don't do any actions that you don't

//want to repeat!

?>



Hope that helps :)

Gareth


bluewaterbob

15 years ago


if you are having problems seeing cookies sometimes or deleting cookies sometimes, despite following the advice below, make sure you are setting the cookie with the domain argument. Set it with the dot before the domain as the examples show: ".example.com".  I wasn't specifying the domain, and finally realized I was setting the cookie when the browser url had the http://www.example.com and later trying to delete it when the url didn't have the www. ie. http://example.com. This also caused the page to be unable to find the cookie when the www. wasn't in the domain.  (When you add the domain argument to the setcookie code that creates the cookie, make sure you also add it to the code that deletes the cookie.)

dmitry dot koterov at gmail dot com

7 years ago


Note that at least in PHP 5.5 setcookie() removes previously set cookies with the same name (even if you've set them via header()), so previously fired Set-Cookie headers with e.g. PHPSESSID name are not flushed to the browser. Even headers_list() doesn't see them after session_start():

header("Set-Cookie: PHPSESSID=abc; path=/; domain=.sub.domain.com");
header("Set-Cookie: PHPSESSID=abc; path=/; domain=.domain.com");
print_r(headers_list()); // here you see two Set-Cookie headers with domains for PHPSESSID
session_id('abc');
session_start();
print_r(headers_list()); // here you don't; you see only one Set-Cookie produced by session_start()


Eric

13 years ago


The server my php code is running on has sessions disabled so I am forced to store a fair bit of arbitrary data in cookies.  Using array names was impractical and problematic, so I implemented a splitting routine.  I do not serialize any class instances, just arrays and simple objects.

In a nutshell, when setting a cookie value, I serialize it, gzcompress it, base64 encode it, break it into pieces and store it as a set of cookies.  To fetch the cookie value I get the named piece then iterate through piece names rebuilding the base64 data, then reverse the rest of the process.  The only other trick is deleting the pieces correctly.

Sessions are better, but if they are not available this is a viable alternative.  I chose gz over bz for compression because it looked faster with only slightly worse ratios.

Here is a simplified version of my implementation.  This is a good starting point but is not suitable for most uses.  For example, the domain and path are hard coded and no return values are checked for validity.

<?php

define
( 'COOKIE_PORTIONS' , '_piece_' );

function

clearpieces( $inKey , $inFirst ) {

   
$expire = time()-3600;

   
    for (

$index = $inFirst ; array_key_exists( $inKey.COOKIE_PORTIONS.$index , $_COOKIE ) ; $index += 1 ) {

       
setcookie( $inKey.COOKIE_PORTIONS.$index , '' , $expire , '/' , '' , 0 );

        unset(
$_COOKIE[$inKey.COOKIE_PORTIONS.$index] );

    }

}

function

clearcookie( $inKey ) {

   
clearpieces( $inKey , 1 );

   
setcookie( $inKey , '' , time()-3600 , '/' , '' , 0 );

    unset(
$_COOKIE[$inKey] );

}

function

storecookie( $inKey , $inValue , $inExpire ) {

   
$decode = serialize( $inValue );

   
$decode = gzcompress( $decode );

   
$decode = base64_encode( $decode );
$split = str_split( $decode , 4000 );//4k pieces

   
$count = count( $split );

   
    for (

$index = 0 ; $index < $count ; $index += 1 ) {

       
$result = setcookie( ( $index > 0 ) ? $inKey.COOKIE_PORTIONS.$index : $inKey , $split[$index] , $inExpire , '/' , '' , 0 );

    }
clearpieces( $inKey , $count );

}

function

fetchcookie( $inKey ) {

   
$decode = $_COOKIE[$inKey];

   
    for (

$index = 1 ; array_key_exists( $inKey.COOKIE_PORTIONS.$index , $_COOKIE ) ; $index += 1 ) {

       
$decode .= $_COOKIE[$inKey.COOKIE_PORTIONS.$index];

    }
$decode = base64_decode( $decode );

   
$decode = gzuncompress( $decode );

   
    return

unserialize( $decode );

}

?>


ahmetantmen at msn dot com

16 years ago


You can be sure about the cookie files contents weren't changed.

<?php

$Seperator

= '--';
$uniqueID = 'Ju?hG&F0yh9?=/6*GVfd-d8u6f86hp';
$Data = 'Ahmet '.md5('123456789');setcookie('VerifyUser', $Data.$Seperator.md5($Data.$uniqueID));

if (

$_COOKIE) {
  
$Cut = explode($Seperator, $_COOKIE['VerifyUser']);
   if (
md5($Cut[0].$uniqueID) === $Cut[1]) {
      
$_COOKIE['VerifyUser'] = $Cut[0];
   } else {
       die(
'Cookie data is invalid!!!');
   }
}

echo

$_COOKIE['VerifyUser'];?>

Create a unique id for your site and create a hash with md5($Data.$uniqueID). Attacker can understant that it must be re-hash after change cookie content.
But doesn't. Because cannot guess your unique id. Seperate your hash and data with seperator and send that cookie. Control that hash of returned value and your unique id's is same returned hash. Otherwise you have to stop attack. Sorry for my poor english!


hansel at gretel dot com

16 years ago


The following code snippet combines abdullah's and Charles Martin's examples into a powerful combination function (and fixes at least one bug in the process):

<?php
 
function set_cookie_fix_domain($Name, $Value = '', $Expires = 0, $Path = '', $Domain = '', $Secure = false, $HTTPOnly = false)
  {
    if (!empty(
$Domain))
    {
     
// Fix the domain to accept domains with and without 'www.'.
     
if (strtolower(substr($Domain, 0, 4)) == 'www.'$Domain = substr($Domain, 4);
     
$Domain = '.' . $Domain;// Remove port information.
     
$Port = strpos($Domain, ':');
      if (
$Port !== false$Domain = substr($Domain, 0, $Port);
    }
header('Set-Cookie: ' . rawurlencode($Name) . '=' . rawurlencode($Value)
                          . (empty(
$Expires) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', $Expires) . ' GMT')
                          . (empty(
$Path) ? '' : '; path=' . $Path)
                          . (empty(
$Domain) ? '' : '; domain=' . $Domain)
                          . (!
$Secure ? '' : '; secure')
                          . (!
$HTTPOnly ? '' : '; HttpOnly'), false);
  }
?>

Basically, if the domain parameter is supplied, it is converted to support a broader range of domains.  This behavior may or may not be desireable (e.g. could be a security problem depending on the server) but it makes cookie handling oh-so-much-nicer (IMO).


Anonymous

2 years ago


To add the "samesite" attribute, you can concatenate it to the path option until it gets implemented/documented properly
Eg:
<?php
    setcookie
('cookie_name', 'cookie_value', 0, '/; SameSite=strict');
?>

Anonymous

12 years ago


A period in a cookie name (like user.name) seems to show up in the $_COOKIE array as an underscore (so user_name). This means that for example $_COOKIE["user_name"] must be used to read a cookie that has been set with setcookie("user.name" ...), which is already rather confusing.

Furthermore the variable $_COOKIE["user_name"] will retain the value set by setcookie("user.name" ...) and no amount of calling setcookie("user_name" ...) will alter this value. This is rather trivially fixed by clearing the "user.name" cookie, but it can take a while to realize this since there's only "user_name" in $_COOKIE.

Hope this saves someone some time.


Carl V

17 years ago


If you want to delete all the cookies set by your domain, you may run the following:

<?php
$cookiesSet
= array_keys($_COOKIE);
for (
$x=0;$x<count($cookiesSet);$x++) setcookie($cookiesSet[$x],"",time()-1);
?>

Very useful when doing logout scripts and the cookie name may have changed (long story).


stovenator at gmail dot com

16 years ago


If you are having issues with IE7 and setcookie(), be sure to verify that the cookie is set via http for http sites, and https for https site.

Also, if the time is incorrect on your server, IE7 will also disallow those cookies from being set.


jdknock (at) gMaIl (dot) com

11 years ago


IE7 can have trouble with settings cookies that are embedded in an iframe. The problem lies with a W3C standard called Platform for Privacy Preferences or P3P for short.

To overcome, include the header:

header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');

before setting the cookie.


cwillard at fastmail dot fm

15 years ago


If you're looking to set multiple values in your cookie (rather than setting multiple cookies) you might find these useful.

<?php
function build_cookie($var_array) {
  if (
is_array($var_array)) {
    foreach (
$var_array as $index => $data) {
     
$out.= ($data!="") ? $index."=".$data."|" : "";
    }
  }
  return
rtrim($out,"|");
}

function

break_cookie ($cookie_string) {
 
$array=explode("|",$cookie_string);
  foreach (
$array as $i=>$stuff) {
   
$stuff=explode("=",$stuff);
   
$array[$stuff[0]]=$stuff[1];
    unset(
$array[$i]);
  }
  return
$array;
}
?>
Hopefully someone finds these useful.


mkmohsinali at gmail dot com

11 years ago


#cookies.php
/*This code will demonstrate use of cookies with PHP
It is very easy to understand and is better for beginner to
understand and get idea about power of cookies when used
with PHP.Here we give user a form to choose colors he/she
likes for website and when he/she visits site again within one
hour his/her settings are saved and read from cookie
and he/she doesn't have to set the page color and page
text color again.You can change time from 3600
seconds to whatever you deem appropriate in your case.
if you don't understand anything please email me*/

<?php
#checking if form has been submitted
if (isset($_POST['submitted'])){
#if yes (form is submitted) assign values from POST array to variables
$newbgColor=$_POST['bgColor'];
$newtxtColor=$_POST['txtColor'];
#set cookies
setcookie("bgColor",$newbgColor,time()+3600);
setcookie("txtColor",$newtxtColor,time()+3600);

}

#in case user has come for first time and cookies are not set then
if ((!isset($_COOKIE['bgColor']) ) && (!isset($_COOKIE['txtColor']))){
$bgColor = "Black";
$txtColor="White";
}
#if cookies are set then use them
else{
$bgColor = $_COOKIE['bgColor'];
$txtColor = $_COOKIE['txtColor'];
}
?>
<!-- HTML Page-->
<html>
<body bgcolor="<?php echo $bgColor ?>" text="<?php echo $txtColor ?>">
<form action= "<?php echo $_SERVER['PHP_SELF']; ?>" method ="POST">
<p>Body Color:</p>
<select name=bgColor>
<option value ="Red">Red</option>
<option value ="Green" selected>Green</option>
<option value ="Blue">Blue</option>
<option value ="Yellow">Yellow</option>
<option value ="Black">Black</option>
<option value ="Brown">Brown</option>
<option value ="White">White</option>
</select>
<p>Text Color:</p>
<select name=txtColor>
<tion value ="Red">Red</option>
<option value ="Green" selected>Green</option>
<option value ="Blue">Blue</option>
<option value ="Yellow">Yellow</option>
<option value ="Black">Black</option>
<option value ="Brown">Brown</option>
<option value ="White">White</option>
</select>
<input type ="hidden" name="submitted" value="true"></br>
<input type="submit" value="remind">
</form>
</body>
</html>


jonathan dot bergeron at rve dot ulaval dot ca

15 years ago


About the delete part, I found that Firefox only remove the cookie when you submit the same values for all parameters, except the date, which sould be in the past. Submiting blank values didn't work for me.

Example :

- set -

<?php setcookie( "name", "value", "future_timestamp", "path", "domain" ); ?>



- delete -

<?php setcookie( "name", "value", "past_timestamp", "path", "domain" ); ?>



Jonathan


jay at w3prodigy dot com

12 years ago


You can also delete cookies by supplying setcookie an empty value.

setcookie("w3p_cookie", "");


chris at styl dot ee

11 years ago


I was searching for a simple example of creating a cookie, storing a random number and updating it on refresh. I couldn't find one so I had to figure it out on my own....

- - - -
One thing to *NOTE* is technically you can't update a cookie, you can only overwrite it with a new one with the same name.

- - - -

This creates a random number, stores it in a cookie, then references it on refresh, checks for duplicates and does necessary correction, then stores it again, rinse and repeat...

<?php
ob_start
();
$MaxCount = 4;// set the max of the counter, in my tests "4" = (0,1,2,3) I adjusted below (+1) to get a "real" 4 (0,1,2,3,4) this is in reality 5 keys to humans, you can adjust script to eliminate "0", but my script makes use of the "0"$random =(rand()%($MaxCount+1));//give me a random number limited by the max, adding "1" because computers start counting at "0"if(!isset($_COOKIE['random'])){// check if random number cookie is not set
    //echo"not set";
   
setcookie('random', $random);//set the cookie for the first time
   
}else{
   
$lastRandom= $_COOKIE['random']; //hold the last number if it was set before
   
if($lastRandom == $random){//some logic to avoid repeats
    
if($random < $MaxCount){//if below max, add 1
       
$random++;
       
//echo "under the max, adding 1, ";   
   
}elseif($random >= ($MaxCount-1)){// if for some reason the random number is more than max or equal to it -1, and an additional -1 for max count in initial var (so in reality this -1 from intial max var, and -1 from $random which should be the same number)
           
$random--;
           
//echo "hit the max, subtracting 1, ";
       
}else{
       
$random++;
       
//echo "no case match, adding 1, ";   
       
}
   
//echo "(".$lastRandom.", ".$random. "), they matched initally - was it fixed?";
   
}else{
   
//echo "(".$lastRandom.", ".$random. "), they DO NOT match";
   
setcookie('random', $random);   
    }
   
//echo"is set: {$_COOKIE['random']}";
}ob_end_flush();?>


laffen

13 years ago


Note that the $_COOKIE variable not will hold multiple cookies with the same name. It is legitimate to set two cookies with the same name to the same host where the sub domain is different.
<?php
setcookie
("testcookie", "value1hostonly", time(), "/", ".example.com", 0, true);
setcookie("testcookie", "value2subdom", time(), "/", "subdom.example.com", 0, true);
?>
The next request from the browser will have both cookies in the $_SERVER['HTTP_COOKIE'] variable, but only one of them will be found in the $_COOKIE variable. Requests to subdom.example.com will have both cookies, while browser request to example.com or www.example.com only sends the cookie with the "value1hostonly" value.

<?php
$kaker
= explode(";", $_SERVER['HTTP_COOKIE']);
foreach(
$kaker as $val){
   
$k = explode("=", $val);
    echo
trim($k[0]) . " => " . $k[1];
}
// output
testcookie => value1hostonly
testcookie
=> value2subdom

?>


Anonymous

2 years ago


Chrome versions prior to version 67 reject samesite=none cookies. And starting in Chrome version 84 samesite=none cookies without the secure attribute are also rejected. But that doesn't mean you can't set cookies on an unencrypted connection. The simple way around it is to use browser sniffing to detect samesite=none compatible browsers:

$cookie_string = 'set-cookie: name=value';

if (!preg_match('/Chrom[^ /]+/([0-9]+)[.0-9]* /', $_SERVER['HTTP_USER_AGENT'], $matches) || $matches[1]>66 && $matches[1]<84) {// match samesite=none compatible browsers
    $cookie_string.= '; samesite=none';
}

header($cookie_string, false);// set cookie


isooik at gmail-antispam dot com

14 years ago


Here's a more advanced version of the php setcookie() alternative function:

<?php
/**

     * A better alternative (RFC 2109 compatible) to the php setcookie() function

     *

     * @param string Name of the cookie

     * @param string Value of the cookie

     * @param int Lifetime of the cookie

     * @param string Path where the cookie can be used

     * @param string Domain which can read the cookie

     * @param bool Secure mode?

     * @param bool Only allow HTTP usage?

     * @return bool True or false whether the method has successfully run

     */

   
function createCookie($name, $value='', $maxage=0, $path='', $domain='', $secure=false, $HTTPOnly=false)

    {

       
$ob = ini_get('output_buffering');
// Abort the method if headers have already been sent, except when output buffering has been enabled

       
if ( headers_sent() && (bool) $ob === false || strtolower($ob) == 'off' )

            return
false;

        if ( !empty(

$domain) )

        {

           
// Fix the domain to accept domains with and without 'www.'.

           
if ( strtolower( substr($domain, 0, 4) ) == 'www.' ) $domain = substr($domain, 4);

           
// Add the dot prefix to ensure compatibility with subdomains

           
if ( substr($domain, 0, 1) != '.' ) $domain = '.'.$domain;
// Remove port information.

           
$port = strpos($domain, ':');

            if (

$port !== false ) $domain = substr($domain, 0, $port);

        }
// Prevent "headers already sent" error with utf8 support (BOM)

        //if ( utf8_support ) header('Content-Type: text/html; charset=utf-8');
header('Set-Cookie: '.rawurlencode($name).'='.rawurlencode($value)

                                    .(empty(
$domain) ? '' : '; Domain='.$domain)

                                    .(empty(
$maxage) ? '' : '; Max-Age='.$maxage)

                                    .(empty(
$path) ? '' : '; Path='.$path)

                                    .(!
$secure ? '' : '; Secure')

                                    .(!
$HTTPOnly ? '' : '; HttpOnly'), false);

        return
true;

    }
?>



Regards,

Isaak


bocian941 at pawno dot pl

11 years ago


My 2 functions to use "live cookies":

<?php

   
function SetCookieLive($name, $value='', $expire = 0, $path = '', $domain='', $secure=false, $httponly=false)

    {

       
$_COOKIE[$name] = $value;

        return
setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);

    }

    function

RemoveCookieLive($name)

    {

        unset(
$_COOKIE[$name]);

        return
setcookie($name, NULL, -1);

    }

?>


J?rg Aldinger

19 years ago


When using your cookies on a webserver that is not on the standard port 80, you should NOT include the :[port] in the "Cookie domain" parameter, since this would not be recognized correctly.

I had the issue working on a project that runs on multiple servers (development, production, etc.). One of the servers is running on a different port (together with other websites that run on the same server but on different ports).

Anonymous

4 years ago


I haven't seen this mentioned here and had a lot of issues (and created a lot of stupid hacks) before I figured this out.

If you have a couple of environments for example, and are trying to set cookies on two domains:

example.com (main site)
dev.example.com (dev site)

In this case your (same named) cookies will interfere with each other if you're trying to set cookies with the domain parameter. 

Simply use an empty string for the domain parameter and the cookies will refer to each host separately.

If you use the subdomain www. on the main site this won't be an issue, but without a subdomain you'll have issues with reading each others' cookies.


Hagrael

БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

1

08.09.2010, 14:38. Показов 20033. Ответов 25

Метки нет (Все метки)


Вот у меня код:

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
include("connect.php");
$result=mysql_query("SELECT login,password FROM users");
while ($myrow=mysql_fetch_assoc($result)) {
    if ($_POST['login']==$myrow['login'] and $_POST['password']==$myrow['password']) {
        setcookie("log","AAA",time()+10);
        $_SESSION['userloggedin']=true;
        $_SESSION['login']=$myrow['login'];
        break;
    }
}
 
if ($_SESSION['userloggedin']!=true) {
    $_SESSION['mistace']="not_right_password";
    if ($_POST['login']) {$_SESSION['sentlogin']=$_POST['login'];}
    header("Location: ".$_SERVER['HTTP_REFERER']);
    exit();
} else {
    $_SESSION['mistace']="user_logged_in";
    if ($_SERVER['HTTP_REFERER']) {
        header("Location: ".$_SERVER['HTTP_REFERER']);
    } else {
        header("Location: ../index.php");
    }
    exit();
}

Но куки не ставятся((( В чём дело?

Добавлено через 5 минут
Дело в том, что куки видны только для данной страницы, на странице в пред. каталоге не рабоает, хотя хост тот же.



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

08.09.2010, 14:38

Ответы с готовыми решениями:

Не работает setcookie
Доброго времени суток.Дело в том,что при переносе кода на хостинг у меня возникла проблема с…

SetCookie и БД
Приветствую вас, братья программисты! :handshake: У меня появилась проблема в написании одного…

setcookie
Проблема в куках. На одной странице они создаются, на другой выводятся. Код первой страницы:…

Ошибка setcookie
Здравствуйте. Такая проблема. Скрипт голосования не сохраняет куки. Скрипт:
&lt;?php
include_once…

25

Nazz

WEB-developer

898 / 729 / 80

Регистрация: 12.03.2009

Сообщений: 2,804

Записей в блоге: 2

08.09.2010, 15:49

2

а так что пишет?

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
error_reporting(E_ALL);
include("connect.php");
$result=mysql_query("SELECT login,password FROM users");
while ($myrow=mysql_fetch_assoc($result)) {
        if ($_POST['login']==$myrow['login'] and $_POST['password']==$myrow['password']) {
                setcookie("log","AAA",time()+10);
                $_SESSION['userloggedin']=true;
                $_SESSION['login']=$myrow['login'];
                break;
        }
}
 
if ($_SESSION['userloggedin']!=true) {
        $_SESSION['mistace']="not_right_password";
        if ($_POST['login']) {$_SESSION['sentlogin']=$_POST['login'];}
        header("Location: ".$_SERVER['HTTP_REFERER']);
        exit();
} else {
        $_SESSION['mistace']="user_logged_in";
        if ($_SERVER['HTTP_REFERER']) {
                header("Location: ".$_SERVER['HTTP_REFERER']);
        } else {
                header("Location: ../index.php");
        }
        exit();
}



1



Hagrael

БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

08.09.2010, 18:36

 [ТС]

3

Nazz,

PHP
1
Warning: Cannot modify header information - headers already sent by (output started at Z:homelocalhostwwwcursphpscriptscomein.php:8) in Z:homelocalhostwwwcursphpscriptscomein.php on line 23

Но и без этого он показывает то же самое. Cookies создаются только для этой страницы!



0



1957 / 796 / 89

Регистрация: 03.11.2009

Сообщений: 3,066

Записей в блоге: 2

08.09.2010, 18:48

4

Hagrael, это весь код? Просто в ошибке сказано, что вывод был в 8 строке этого файла… А там

Цитата
Сообщение от Nazz
Посмотреть сообщение

$_SESSION[‘login’]=$myrow[‘login’];

Добавлено через 2 минуты
Hagrael, а в браузере есть устанавливаемая кука?Или она удаляется при переходе на другую страницу? В таком случае, нужно посмотреть, как Вы используете эту куку на другой странице…



1



БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

08.09.2010, 19:35

 [ТС]

5

romchiksoad, извините, но я не понял.



0



1957 / 796 / 89

Регистрация: 03.11.2009

Сообщений: 3,066

Записей в блоге: 2

08.09.2010, 20:59

6

Hagrael, ничего страшного Вы весь код скопировали на форум?
Как Вы работаете с куками на других страницах?



1



Hagrael

БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

09.09.2010, 13:34

 [ТС]

7

romchiksoad, я пишу

PHP
1
print_r($_COOKIE)

выводит только PHPSESSID.

Добавлено через 11 секунд
И да, это весь код.



0



68 / 61 / 11

Регистрация: 10.08.2009

Сообщений: 226

09.09.2010, 16:40

8

Лучший ответ Сообщение было отмечено Kerry_Jr как решение

Решение

Ошибка говорит о том, что перед вызовом setcookie где-то что-то уже выводится. А этого быть не должно. Куки должны устанавливаться до любого другого вывода.

И еще. Автор извини, но это бредовый способ проверять логин-пароль, прокручивая в цикле все строки базы. SQL жеж нуна использовать по прямому назначению.



0



Hagrael

БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

09.09.2010, 16:55

 [ТС]

9

ILA, типа

PHP
1
$result=mysql_query("SELECT password FROM users WHERE login='".$_POST['login']."'");

так надо?



0



WEB-developer

898 / 729 / 80

Регистрация: 12.03.2009

Сообщений: 2,804

Записей в блоге: 2

09.09.2010, 17:51

10

да, именно так будет лутше))



0



БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

09.09.2010, 18:47

 [ТС]

11

)) Действительно, а то так сервер загружает это. Но тут проблема, а что если данного логина нет? Тогда $result=false, и надо выполнять проверку перед mysql_fetch_array(), да?



0



romchiksoad

1957 / 796 / 89

Регистрация: 03.11.2009

Сообщений: 3,066

Записей в блоге: 2

09.09.2010, 19:29

12

Hagrael, если такой записи в таблице нет, то mysql_query вернет ноль строк. FALSE вернется при ошибке в запросе. Таким образом, можно ограничиться такой проверкой:

PHP
1
2
3
4
5
6
if ( mysql_num_rows ( $query ) == 1 ) {
//Продолжаем работу
}
else {
//Пользователь не найден
}



1



БТР — мой друг

333 / 277 / 47

Регистрация: 07.01.2010

Сообщений: 1,932

09.09.2010, 20:03

 [ТС]

13

Ясно. А что собственно с setcookie() ?



0



LORDofLINEAGE

39 / 39 / 17

Регистрация: 19.01.2013

Сообщений: 190

10.07.2015, 16:54

14

PHP
1
setcookie("log","AAA",time()+10, '/');

нужно указать путь, где должна «работать» кука



0



pav1uxa

10.07.2015, 20:26

Не по теме:

LORDofLINEAGE, Вы что, серьезно? Теме 5 лет.



0



22 / 20 / 5

Регистрация: 29.02.2016

Сообщений: 592

20.07.2016, 09:21

16

нашёл 50% ответа!!! команда создания кук работает только вверху страницы! или в странице пустой.



0



Kerry_Jr

20.07.2016, 09:37

Не по теме:

D7ILeucoH, еще один умник :wall:. На дату крайнего перед вашим сообщения смотреть нужно.



0



D7ILeucoH

22 / 20 / 5

Регистрация: 29.02.2016

Сообщений: 592

20.07.2016, 12:09

18

и что? теме 6 лет и ни одного дельного ответа! а я нашёл! надо вот так делать, правда симбиоз с JS:

PHP
1
2
3
4
echo('<script language="JavaScript">
var dated = new Date(new Date().getTime() + 60*1000*60*24*365); //кука на год
document.cookie = "'.$name.'='.$value.'; path=/; expires=" + dated.toUTCString();
</script>');



0



Эксперт PHP

4833 / 3848 / 1596

Регистрация: 24.04.2014

Сообщений: 11,294

20.07.2016, 12:23

19

Цитата
Сообщение от D7ILeucoH
Посмотреть сообщение

и что? теме 6 лет и ни одного дельного ответа!

А твой ответ разве дельный?



0



Эксперт PHP

5735 / 4122 / 1500

Регистрация: 06.01.2011

Сообщений: 11,251

20.07.2016, 12:50

20

Не по теме:

Цитата
Сообщение от D7ILeucoH
Посмотреть сообщение

команда создания кук работает только вверху страницы! или в странице пустой.

Надо срочно разработчикам всяких симфоней и ларавелей сообщить. А-то они зачем-то весь проект по разным файлам разбрасывают.
А нужно же в одном! Причём cookie посылать первой строкой и устанавливать с помощью JS.
Чел

код Библии

Web взломал!

Если без шуток — D7ILeucoH, прочтите хотя бы документацию на http://php.net.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

20.07.2016, 12:50

20

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Почему айтюнс выдает ошибку при восстановлении iphone
  • Почему samsung account выдает ошибку