2011-09-04 72 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); 
?>