简体   繁体   English

如何使用 MAMP + MacOSx + PHP 在 localhost 上设置 cookie?

[英]How do I set a cookie on localhost with MAMP + MacOSx + PHP?

I'm developing on my Mac notebook, I use MAMP.我正在我的 Mac 笔记本上开发,我使用 MAMP。 I'm trying to set a cookie with PHP, and I can't.我正在尝试使用 PHP 设置 cookie,但我不能。 I've left off the domain, I've tried using "\" for the domain.我已经离开了域,我尝试使用“\”作为域。 No luck.没运气。

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

I must be missing something obvious.我一定遗漏了一些明显的东西。 I need a quick and simple solution to this.我需要一个快速简单的解决方案。 Is there one?有吗?

I'm not doing anything fancy, simply loading (via MAMP) the page, http://localhost:8888/MAMP/lynn/setcookie.php我没有做任何花哨的事情,只是加载(通过 MAMP)页面http://localhost:8888/MAMP/lynn/setcookie.php

That script has the setcookie code at the top, prior to even writing the HTML tags.该脚本的顶部有 setcookie 代码,甚至在编写 HTML 标签之前。 (although I tried it in the BODY as well). (尽管我也在 BODY 中尝试过)。 I load the page in various browsers, then open the cookie listing.我在各种浏览器中加载页面,然后打开 cookie 列表。 I know the browsers accept cookies, because I see current ones in the list.我知道浏览器接受 cookies,因为我在列表中看到了当前浏览器。 Just not my new one.只是不是我的新的。

From the docs:从文档:

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. setcookie() 定义要与 HTTP 标头的 rest 一起发送的 cookie。 Like other headers, cookies must be sent before any output from your script (this is a protocol restriction).与其他标头一样,cookies 必须在脚本中的任何 output 之前发送(这是协议限制)。 This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.这要求您在任何 output 之前调用此 function,包括和标签以及任何空格。

Is that it?是这样吗?

edit:编辑:

Can you see the cookie being sent by the server, eg by using the Firefox extension Tamper Data , or telnet?你能看到服务器发送的 cookie,例如通过使用 Firefox 扩展Tamper Data或 telnet? Can you see it being sent back by the browser on the next request?你能看到它在下一个请求中被浏览器发回吗? What's the return value of setcookie()? setcookie() 的返回值是多少? Is it not working in all browsers, or just in some?它不适用于所有浏览器,还是仅适用于某些浏览器?

<?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 this.尝试这个。

Taking out "localhost" and just having a blank string worked for me.取出“localhost”并只使用一个空白字符串对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM