Page 1 of 1

Session variable

Posted: Wed Feb 29, 2012 9:08 pm
by stribor
I have file file1.php that when it is run i would like to based on some condition i would like to define
global variable or constant that will be visible in file2.php. File2.php includes file1.php.
I tried to accomplish this with session for example like this.
file1.php

Code: Select all

<?php
session_start()
If (something){
  define('MYCONST',5);
}
Else {
  define ('MYCONST',6);
}
File2.php

Code: Select all

Include file1.php
Session_start();
Echo MYCONST;
But output i get is MYCONST

i first run file1
Then on press of the button i run file2.php

Can anyone suggest what i am doing wrong please

Re: Session variable

Posted: Thu Mar 01, 2012 2:08 am
by temidayo
Your code should look like this instead
file1.php

Code: Select all

<?php
session_start()
If (something){
  $_SESSION['MYCONST'] = 5;
}
Else {
  $_SESSION['MYCONST'] = 6;
}
File2.php

Code: Select all

Session_start();
echo $_SESSION['MYCONST'];

Re: Session variable

Posted: Thu Mar 01, 2012 4:03 pm
by social_experiment
stribor wrote:Can anyone suggest what i am doing wrong please
The code seems is correct; what will 'something' be? Result of an equation? That's likely to be that problem.

You don't need session_start() on file2.php because you are including a page that already has the function included. You will get a Notice telling you that a session has already started and the session_start() in file1 will be ignored

Re: Session variable

Posted: Fri Mar 02, 2012 2:20 am
by temidayo
stribor wrote: i first run file1
Then on press of the button i run file2.php
The file may need to be restructured. How come you include one file1 in file2
and still navigate to of the file2 afterwards?