• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

106
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

about 3 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error