2011-09-04 57 views
0

我需要通过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。在我自己的服务器上都很好。谢谢您的帮助。

+0

我知道,PHPSESSID保存为一个cookie ,但我是n不清楚如何检索它以访问我的异步脚本中的会话变量。 – Ryan

+0

检查您的上一个问题,我添加了一个应该解决它的答复。 http://stackoverflow.com/questions/7297827/how-can-i-run-an-fql-request-in-the-background-asynchronous-api-calls-via-php/7298224#7298224 – Andreas

+0

为了清晰我编辑。安德烈亚斯,你一直很有帮助,但由于某种原因,我仍然陷入困境。你能看看我上面简单的调试脚本,看看我错过了什么吗? – Ryan

回答

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); 
?> 
相关问题