PHP Cookies在localhost上运行良好,但它不适用于实时服务器

时间:2010-12-13 10:11:42

标签: php cookies localhost

  

注意:此问题已经解决,   最后我发现它不是饼干   问题,问题是   unserialize()函数。序列化   作为参数的cookie   该功能必须是striplash-ed   第一

您好,我在这里有关于PHP Cookie的问题。我正在使用PHP Cookie来保存用户首选项。我已在本地计算机上测试了我的代码(使用XAMPP的localhost)。一切都很好,包括饼干。但是当我将它上传到实时服务器时,cookie根本不起作用。似乎setcookie()函数不会写入cookie值。我通过在本地主机和我的实时服务器上回显cookie值来测试。 localhost上的$ _COOKIE []值显示但不显示实时服务器中的值。

我想也许这与$ expire时区有关,就像这篇帖子http://anupraj.com.np/index.php/php-cookies-not-working-php-cookie-tutorial-and-scirpt/14中的那个。但后来我意识到我已经将cookie设置为在1个月后到期,而不仅仅是在那篇博客文章中的一小时内。所以我认为情况并非如此。

这是setting.php的内容

<?php
$defaultSettings['default_post_to'] = 'both';
$defaultSettings['timesince_style'] = 'simplify';
...
$defaultSettings['display_geo_info'] = 'true';
$defaultSettings['enable_javascript'] = 'true';

if(!isset($_COOKIE['settings'])){
    setcookie("settings", serialize($defaultSettings), time()+3600*24*30);
    header('Location: index.php');
}
$setting = unserialize($_COOKIE['settings']);
?>

这是index.php的内容

<?php
/*
ini_set ("display_errors", "1");
error_reporting(E_ALL);  
*/

session_start();

require_once("settings.php"); // Settings files
require_once('varlib.php'); // Get all possible passed variable
require_once('auth.php'); // Check for channel login status

// If inputbar form submitted
if( $_POST['inputbox'] ){
...
}
else{
    echo "SETTING COOKIE: <br/><br/>";
    // This print_r is only showing the $_COOKIE value (which is stored on $setting) on localhost but no on live server
        print_r($setting);
    switch( $com ){
        ...
    }
}
?>

我到处搜索它(Google,stackoverflow,在twiiter / FB上询问朋友)仍然没有解决方案

我希望有些机构能在这里给我解决方案 谢谢:))

6 个答案:

答案 0 :(得分:1)

查看setcookie函数的路径和域参数。 参考:setcookie @ PHP docs http://php.net/manual/en/function.setcookie.php

尝试此操作来设置Cookie:

if ($on_localhost) { // change this
    $domain = '.localhost';
} else {
    $domain = '.webhoster.com'; // change this
}
setcookie(
    'settings',
    serialize($defaultSettings),
    time()+3600*24*30,
    '/',          // this is the path
    $domain       // this is the domain
);
祝你好运!

答案 1 :(得分:0)

试试这个:

setcookie("settings", serialize($defaultSettings), time()+3600*24*30, '/'); // added path

另外,serialize($defaultSettings)结果可能太大了吗?

答案 2 :(得分:0)

在Location-header之后尝试exit()

Location-header不会阻止PHP脚本执行进一步的指令,也许在标题之后执行会导致错误行为的事情。

答案 3 :(得分:0)

可能您的服务器时间不正确,因此Cookeis无法在服务器上运行。

试试这个:

setcookie("settings", serialize($defaultSettings), 0);

将过期设置为零将解决您的问题。或者更新服务器时间。

答案 4 :(得分:0)

在应用解决方案时,我们忘记了Cookie的基本知识。

Cookie就像标题一样。与标题一样,它应该在任何输出生成之前发送。然后只有它成功设置。我为这个问题苦苦挣扎但是当我完成基础知识时,这个问题很快就得到了解决。

这种语法足以解决这个问题...

setcookie(
'settings',
serialize($defaultSettings),
time()+3600*24*30,
'/'          // this is the path
);

答案 5 :(得分:0)

仅在setcookie()之前初始化ob_start()方法。大多数开发人员的ob_start()方法都包含在配置文件中。

相关问题