E
E
Ekaterina2021-12-11 15:01:23
PHP
Ekaterina, 2021-12-11 15:01:23

How to defeat 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 coocies, I don’t write.

<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");
$APPLICATION->SetTitle(" ");
$GLOBALS['APPLICATION']->RestartBuffer();
use Bitrix\Main\Application;
use Bitrix\Main\Web\Cookie;
$application = Application::getInstance();
$context = $application->getContext(); 

/* Избранное */
   global $APPLICATION;
   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); $cookie->setDomain($context->getServer()->getHttpHost()); 
    $cookie->setHttpOnly(false);  $context->getResponse()->addCookie($cookie); 
    $context->getResponse()->flush("");
    \Bitrix\Main\Context::getCurrent()->getResponse()->flush('');
        echo json_encode($result);
        die();
//  Ниже код - иконки загораются, и счетчик работает, но переходишь на страницу избранных товаров, а там пусто...
//header('Content-Type: application/x-javascript; charset='.LANG_CHARSET); 
   //     echo \Bitrix\Main\Web\Json::encode($result);
   //     \Bitrix\Main\Application::getInstance()->end();
     //   echo json_encode($result);
       // die();
      }
      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(); ?>

<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Ekaterina, 2021-12-11
@Ekaterina002

Fixed:
//save session in Bitrix
$session = \Bitrix\Main\Application::getInstance()->getSession();
//$arElements = unserialize($APPLICATION->get_cookie('favorites'));
$arElements = unserialize($session->get('favorites')/*$APPLICATION->get_cookie('favorites')*/);
if(!in_array($_GET['id'], $arElements))
{
$arElements[] = $_GET['id'];
$result = 1; // Sensor. Add
}
else {
$key = array_search($_GET['id'], $arElements); // Find the element to remove from the favorites
unset($arElements[$key]);
$result = 2; // Sensor. Remove
}
$session->set('favorites', serialize($arElements));
$cookie = new Cookie("favorites", serialize($arElements), time() + 60*60*24*60);
$cookie->setDomain($context->getServer()->getHttpHost());
$cookie->setHttpOnly(false);
$context->getResponse()->addCookie($cookie);
$context->getResponse()->flush("");*/
in component_epolog.php
if(!$USER->IsAuthorized())
{
$session = \Bitrix\Main\Application::getInstance()-> getSession();
$arFavorites = unserialize($session->get('favorites'));
//$arElements = unserialize($APPLICATION->get_cookie('favorites'));
//$arFavorites = unserialize($APPLICATION->get_cookie("favorites"));
//print_r($arFavorites);
if(!$USER->IsAuthorized()) // For unauthorized
{
global $APPLICATION;
$session = \Bitrix\Main\Application::getInstance()->getSession();
$favorites = unserialize($session->get('favorites'));

A
Artem Zhitnik, 2021-12-11
@art-zhitnik

Your header and footer are connected, but you probably need prolog_before?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question