A
A
Alexander2021-01-13 22:53:39
1C-Bitrix
Alexander, 2021-01-13 22:53:39

What to fix (what could be the error) to write data to cookies through the Bitrix API?

There is a code that adds to favorites.
If the user is authorized, then we write data to the user, if not authorized, then to cookies.
I don’t understand what’s wrong with cookies, I don’t write.

global $APPLICATION;
use Bitrix\Main;
use Bitrix\Main\Localization\Loc;
use Bitrix\Main\Security\Sign\Signer;
use Bitrix\Main\UI\Extension;
use Bitrix\Main\Web\Json;
use Bitrix\Main\Application;
use Bitrix\Main\Web\Cookie;



$GLOBALS['APPLICATION']->RestartBuffer();
/* Избранное */

if($_GET['id'])
{
    if(!$USER->IsAuthorized()) // Для неавторизованного
    {
        $arElements = unserialize($APPLICATION->get_cookie('favorites'));

        if(!in_array($_GET['id'], $arElements))
        {
            $arElements[] = $_GET['id'];
            $result = 1; // Датчик. Добавляем
        }
        else {
            $key = array_search($_GET['id'], $arElements); // Находим элемент, который нужно удалить из избранного
            unset($arElements[$key]);
            $result = 2; // Датчик. Удаляем
        }

        $cookie = new Cookie("favorites", serialize($arElements), time() + 60*60*24*60, '', 'sitename');
        $cookie->setDomain($context->getServer()->getHttpHost());
        $cookie->setHttpOnly(false);
        $cookie->setSecure(false);
        $context->getResponse()->addCookie($cookie);
        $context->getResponse()->flush("");


    }
    else { // Для авторизованного
        $idUser = $USER->GetID();
        $rsUser = CUser::GetByID($idUser);
        $arUser = $rsUser->Fetch();
        $arElements = $arUser['UF_FAVORITES'];  // Достаём избранное пользователя
        if(!in_array($_GET['id'], $arElements)) // Если еще нету этой позиции в избранном
        {
            $arElements[] = $_GET['id'];
            $result = 1;
        }
        else {
            $key = array_search($_GET['id'], $arElements); // Находим элемент, который нужно удалить из избранного
            unset($arElements[$key]);
            $result = 2;
        }
        $USER->Update($idUser, Array("UF_FAVORITES" => $arElements)); // Добавляем элемент в избранное
    }
}
/* Избранное */
echo json_encode($result);
die();


what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Emelyanov, 2021-01-14
@kikher

\Bitrix\Main\Context::getCurrent()->getResponse()->writeHeaders();

I
Ilya, 2021-01-13
@New_Horizons

Answering the title question: setcookie
Too lazy to read a footcloth)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question