ホームページ >バックエンド開発 >PHPチュートリアル >PHP と NodeJS はどのようにしてセッションを共有しますか?
<code class="language-php"><span class="x">php_session.php?SID=xxxx</span>
<span class="cp"><?php</span>
<span class="k">function</span> <span class="nf">getSessionByID</span><span class="p">(</span><span class="nv">$SID</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nb">session_id</span><span class="p">())</span> <span class="p">{</span>
<span class="c1">// 关闭当前session</span>
<span class="nb">session_destroy</span><span class="p">();</span>
<span class="p">}</span>
<span class="c1">// 初始化指定session</span>
<span class="nb">session_id</span><span class="p">(</span><span class="nv">$SID</span><span class="p">);</span>
<span class="nb">session_start</span><span class="p">();</span>
<span class="c1">// 返回操作接口更友好的JSON</span>
<span class="c1">// 必要的FLAG看这里 http://www.php.net/manual/en/json.constants.php</span>
<span class="k">return</span> <span class="nb">json_encode</span><span class="p">(</span><span class="nv">$_SESSION</span><span class="p">);</span>
<span class="p">}</span>
<span class="nb">header</span><span class="p">(</span><span class="s1">'Content-Type:application/json'</span><span class="p">);</span>
<span class="k">echo</span> <span class="nx">getSessionByID</span><span class="p">(</span><span class="nv">$_GET</span><span class="p">[</span><span class="s1">'SID'</span><span class="p">]);</span>
<span class="cp">?></span><span class="x"></span>
<span class="x">node</span>
<span class="x">var request = require('request');</span>
<span class="x">request('http://localhost/php_session.php?SID=xxxx', function(err, res, body) {</span>
<span class="x"> if (!err && res.statusCode == 200) {</span>
<span class="x"> // 根据需要使用body(json)</span>
<span class="x"> }</span>
<span class="x">});</span>
</code>
memcached などのサードパーティのキャッシュ ツールを使用できます。