MJQ
MJQ

Reputation: 1786

Getting data from Php session

I have created a php session and have assigned data like so

session_start();
$_SESSION['desd']=$imgD;

When i try to retrieve it on other page i get nothing.

this is what i have done on second page,

session_start();
$_imgname = $_SESSION['desd'];

How to do that?

Upvotes: 2

Views: 34708

Answers (2)

Yegor Lukash
Yegor Lukash

Reputation: 510

If you call session_start(), the server gets the session ID from cookies.

Maybe something is wrong with the cookies because the code is valid.

Upvotes: 1

Richard
Richard

Reputation: 61259

The code is valid, assuming that the variable $imgD is defined (var_dump is one way of checking this, but print or echo may also work).

Check to ensure that cookies are enable in your browser.

Also, be sure that session_start() comes near the top of your script, it should be the first thing sent to the client each time.

To test a session, create "index.php" with the following code:

<?php
  session_start();  
  if(isset($_SESSION['views']))
      $_SESSION['views'] = $_SESSION['views']+ 1;
  else
      $_SESSION['views'] = 1;

  echo "views = " . $_SESSION['views']; 
?>

Reload the page several times and you should see an incrementing number.

An example of passing session variables between two pages is as follows:

PageOne.php

 <?php 
   session_start(); 

   // makes an array 
   $colors=array('red', 'yellow', 'blue'); 
   // adds it to our session 
   $_SESSION['color']=$colors; 
   $_SESSION['size']='small'; 
   $_SESSION['shape']='round'; 
   print "Done";
 ?> 

PageTwo.php

<?php 
 session_start(); 
 print_r ($_SESSION);
 echo "<p>";

 //echo a single entry from the array
 echo $_SESSION['color'][2];
?>

For simplicity put PageOne.php and PageTwo.php in the same directory. Call PageOne.php and then PageTwo.php.

Try also tutorials here, here, and here.

Upvotes: 5

Related Questions