php 从 cookie 文件中读取cookie 值的方法

cookie.php文件如下:

# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.
 
.google.com    TRUE    /   FALSE   1305843382  cookiename  the value
.yahoo.com TRUE    /   FALSE   1305843382  another_cookie  it's value

<?php
    /**
     * 获取淘宝单个Cookie值
     *
     */
    function getCookieVal($name, $domain) {//alimama.com
        $file_name = dirname(__FILE__) . '/cookie.php';
        $content = file_get_contents($file_name);
        $cookies = extractCookies($content);
        foreach ($cookies as $val) {
            if ($val['domain'] == $domain and $val['name'] == $name) {
                return $val['value'];
            }
        }
        return '';
    }


    /**
     * Extract any cookies found from the cookie file. This function expects to get
     * a string containing the contents of the cookie file which it will then
     * attempt to extract and return any cookies found within.
     *
     * @param string $string The contents of the cookie file.
     *
     * @return array The array of cookies as extracted from the string.
     *
     */
    function extractCookies($string) {

        $lines = explode(PHP_EOL, $string);

        foreach ($lines as $line) {

            $cookie = array();

            // detect httponly cookies and remove #HttpOnly prefix
            if (substr($line, 0, 10) == '#HttpOnly_') {
                $line = substr($line, 10);
                $cookie['httponly'] = true;
            } else {
                $cookie['httponly'] = false;
            }

            // we only care for valid cookie def lines
            if (strlen($line) > 0 && $line[0] != '#' && substr_count($line, "\t") == 6) {

                // get tokens in an array
                $tokens = explode("\t", $line);

                // trim the tokens
                $tokens = array_map('trim', $tokens);

                // Extract the data
                $cookie['domain'] = $tokens[0]; // The domain that created AND can read the variable.
                $cookie['flag'] = $tokens[1];   // A TRUE/FALSE value indicating if all machines within a given domain can access the variable.
                $cookie['path'] = $tokens[2];   // The path within the domain that the variable is valid for.
                $cookie['secure'] = $tokens[3]; // A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.

                $cookie['expiration-epoch'] = $tokens[4];  // The UNIX time that the variable will expire on.   
                $cookie['name'] = urldecode($tokens[5]);   // The name of the variable.
                $cookie['value'] = urldecode($tokens[6]);  // The value of the variable.
                // Convert date to a readable format
                $cookie['expiration'] = date('Y-m-d h:i:s', $tokens[4]);

                // Record the cookie.
                $cookies[] = $cookie;
            }
        }

        return $cookies;
    }
?>

参考资料:
http://stackoverflow.com/questions/410109/php-reading-a-cookie-file

js操作cookie的方法

<script type="text/javascript">
    //创建Cookie
    function createCookie(name,value,hour) {
        if (hour) {
            var date = new Date();
            date.setTime(date.getTime()+(hour*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }
    //读取Cookie    
    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }
    //清空Cookie
    function eraseCookie(name) {
        createCookie(name,"",-1);
    }

    //设置cookiename值为 cookievalue过期时间1小时
    createCookie('cookiename','cookievalue',1);

</script>

参考资料
http://www.quirksmode.org/js/cookies.html
http://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript

Cookie禁用了,Session还能用吗?

Cookie与Session,一般认为是两个独立的东西,Session采用的是在服务器端保持状态的方案,而Cookie采用的是在客户端保持状态的方案。
Cookie分为两种,一种可以叫做session cookie,浏览器关闭就会丢失,一种可以叫做persistent cookie,就是我们通常意义上所说的cookie,通常服务器端的session是借助于seesion cookie来和客户端交互的。

针对php,如果客户端关闭cookie,我们怎么办?
1. 设置php.ini配置文件中的“session.use_trans_sid = 1”,或者编译时打开打开了“–enable-trans-sid”选项,让PHP自动跨页传递Session ID。
2. 手动通过URL传值、隐藏表单传递Session ID。
3. 用文件、数据库等形式保存Session ID,在跨页过程中手动调用。