'Storing translation array in cookie

I save translation text in PHP files like that:

en.php:

$translation = [
    "home" => [
        "title" => "Home",
    ],
    "contact" => [
        "title" => "Contact", 
    ],
];

return json_encode($translation);

I want to save this array in cookie to use it across the website without including it each time the user visits a page.

So in header.php:

if(!isset($_COOKIE['translation']) && !isset($_GET['lang'])){
    $translation = require_once('en.php');
    setcookie('translation', $translation, time()+86400, '/');
    $_COOKIE['translation'] = $translation;
}elseif(isset($_GET['lang'])){
    $translation = require_once($_GET['lang'] . '.php');
    setcookie('translation', $translation, time()+86400, '/');
    $_COOKIE['translation'] = $translation;
}

$decode = json_decode($_COOKIE['translation']);

echo $decode->home->title;

But I'm getting an error This site can’t be reached ERR_INVALID_RESPONSE

php


Solution 1:[1]

Try the following:

Remove return json_encode($translation); in en.php

Then in header.php :

if (! isset($_COOKIE['translation']) && ! isset($_GET['lang'])) {
  require_once('en.php');
  $jsonEncodedTranslation = json_encode($translation);

  setcookie('translation', $jsonEncodedTranslation, time() + 86400, '/');
  $_COOKIE['translation'] = $jsonEncodedTranslation;
} elseif(isset($_GET['lang'])) {
  require_once($_GET['lang'].'.php'); // this looks evil btw
  $jsonEncodedTranslation = json_encode($translation);

  setcookie('translation', $jsonEncodedTranslation, time() + 86400, '/');
  $_COOKIE['translation'] = $jsonEncodedTranslation;
}

$decode = json_decode($_COOKIE['translation']);

echo $decode->home->title;

On a side note, this looks like a poor implementation. Most websites will include a translation file on every page, and that's totally fine because that's probably the fastest solution. You, on the other side, are encode/decoding on every page and forcing the client to send massive http headers (Cookie) on each request.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Musa