Session variable

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
stribor
Forum Newbie
Posts: 12
Joined: Fri Apr 01, 2011 10:48 pm

Session variable

Post 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
temidayo
Forum Contributor
Posts: 109
Joined: Fri May 23, 2008 6:17 am
Location: Nigeria

Re: Session variable

Post 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'];
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Session variable

Post 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
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
temidayo
Forum Contributor
Posts: 109
Joined: Fri May 23, 2008 6:17 am
Location: Nigeria

Re: Session variable

Post 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?
Post Reply