12c06-1.php

来自「介绍PHP5的给类型函数应用」· PHP 代码 · 共 63 行

PHP
63
字号
<?php// A library to pass session data between two servers on the same subdomain:// A function to convert a session into a cookie:function session_2_cookie() {    // Serialize, and base64 encode the session data:    $output = base64_encode(serialize($_SESSION));        // Now, send this as a cookie to our entire domain:    setcookie('sessionpass', $output, false, '/', garner_subdomain());}// A function that will accept this cookie, and turn it back into a sessionfunction cookie_2_session() {    // Make sure that the session has started:    @session_start();        // Unserialize and unencode the cookie, saving it directly into    //  the SESSION vars:    $_SESSION = unserialize(base64_decode(@$_COOKIE['sessionpass']));}// A support function that will determine our subdomain for us without//  having to know it:function garner_subdomain() {    // Explode the HOST into it's constituent parts:    $parts = explode('.', $_SERVER['HTTP_HOST']);    $cp = count($parts);    // If a 1 part hostname like 'localhost' don't bother with a subdomain:    if ($cp == 1) { $subdomain = ''; }    // Otherwise, generate our subdomain by using the last 2 parts    else { $subdomain = ".{$parts[$cp-2]}.{$parts[$cp-1]}"; }    return $subdomain;}// Quick test:// If GET next doesn't exist, then create a blank session, and add a value:if (!(isset($_GET['next']))) {    // Start the session    session_start();        // Blow away the current values:    $_SESSION = array();        // Add a single value:    $_SESSION['test'] = 'Hello World';    // Now convert the session into a cookie:    session_2_cookie();    // Now for testing, redirect immediately back to the same webpage:    header("Location: {$_SERVER['PHP_SELF']}?next=true");} else {    // We are in the redirected mode, pretend to be a different server:    // Convert the cookie back into a session:    cookie_2_session();    // And now output the value from it:    echo "<p>{$_SESSION['test']}</p>";}?>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?