How to set cookie on localhost using MAMP + MacOSx + PHP?

I am developing on my Mac laptop, I am using MAMP. I am trying to set a cookie with PHP and I cannot. I refused the domain, I tried using "\" for the domain. Bad luck.

setcookie("username", "George", false, "/", false);
setcookie("name","Joe");

I have to miss something obvious. I need a quick and easy solution. There is one?

I am not doing anything, just loading (via MAMP) the page, http: // localhost: 8888 / MAMP / lynn / setcookie.php

That the script has setcookie code at the top before writing HTML tags. (although I also tried it in the BODY). I load the page in various browsers and then open the list of cookies. I know that browsers accept cookies because I see the current ones in the list. Just not my new one.

+3
source share
3 answers

From the docs:

setcookie () defines a cookie to send along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you send calls to this function before any output, including tags, as well as any spaces.

What's this?

change

You can see that the cookie is being sent by the server, for example. using the Tamper Data or telnet extension? Do you see that it is sent back by the browser at the following request? What is the return value of setcookie ()? Doesn't that work in all browsers, or just some?

+6
source
<?php
ob_start();
if (isset($_COOKIE['test'])) {
    echo 'cookie is fine<br>';
    print_r($_COOKIE);
} else {
    setcookie('test', 'cookie test content', time()+3600);  /* expire in 1 hour */
    echo 'Trying to set cookie. Reload page plz';    
}

Try it.

+1
source

The output of "localhost" and just having an empty string worked for me.

0
source

Source: https://habr.com/ru/post/1704523/


All Articles