Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

49
Views
PHP set Cookie - JavaScript read Cookie

I am developing a game.

I need to exchange data between PHP and JavaScript.

  • PHP generates a value (a secret text), which is the solution of the game.

  • PHP encodes the value via base64_encode(), enduser should not find the solution (easily).

  • PHP stores the encoded value in Cookie.

  • JavaScript reads the cookie value.

  • JavaScript decodes the value, window.atob()

  • JavaScript checks user entry vs. generated secret text from the cookie.

This approach works on localhost, but not on web server.

Following is the code I am using. (in PHP, setting "domain" param with my website such "mydomain.com" did not solve the issue)

PHP

    function setMyCookie($name, $value) {
       setcookie($name, $value, [
           'expires' => time() + 86400,
           'path' => '/',
           'domain' => '',
           'secure' => true,
           'httponly' => false,
           'samesite' => 'None',
        ]);
    }

JavaScript

  function getCookie(cname) {
        let name = cname + "=";
        let decodedCookie = decodeURIComponent(document.cookie);
        let ca = decodedCookie.split(';');
        for(let i = 0; i <ca.length; i++) {
          let c = ca[i];
          while (c.charAt(0) == ' ') {
            c = c.substring(1);
          }
          if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
          }        
        }
        return "";  
    }

Question 1: How can fix my issue on webserver?

Question 2: Is there another approach (other than cookie) which you may recommend?

Thanks BM

7 months ago ยท Santiago Trujillo
Answer question
Find remote jobs