PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

An Introduction To PHP Sessions

Can I Store A File Pointer In A Session?

The short answer is NO. Let’s create a page1.php and page2.php and see what happens. page1.php will look like this:

Listing 18 page1.php
<?php
 
  // make it or break it
  session_start();
 
  // create a file pointer
  $fp = fopen('my_file.txt', "r");
 
  // set the file pointer to a session variable
  $_SESSION['filePointer'] = $fp
?>
 
<a href="page2.php">link to page 2</a>

Everything here is fine. the variable is set and no error should be seen. page2.php should look like this:

Listing 19 page2.php
<?php
  // make it or break it
  error_reporting(E_ALL);
 
  // begin our session
  session_start();
 
  // try to the read from the file pointer
  $contents = fread ($_SESSION['filePointer'], filesize ($filename));
 
  // close the file
  fclose ($_SESSION['filePointer']);
 
  // echo the files contents
  echo "Contents: $contents"
 
?>

The above code will produce an error similar to this:

Listing 20 The warning caused by trying to store file pointers in sessions (listing-20.txt)
Notice: Undefined variable: filename in /html/page2.php on line 10

Warning: fread(): supplied argument is not a valid stream resource in /html/page2.php on line 10

Warning: fclose(): supplied argument is not a valid stream resource in /html/page2.php on line 13

Contents:

As you can see, no success on storing the file pointer.

In This Article