2017-03-02 47 views
1

我在練習如何在PHP中將值存儲到會話中。在會話中存儲後,Php資源ID已更改

的問題是:

當我在testsession.php稱之爲echo $_SESSION['handle'],它顯示爲0。

當我使用var_dump($_SESSION['handle']),它表明,INT(0)。

storeValueParctice.php

$handle = fopen ("test.txt", "r"); 
$_SESSION['handle']=$handle; 
echo $_SESSION['handle'] // it will show resource id#(somenumber) 

testsession.php

echo $_SESSION['handle']; //it shows 0. 
var_dump($_SESSION['handle']);//it shows that int(0). 
fseek ($_SESSION['handle'], 0); // this will give me an error which is 
//Warning: fseek() expects parameter 1 to be resource, integer given . 

我不知道爲什麼會發生這種情況。

如何獲取testsession.php中的資源ID號?

我想通過$_SESSION['handle']storeValueParctice.phptestsession.php並在testsession.php做一些文件操作。

+0

我不確定這會適用於您。文件句柄的範圍是當前進程,並在腳本結束時結束。我不相信它可能通過一個打開的文件句柄到這個方法中的另一個進程。 –

+0

您不能在會話中保存文件資源引用,然後在另一個實例中重新使用它。如果您想在會話中對文件進行操作,請保存文件的名稱(如'$ _SESSION ['file_name']'而不是$ _SESSION ['handle']'),並在需要時重新打開該文件它再次。 –

回答

1

首先在頁面的頂部添加PHP會話啓動命令:

<?php 
session_start(); 
?> 

的fopen()函數返回File對象。

,如果你想獲得文件內容到會話試試這個:

$handle = file_get_contents ("test.txt"); 
$_SESSION['handle']=$handle; 
var_dump($_SESSION['handle']); // it will show resource id#(somenumber) 

這應該解決您的問題

1

您需要同時在頁面的頂部添加session_start()能夠通過上的值。

storeValueParctice.php

<?php 

    session_start(); <=== 

    ...rest of the code... 
?> 

testsession.php

<?php 

    session_start(); <=== 

    ...rest of the code... 
?> 

參見:https://www.tutorialspoint.com/php/php_sessions.htm