如何通过fsockopen将会话传递给新套接字?

时间:2011-09-04 17:19:16

标签: php session asynchronous background-process fsockopen

我需要通过php中的fsockopen将会话传递给异步调用。

你能帮我把会话传递给新套接字吗?

SOLUTION:

以下代码有效。

start.php

<?php
session_start();
$_SESSION['var1'] = 'value1';
async_call('/async.php');
echo '<pre>';
print_r($_SESSION);
echo $_COOKIE['PHPSESSID'] . "\r\n";
echo '<a href="verify.php">verify.php</a>';

function async_call($filepath) {
    $host = 'sandbox'; // set to your domain
    $sock = fsockopen($host, 80);
    fwrite($sock, "GET $filepath HTTP/1.1\r\n");
    fwrite($sock, "Host: $host\r\n");
    fwrite($sock, "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n");
    fwrite($sock, "Connection: close\r\n");
    fwrite($sock, "\r\n");
    fflush($sock);
    fclose($sock);
}
?>

async.php

<?php
session_start();
logger('confirm logger is working');
logger($_SESSION);  // this is always blank!

function logger($msg) {
    $filename = 'debug.log';
    $fd = fopen($filename, "a");
    if (is_array($msg))
        $msg = json_encode($msg);
    $msg = '[' . date('Y/m/d h:i:s', time()) . "]\t" . $msg;
    fwrite($fd, $msg . "\n");
    fclose($fd);
}
?>

verify.php

<?php
$logfile = 'debug.log';
echo '<a href="start.php">start.php</a>';
echo '<pre>' . file_get_contents($logfile);
?>

我可以让它在本地工作,但结果是我在没有任何文档的情况下暂停了不允许使用fsockopen的共享主机。在我自己的服务器上都很好。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

感谢Andreas的帮助。结果是我在没有任何文档的情况下在不允许的fsockopen上暂存的共享主机。这就是为什么我可以让它在本地工作但不在登台服务器上工作。

以下代码有效。

<强> start.php

<?php
session_start();
$_SESSION['var1'] = 'value1';
async_call('/async.php');
echo '<pre>';
print_r($_SESSION);
echo $_COOKIE['PHPSESSID'] . "\r\n";
echo '<a href="verify.php">verify.php</a>';

function async_call($filepath) {
    $host = 'sandbox'; // set to your domain
    $sock = fsockopen($host, 80);
    fwrite($sock, "GET $filepath HTTP/1.1\r\n");
    fwrite($sock, "Host: $host\r\n");
    fwrite($sock, "Cookie: PHPSESSID=" . $_COOKIE['PHPSESSID'] . "\r\n");
    fwrite($sock, "Connection: close\r\n");
    fwrite($sock, "\r\n");
    fflush($sock);
    fclose($sock);
}
?>

<强> async.php

<?php
session_start();
logger('confirm logger is working');
logger($_SESSION);  // this is always blank!

function logger($msg) {
    $filename = 'debug.log';
    $fd = fopen($filename, "a");
    if (is_array($msg))
        $msg = json_encode($msg);
    $msg = '[' . date('Y/m/d h:i:s', time()) . "]\t" . $msg;
    fwrite($fd, $msg . "\n");
    fclose($fd);
}
?>

<强> verify.php

<?php
$logfile = 'debug.log';
echo '<a href="start.php">start.php</a>';
echo '<pre>' . file_get_contents($logfile);
?>