473,516 Members | 3,277 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

-> PHP4 Singleton implementation question <-

Hi,
I'm trying to implement a singleton in PHP4 but it doesn't seem to
work. The object is recreated each time I call it.

The goal of the class is to keep a variable up to date.
It's used to display a database content, 25 rows at a time.
The singleton keeps track of the current starting row and
increases it or decreases it by 25 depending on the user action
(pressing a Next or Prev button).
Those buttons are submit buttons calling the current form itself.

But each time I re-enter that form, the singleton variable is created
again and therefore the currentRow variable reinitilized.

Thanks for any help?

Here is the code for the class called Welcome:
---------------------------------------------
class Welcome {
var $offsetRows = 25;
var $currentRow ;
// ************************************************** ********
// INSTANCE function to instanciate this class only once
// ************************************************** ********
function &getInstance() {
static $instance ;
if( !$instance ) {
$instance = new Welcome() ;
}
return $instance ;
}

// ************************************************** ********
// CONSTRUCT function called when object is created
// ************************************************** ********
function Welcome() {
$this->currentRow = 0 ;
$this->offsetRows = 25 ;
}
// ************************************************** ********
// SHOWRECORDS
// Displays the actual table with info in rows.
// ************************************************** ********
function showRecords() {
// my table display code here using $this->currentRow
}

// ************************************************** ********
// NEXTRECORDS
// Displays the next nn offset records
// ************************************************** ********
function nextRecords() {
$this->currentRow += $this->offsetRows ;
$this->showRecords() ;
}
// ************************************************** ********
// PREVRECORDS
// Displays the previous nn offset records if not at first
// ************************************************** ********
function prevRecords() {
$this->currentRow -= $this->offsetRows ;
if( $this->currentRows < 0 )
$this->currentRows = 0 ;
$this->showRecords() ;
}
}
Then my form works as follows:
------------------------------
<FORM action="<?=$_SERVER['PHP_SELF']?>" method="post">
<?php
require_once( "class_welcome.php" ) ;
if( !$welcome ) {
$welcome =& Welcome::getInstance() ;
}

if(isset($_POST['next'])) {
$welcome->nextRecords() ;
}
else {
if(isset($_POST['previous'])) {
$welcome->prevRecords() ;
}
else {
$welcome->showRecords() ;
}
}
?>

<P>
<INPUT name="previous" type="submit" value="<<" />
<INPUT name="next" type="submit" value=">>" />
</FORM>


Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Nov 30 '06 #1
35 1986
"Steve JORDI" <st*******************@hotmail.comwrote in message
news:o0********************************@4ax.com...
Hi,
I'm trying to implement a singleton in PHP4 but it doesn't seem to
work. The object is recreated each time I call it.
PHP4 is not the best platform for OOP. PHP5 has much more sophisticated
object handling.
The goal of the class is to keep a variable up to date.
It's used to display a database content, 25 rows at a time.
The singleton keeps track of the current starting row and
increases it or decreases it by 25 depending on the user action
(pressing a Next or Prev button).
Those buttons are submit buttons calling the current form itself.

But each time I re-enter that form, the singleton variable is created
again and therefore the currentRow variable reinitilize
I'm guessing you have a C++ or Java background. The request/response
architecture is quite different from a desktop application. A variable will
not be available thru two different page calls unless it's stored as a
session variable. Otherwise, each page call should be concidered as
restarting an application and at the end of the page all variables are
destroyed except for session variables.

First I encourage you to go for php version 5, you'll get much more out of
the classes and objects. Next thing you should do is learn how sessions
work. And then finally, check out the singleton example at php.net:
http://www.php.net/manual/en/language.oop5.patterns.php

--
"Ohjelmoija on organismi joka muuttaa kofeiinia koodiksi" - lpk
http://outolempi.net/ahdistus/ - Satunnaisesti päivittyvä nettisarjis
sp**@outolempi.net | rot13(xv***@bhgbyrzcv.arg)
Nov 30 '06 #2
Kimmo,

Thanks for your prompt reply,

>PHP4 is not the best platform for OOP. PHP5 has much more sophisticated
object handling.
Yes I know but for now I have no choice but to use the existing PHP 4
in the company.
>I'm guessing you have a C++
Correct :-)

>The request/response architecture is quite different from a desktop
application. A variable will not be available thru two different
page calls unless it's stored as a session variable.
Mhhh... Interresting.
>Otherwise, each page call should be concidered as restarting an
application and at the end of the page all variables are
destroyed except for session variables.
OK.

>First I encourage you to go for php version 5, you'll get much more out of
the classes and objects. Next thing you should do is learn how sessions
work.
Ok I will check session matters. Thanks for the hint.
>And then finally, check out the singleton example at php.net:
http://www.php.net/manual/en/language.oop5.patterns.php
Yes, I've seen it, but it's for PHP 5 which I can't use right now.

Thanks for your help.

Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Nov 30 '06 #3
<snip>
Then my form works as follows:
------------------------------
<FORM action="<?=$_SERVER['PHP_SELF']?>" method="post">
<?php
require_once( "class_welcome.php" ) ;
if( !$welcome ) {
$welcome =& Welcome::getInstance() ;
}
Following the PHP documentation on http://nl3.php.net/static , I would
suggest to replace this last line with a non-referencing one:

$welcome = Welcome::getInstance() ;

As was posted earlier, PHP5 has solved the objects-and-references problem.

Best regards.
Nov 30 '06 #4
>Following the PHP documentation on http://nl3.php.net/static , I would
>suggest to replace this last line with a non-referencing one:
$welcome = Welcome::getInstance() ;
Did this but it din't change a thing.
>As was posted earlier, PHP5 has solved the objects-and-references problem.
Yes, but I have to deal with PHP4, not 5 unfortunately.

I also tried to set a $_SESSION['welcome'] variable, but still, each
time I reenter my page, it's reassigned a new instance.

It's crazy, I would never have thought that it would be such a hassle
to keep a variable value between pages (without using URL parameters).

Thanks anyway.

Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Nov 30 '06 #5
<snip>
I also tried to set a $_SESSION['welcome'] variable, but still, each
time I reenter my page, it's reassigned a new instance.

It's crazy, I would never have thought that it would be such a hassle
to keep a variable value between pages (without using URL parameters).

Sorry, I did not correctly read your message, and I thought it was
re-created within one page request. If you want something kept between
page requests, you'll need a session. There's no need to store the
object itself in the session, although that is not impossible. Even
then, the object will be re-created (unserialized) for each page visit.
You can store just the data itself in the session (I assume it is one or
more arrays) and have your instance check for existence of that session
data at instantiation. Be sure to start the session before any data is
sent to the client by calling session_start(). See
http://nl3.php.net/manual/en/function.session-start.php for more info.

Best regards.
Nov 30 '06 #6
Steve JORDI wrote:
>>Following the PHP documentation on http://nl3.php.net/static , I would
suggest to replace this last line with a non-referencing one:
$welcome = Welcome::getInstance() ;


Did this but it din't change a thing.

>>As was posted earlier, PHP5 has solved the objects-and-references problem.


Yes, but I have to deal with PHP4, not 5 unfortunately.

I also tried to set a $_SESSION['welcome'] variable, but still, each
time I reenter my page, it's reassigned a new instance.

It's crazy, I would never have thought that it would be such a hassle
to keep a variable value between pages (without using URL parameters).

Thanks anyway.

Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Steve,

If you've ever done any transactional processing, that's what web pages are.

When the browser makes a request, the server starts a process (or
thread) to handle the request. It allocates the necessary resources,
and turns control over to your program (the php interpreter, in this
case). The interpreter allocates additional resources as necessary to
process your script and runs the script.

When the script ends, the process reverses. The interpreter cleans up
its resources and returns to the server. The server then cleans up the
resources it allocated and terminates the process or thread.

Each request is separate in itself. Resources are not kept, because
another request may or may not follow this one. And if another request
does come in, it may or may not be something you expect. And it may or
may not be from the same user.

Now, the developers understood there was a need to save information
across requests. Therefore they implemented sessions to save the data
on the server, and cookies to save it on the browser.

So, if you want to save your object across the request, you need to
store it in the session (not a good idea to store this in the cookie -
too many people have cookies disabled, and saving them on the user's
computer allows the user to edit the cookie).
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Nov 30 '06 #7
Jerry,
thanks for your explanations.

I did actually try to save the variable as a session one, but
it didn't seem to work.

I had a
start_session() ;

Then, when entering or re-entering my page, it tests
if( !isset($_SESSION['welcome']) )
$_SESSION['welcome'] =& Welcome::GetInstance() ;

Problem is that it correctly get the instance the first time,
but gets it again each time I re-enter my page.

Shouldn't $_SESSION['welcome'] be saved within the session?

From the literrature I read, it's the way to go, but clearly,
something's wrong, I'm missing something.

Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Dec 1 '06 #8
Steve JORDI wrote:
Jerry,
thanks for your explanations.

I did actually try to save the variable as a session one, but
it didn't seem to work.

I had a
start_session() ;

Then, when entering or re-entering my page, it tests
if( !isset($_SESSION['welcome']) )
$_SESSION['welcome'] =& Welcome::GetInstance() ;

Problem is that it correctly get the instance the first time,
but gets it again each time I re-enter my page.

Shouldn't $_SESSION['welcome'] be saved within the session?

From the literrature I read, it's the way to go, but clearly,
something's wrong, I'm missing something.

Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Yes, and if your session is working, you it will be. Are you sure
NOTHING is sent to the browser before the session_start() call? No
white space, no DOCTYPE, nothing?

Enable all errors on the page by adding this at the top of your PHP code:

ini_set("display_errors","1");
error_reporting(E_ALL);

And see what you get.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 1 '06 #9
OK I will check everything on Monday when back to work.
I'll keep you posted.
Thanks for your help anyway.

Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Dec 1 '06 #10
Tom
You probably have register_globals on and the session variable is
getting overwritten -- this problem drove me crazy for ages.

I finally figured it out recently and posted a comment on the php site
that will help if this is problem:

http://www.php.net/manual/en/ref.session.php#70184

Good luck!

Tom
On Nov 30, 5:37 am, Steve JORDI <steveK_I_L_LSPAMjo...@hotmail.com>
wrote:
Following the PHP documentation onhttp://nl3.php.net/static, I would
suggest to replace this last line with a non-referencing one:
$welcome = Welcome::getInstance() ;Did this but it din't change a thing.
As was posted earlier, PHP5 has solved the objects-and-references problem.Yes, but I have to deal with PHP4, not 5 unfortunately.

I also tried to set a $_SESSION['welcome'] variable, but still, each
time I reenter my page, it's reassigned a new instance.

It's crazy, I would never have thought that it would be such a hassle
to keep a variable value between pages (without using URL parameters).

Thanks anyway.

Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: stevejordiK_I_L_LS...@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Dec 1 '06 #11
Jerry,
>Yes, and if your session is working, you it will be. Are you sure
NOTHING is sent to the browser before the session_start() call? No
white space, no DOCTYPE, nothing?
Yes, the start_session() call is the first line in the code.

>Enable all errors on the page by adding this at the top of your PHP code:
ini_set("display_errors","1");
error_reporting(E_ALL);
Yes, added this but didn't change anything. no message.
I'm using PHP4.4.4, is this the problem?
Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Dec 4 '06 #12
Steve JORDI wrote:
Jerry,

>>Yes, and if your session is working, you it will be. Are you sure
NOTHING is sent to the browser before the session_start() call? No
white space, no DOCTYPE, nothing?


Yes, the start_session() call is the first line in the code.
>>Enable all errors on the page by adding this at the top of your PHP code:
ini_set("display_errors","1");
error_reporting(E_ALL);


Yes, added this but didn't change anything. no message.
I'm using PHP4.4.4, is this the problem?
Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
No, PHP has supported sessions for a long time.

One thing - do you have the class definition included before the
session-start() call? I didn't think about this - but you have to have
the definition in there before you start the session. And does your
php.ini file automatically start sessions? If so, this could be the
problem, also.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 4 '06 #13
Jerry,
I include the class definition before the start session
the PHP.INI is not set to start sessions automatically.

Maybe some code excerpts would help...
Here is the index.php start file:
--------------------------------
<?php
include_once( "class_welcome.php" ) ;
session_start() ;
ini_set("display_errors","1");
error_reporting(E_ALL);
header("Location: ./passeportswelcome.php") ;
?>

then I have passeportswelcome.php:
----------------------------------
<body>
<FORM action="<?=$_SERVER['PHP_SELF']?>" method="post">
<?php

if( !isset( $_SESSION['welcome'] ) )
$_SESSION['welcome'] =& Welcome::getInstance() ;

if(isset($_POST['next'])) {
$_SESSION['welcome']->nextRecords() ;
}
else {
if(isset($_POST['previous'])) {
$_SESSION['welcome']->prevRecords() ;
}
else {
$_SESSION['welcome']->showRecords() ;
}
}

?>

<P>
<INPUT name="previous" type="submit" value="&lt;&lt;" />
<INPUT name="next" type="submit" value="&gt;&gt;" />
</FORM>
</body>

and finally, here is the begining of the class_welcome.php:
-----------------------------------------------------------
<?php
// ************************************************** ********
// CLASS WELCOME
// Displays records in a table
// Limited to nn records with nn chunks offsets
//
// This is a SINGLETON
// Use it in your main form as $obj = &Welcome::getInstance() ;
// ************************************************** ********
class Welcome {
var $offsetRows = 25;
var $currentRow ;
// ************************************************** ********
// INSTANCE function to instanciate this class only once
// ************************************************** ********
function &getInstance() {
static $instance ;
if( !$instance ) {
$instance = new Welcome() ;
}
return $instance ;
}

// ************************************************** ********
// CONSTRUCTOR function called when object is created
// ************************************************** ********
function Welcome() {
$this->currentRow = 0 ;
$this->offsetRows = 25 ;
}
// ************************************************** ********
// SHOWRECORDS
// Displays the actual table with info in rows.
// ************************************************** ********
function showRecords() {
// display code
}

// ************************************************** ********
// NEXTRECORDS
// ************************************************** ********
function nextRecords() {
$this->currentRow += $this->offsetRows ;
$this->showRecords() ;
}
}
?>
What it does is correctly display my table from rows 0 to 25 going
through (I've added "echo" to each function)
***WELCOME INSTANCE INIT***
***WELCOME CONSTRUCTOR***
***WELCOME INSTANCE ***
***SHOW RECORDS***

Then if I click on the ">>" button (being "next" in the form), it
goes through
***WELCOME INSTANCE INIT***
***WELCOME CONSTRUCTOR***
***WELCOME INSTANCE ***
***NEXT RECORDS***
***SHOW RECORDS***

As you can see, it instances Welceom again and goes again through
the constructor which initializes $currentRow to 0 again...
It should skip "Instance init" and "constructor".

Thanks

Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Dec 4 '06 #14
Steve JORDI wrote:
Jerry,
I include the class definition before the start session
the PHP.INI is not set to start sessions automatically.

Maybe some code excerpts would help...
Here is the index.php start file:
--------------------------------
<?php
include_once( "class_welcome.php" ) ;
session_start() ;
ini_set("display_errors","1");
error_reporting(E_ALL);
header("Location: ./passeportswelcome.php") ;
?>

then I have passeportswelcome.php:
----------------------------------
<body>
<FORM action="<?=$_SERVER['PHP_SELF']?>" method="post">
<?php

if( !isset( $_SESSION['welcome'] ) )
$_SESSION['welcome'] =& Welcome::getInstance() ;

if(isset($_POST['next'])) {
$_SESSION['welcome']->nextRecords() ;
}
else {
if(isset($_POST['previous'])) {
$_SESSION['welcome']->prevRecords() ;
}
else {
$_SESSION['welcome']->showRecords() ;
}
}

?>

<P>
<INPUT name="previous" type="submit" value="&lt;&lt;" />
<INPUT name="next" type="submit" value="&gt;&gt;" />
</FORM>
</body>

and finally, here is the begining of the class_welcome.php:
-----------------------------------------------------------
<?php
// ************************************************** ********
// CLASS WELCOME
// Displays records in a table
// Limited to nn records with nn chunks offsets
//
// This is a SINGLETON
// Use it in your main form as $obj = &Welcome::getInstance() ;
// ************************************************** ********
class Welcome {
var $offsetRows = 25;
var $currentRow ;
// ************************************************** ********
// INSTANCE function to instanciate this class only once
// ************************************************** ********
function &getInstance() {
static $instance ;
if( !$instance ) {
$instance = new Welcome() ;
}
return $instance ;
}

// ************************************************** ********
// CONSTRUCTOR function called when object is created
// ************************************************** ********
function Welcome() {
$this->currentRow = 0 ;
$this->offsetRows = 25 ;
}
// ************************************************** ********
// SHOWRECORDS
// Displays the actual table with info in rows.
// ************************************************** ********
function showRecords() {
// display code
}

// ************************************************** ********
// NEXTRECORDS
// ************************************************** ********
function nextRecords() {
$this->currentRow += $this->offsetRows ;
$this->showRecords() ;
}
}
?>
What it does is correctly display my table from rows 0 to 25 going
through (I've added "echo" to each function)
***WELCOME INSTANCE INIT***
***WELCOME CONSTRUCTOR***
***WELCOME INSTANCE ***
***SHOW RECORDS***

Then if I click on the ">>" button (being "next" in the form), it
goes through
***WELCOME INSTANCE INIT***
***WELCOME CONSTRUCTOR***
***WELCOME INSTANCE ***
***NEXT RECORDS***
***SHOW RECORDS***

As you can see, it instances Welceom again and goes again through
the constructor which initializes $currentRow to 0 again...
It should skip "Instance init" and "constructor".

Thanks

Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Ah, now I see the problem.

When you make the call

header("Location: ./passeportswelcome.php") ;

you are telling the browser to load a new page. But on that page you
don't have a session-start() - or the include for your class.

Since it's a new page, everything starts over. You need the include and
session_start() call here, also.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 5 '06 #15
>When you make the call
header("Location: ./passeportswelcome.php") ;
you are telling the browser to load a new page. But on that page you
don't have a session-start() - or the include for your class.
Ok, the include is actually in my source code. but not session_start.
>Since it's a new page, everything starts over. You need the include and
session_start() call here, also.
Yes, that did it! THANKS!!!
I didn't know that session_start() was also used to resume a session.
I thought that having it once was enough, but as you said, the web
being a stateless environment...
Wow, now I know that, it seems logical :-)

Anyway, again, thanks a lot for your patience and your help.

Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Dec 5 '06 #16
Steve JORDI wrote:
Yes, that did it! THANKS!!!
I didn't know that session_start() was also used to resume a session.
I thought that having it once was enough, but as you said, the web
being a stateless environment...
Wow, now I know that, it seems logical :-)
I've had such problems figgering this out, I resorted to writing my own
session handling. Getting this down would *seriously* cut back on the
number of lines of code I have to write!
So...

It *resumes* a session?!
If I put a bunch of values into session variables, how do I get those
back with the resumed session... and how do I make sure I resumed the
right session?
Dec 5 '06 #17
Steve JORDI wrote:
>>When you make the call
header("Location: ./passeportswelcome.php") ;
you are telling the browser to load a new page. But on that page you
don't have a session-start() - or the include for your class.


Ok, the include is actually in my source code. but not session_start.

>>Since it's a new page, everything starts over. You need the include and
session_start() call here, also.


Yes, that did it! THANKS!!!
I didn't know that session_start() was also used to resume a session.
I thought that having it once was enough, but as you said, the web
being a stateless environment...
Wow, now I know that, it seems logical :-)

Anyway, again, thanks a lot for your patience and your help.

Sincerely,
Steve JORDI

(Remove the K_I_L_LSPAM from my email address)
------------------------------------------------
1197 Prangins Email: st*******************@hotmail.com
Switzerland WWW: www.sjordi.com
------------------------------------------------
Volcanoes at www.sjordi.com/volcanoes
MovieDB at www.sjmoviedb.com
------------------------------------------------
Yep, you need session_start() at the top of every page which uses the
session.

Glad it's working for you!

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 5 '06 #18
Sanders Kaufman wrote:
Steve JORDI wrote:
>Yes, that did it! THANKS!!!
I didn't know that session_start() was also used to resume a session.
I thought that having it once was enough, but as you said, the web
being a stateless environment...
Wow, now I know that, it seems logical :-)


I've had such problems figgering this out, I resorted to writing my own
session handling. Getting this down would *seriously* cut back on the
number of lines of code I have to write!
So...

It *resumes* a session?!
If I put a bunch of values into session variables, how do I get those
back with the resumed session... and how do I make sure I resumed the
right session?
Just call session_start() on every page that uses sessions. PHP ensures
the correct session id is used again.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 5 '06 #19
Jerry Stuckle wrote:
Sanders Kaufman wrote:
>It *resumes* a session?!
If I put a bunch of values into session variables, how do I get those
back with the resumed session... and how do I make sure I resumed the
right session?

Just call session_start() on every page that uses sessions. PHP ensures
the correct session id is used again.
So with this page:

-----
session_start();
$_SESSION["MyVar"] = 123;
----

When the user reloads, MyVar *will* equal 123?
It's that simple?

When I was trying to learn about them, I ran into something to do with
ob or ob_flush. Was I on a wrong tracK?
Dec 5 '06 #20
Sanders Kaufman wrote:
Jerry Stuckle wrote:
>Sanders Kaufman wrote:

>>It *resumes* a session?!
If I put a bunch of values into session variables, how do I get those
back with the resumed session... and how do I make sure I resumed the
right session?


Just call session_start() on every page that uses sessions. PHP
ensures the correct session id is used again.


So with this page:

-----
session_start();
$_SESSION["MyVar"] = 123;
----

When the user reloads, MyVar *will* equal 123?
It's that simple?
It is if you have register_globals on - but that's a very bad thing to
have - a potential security risk.

What it will do is set $_SESSION('MyVar'] equal to 123. To get the
value out of the session on another page, just do:

session_start();
$MyVar = $_SESSION["MyVar"];

or, a better way (in case the user got to the second page without going
through the first one)

session_start();
$MyVar = isset($_SESSION['MyVar']) ? $_SESSION['MyVar'] : 0;

If $_SESSION['MyVar'] is set, the value in it will be placed in $MyVar.
But if $_SESSION['MyVar'] is not set, the code will set $MyVar to 0
(adjust the default value as you wish - even null is ok).
When I was trying to learn about them, I ran into something to do with
ob or ob_flush. Was I on a wrong tracK?

The problem with a session is you must start it before the headers are
sent to the browser. This will happen if there is *any* output sent,
even white space. So, for instance, if you have:

---top of file----

<?php
session_start();
?>

..... more of the file....

the session will fail because you sent output (a blank line) to the
browser. This caused the headers to be sent, and it's now too late to
start the session.

ob_start() buffers any output to the browser, so the headers aren't sent
right away. But IMHO this is a "quick and dirty" fix which just
bypasses the real problem. I think it's much better to structure code
properly so you issue the session_start() call at the beginning of your
page.

Others feel differently, but about the only time I use ob_start(), etc.,
is when I'm doing templating or similar, and need to parse the output
before sending it to the browser - i.e. substituting a persons name for
a [NAME] tag. But that's a little more advanced than we need to get
into right here.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 5 '06 #21
Jerry Stuckle wrote:
Sanders Kaufman wrote:
It is if you have register_globals on - but that's a very bad thing to
have - a potential security risk.
Aha! I seem to remember that being part of why I made up my own session
logic. And it begs my next question:

What is the security risk attached to having register_globals turned on?

$MyVar = isset($_SESSION['MyVar']) ? $_SESSION['MyVar'] : 0;

BONUS! Is that a way of saying "if myvar isn't set, set it to zero"?
I hope so because I've got a bunch of pages with the most convoluted
code just to handle that "unset vs. set to zero" issue.
If $_SESSION['MyVar'] is set, the value in it will be placed in $MyVar.
But if $_SESSION['MyVar'] is not set, the code will set $MyVar to 0
(adjust the default value as you wish - even null is ok).
Cool. Thanks.
You just despaghetti'd a mess o' code.

ps. I tantrumed you as a troll about a month ago when an answer you
gave was a little too *personal*. I'm glad I rebuilt my system and lost
my filter.
Dec 6 '06 #22
Sanders Kaufman wrote:
Jerry Stuckle wrote:
>Sanders Kaufman wrote:

>It is if you have register_globals on - but that's a very bad thing to
have - a potential security risk.


Aha! I seem to remember that being part of why I made up my own session
logic. And it begs my next question:

What is the security risk attached to having register_globals turned on?
Well,among other things, a smart user could do something like:

http://www.example.com?authorized=1&level=admin

This could set the person as authorized, with admin level. Of course, a
simple example - but you get the idea. Even the PHP designers have
recommended against its use, and it will probably be removed in a future
release.
>
>$MyVar = isset($_SESSION['MyVar']) ? $_SESSION['MyVar'] : 0;

BONUS! Is that a way of saying "if myvar isn't set, set it to zero"?
I hope so because I've got a bunch of pages with the most convoluted
code just to handle that "unset vs. set to zero" issue.
Yep. I use something similar all the time.
>If $_SESSION['MyVar'] is set, the value in it will be placed in
$MyVar. But if $_SESSION['MyVar'] is not set, the code will set
$MyVar to 0 (adjust the default value as you wish - even null is ok).


Cool. Thanks.
You just despaghetti'd a mess o' code.

ps. I tantrumed you as a troll about a month ago when an answer you
gave was a little too *personal*. I'm glad I rebuilt my system and lost
my filter.

:-)

I do have a tendency to get rather pissed off at people who think they
know it all when they really have no clue. But after almost 40 years of
programming I get a little jaded :-)

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 6 '06 #23
Jerry Stuckle wrote:
Sanders Kaufman wrote:
>What is the security risk attached to having register_globals turned on?

Well,among other things, a smart user could do something like:

http://www.example.com?authorized=1&level=admin

This could set the person as authorized, with admin level. Of course, a
simple example - but you get the idea. Even the PHP designers have
recommended against its use, and it will probably be removed in a future
release.
It looks like you're saying that query string variables are
automatically made into $_SESSION variables - is that right?

If not - then the whole security issue is resolved by using $_GET and
$_POST correctly, right?

>>$MyVar = isset($_SESSION['MyVar']) ? $_SESSION['MyVar'] : 0;
I do have a tendency to get rather pissed off at people who think they
know it all when they really have no clue. But after almost 40 years of
programming I get a little jaded :-)
They say the toothless get ruthless. :)
Dec 6 '06 #24
Sanders Kaufman wrote:
Jerry Stuckle wrote:
>Sanders Kaufman wrote:

>>What is the security risk attached to having register_globals turned on?


Well,among other things, a smart user could do something like:

http://www.example.com?authorized=1&level=admin

This could set the person as authorized, with admin level. Of course,
a simple example - but you get the idea. Even the PHP designers have
recommended against its use, and it will probably be removed in a
future release.


It looks like you're saying that query string variables are
automatically made into $_SESSION variables - is that right?
I'm saying that any variable ($_GET, $_POST or $_SESSION) with that
index can replace the variable, i.e. $MyVar could originate in
$_SESSION["MyVar"], but could also come from $_POST["MyVar"] or
$_GET["MyVar"]. And if you have multiple, the settings in your php.ini
file determines which takes precedence.

This can be very dangerous.
If not - then the whole security issue is resolved by using $_GET and
$_POST correctly, right?
Yes, you can use $_GET and $_POST (and $_SESSION). And if you leave
register_globals off, then you *must* use them. Less chance for error.
>
>>>$MyVar = isset($_SESSION['MyVar']) ? $_SESSION['MyVar'] : 0;


>I do have a tendency to get rather pissed off at people who think they
know it all when they really have no clue. But after almost 40 years
of programming I get a little jaded :-)


They say the toothless get ruthless. :)

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 6 '06 #25
Jerry Stuckle wrote:
Sanders Kaufman wrote:
>If not - then the whole security issue is resolved by using $_GET and
$_POST correctly, right?

Yes, you can use $_GET and $_POST (and $_SESSION). And if you leave
register_globals off, then you *must* use them. Less chance for error.
So - as long as I explicitly reference $_SESSION[] when continuing a
session, I'm not subject to the security vulnerabilities of
register_globals, right?

One more thing - on the session token.
I notice that PHP puts it in the query string.
Is it possible to force that into a cookie?

I know this will mess with folks who turn cookies off, but I'm
accounting for that elsehow.
Dec 6 '06 #26
Jerry Stuckle wrote:
I'm saying that any variable ($_GET, $_POST or $_SESSION) with that
index can replace the variable, i.e.
Index, index, index.... hmmmm. Just a s a curiosity, can I reference
other sessions like so:

$x = $_SESSION[$sSessionToken]["MyVar"]
Dec 6 '06 #27
Sanders Kaufman wrote:
Jerry Stuckle wrote:
>Sanders Kaufman wrote:

>>If not - then the whole security issue is resolved by using $_GET and
$_POST correctly, right?


Yes, you can use $_GET and $_POST (and $_SESSION). And if you leave
register_globals off, then you *must* use them. Less chance for error.


So - as long as I explicitly reference $_SESSION[] when continuing a
session, I'm not subject to the security vulnerabilities of
register_globals, right?
True - but ANY misstep can be disastrous. The problem is,

$i = $MyVar;

doesn't cause an error of $MyVar hasn't been explicitly assigned a value
in your code, but it is in the $_SESSION, $_POST, $_GET or $_COOKIES
(forgot the last one) array. That's very dangerous.
One more thing - on the session token.
I notice that PHP puts it in the query string.
Is it possible to force that into a cookie?

I know this will mess with folks who turn cookies off, but I'm
accounting for that elsehow.
PHP can put it in a cookie if the user has cookies enabled. This is
controlled by the session.use_cookies and session.use_only_cookie in
your php.ini file.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 6 '06 #28
Sanders Kaufman wrote:
Jerry Stuckle wrote:
>I'm saying that any variable ($_GET, $_POST or $_SESSION) with that
index can replace the variable, i.e.


Index, index, index.... hmmmm. Just a s a curiosity, can I reference
other sessions like so:

$x = $_SESSION[$sSessionToken]["MyVar"]
No, you only have one session available.

Your example would access an array (index found in $sSessionToken) with
element 'MyVar'.

Sessions are particular to that site. Anything else would be a major
security breach. Additionally, the session info is kept on the server,
so even if you (theoretically) could access another site's session, the
data wouldn't be there.

As for accessing the info for another browser's session, you can't with
the default session handling. But you could put your own session
handler in there and do whatever you want - i.e. store the data in a
database. Then you could access data from other sessions on your
machine. But it's not recommended.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 6 '06 #29
Jerry Stuckle wrote:
Sanders Kaufman wrote:
>One more thing - on the session token.
I notice that PHP puts it in the query string.
Is it possible to force that into a cookie?

I know this will mess with folks who turn cookies off, but I'm
accounting for that elsehow.

PHP can put it in a cookie if the user has cookies enabled. This is
controlled by the session.use_cookies and session.use_only_cookie in
your php.ini file.
I would need my app to handle that gracefully. Is there a built-in
function to programatically determine which way it's set?
Dec 6 '06 #30
Message-ID: <lb******************************@comcast.comfro m Jerry
Stuckle contained the following:
>So - as long as I explicitly reference $_SESSION[] when continuing a
session, I'm not subject to the security vulnerabilities of
register_globals, right?

True - but ANY misstep can be disastrous. The problem is,

$i = $MyVar;

doesn't cause an error of $MyVar hasn't been explicitly assigned a value
in your code, but it is in the $_SESSION, $_POST, $_GET or $_COOKIES
(forgot the last one)
$_REQUEST ?

--
Geoff Berrow (put thecat out to email)
It's only Usenet, no one dies.
My opinions, not the committee's, mine.
Simple RFDs http://www.ckdog.co.uk/rfdmaker/
Dec 6 '06 #31
no
On Wed, 06 Dec 2006 04:04:21 GMT, Sanders Kaufman <bu***@kaufman.net>
wrote:
>Jerry Stuckle wrote:
>Sanders Kaufman wrote:
>>If not - then the whole security issue is resolved by using $_GET and
$_POST correctly, right?

Yes, you can use $_GET and $_POST (and $_SESSION). And if you leave
register_globals off, then you *must* use them. Less chance for error.

So - as long as I explicitly reference $_SESSION[] when continuing a
session, I'm not subject to the security vulnerabilities of
register_globals, right?
If it is possible to switch register_globals OFF I would very strongly
recommend it. Most hosting companies will have the ability to switch
it on/off per domain or server and it will be much better for
peace-of-mind of you get it switched off.

I recently had a problem when the site that I had been working on
in-house started coming up with all kinds of problems when it was run
on the 'proper', commercial host. Turned out that register_globals was
on, even though they were running PHP4.3 (nice eh?!) and I had session
variables like $_SESSION['userid'] and later in my code I had used
what I assumed would be local variables like $userid ... and of course
they were the same thing and were corrupting each other! Grrr Turning
register_globals off for that domain fixed the problem immediately.
>One more thing - on the session token.
I notice that PHP puts it in the query string.
Is it possible to force that into a cookie?
This is another configuration issue that you should be able to discuss
with your host.

Chris R.
Dec 6 '06 #32
Geoff Berrow wrote:
Message-ID: <lb******************************@comcast.comfro m Jerry
Stuckle contained the following:

>>>So - as long as I explicitly reference $_SESSION[] when continuing a
session, I'm not subject to the security vulnerabilities of
register_globals, right?

True - but ANY misstep can be disastrous. The problem is,

$i = $MyVar;

doesn't cause an error of $MyVar hasn't been explicitly assigned a value
in your code, but it is in the $_SESSION, $_POST, $_GET or $_COOKIES
(forgot the last one)


$_REQUEST ?
$_REQUEST is just a synonym for both $_POST and $_GET. But I don't use
it - it's too easy for a hacker to substitute $_POST values in the $_GET
request.

If I want the form to be posted, I always use $_POST.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 6 '06 #33
Sanders Kaufman wrote:
Jerry Stuckle wrote:
>Sanders Kaufman wrote:

>>One more thing - on the session token.
I notice that PHP puts it in the query string.
Is it possible to force that into a cookie?

I know this will mess with folks who turn cookies off, but I'm
accounting for that elsehow.


PHP can put it in a cookie if the user has cookies enabled. This is
controlled by the session.use_cookies and session.use_only_cookie in
your php.ini file.


I would need my app to handle that gracefully. Is there a built-in
function to programatically determine which way it's set?
You could use ini_get() to check on it. But your server should be set up
to use cookies if they're available, and the query string if they're not.

And if the server isn't set up properly, it's time to get a new host,
IMHO. There are too many out there to worry about trying to get around
problems such as this.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 6 '06 #34
no@emails.thx wrote:
On Wed, 06 Dec 2006 04:04:21 GMT, Sanders Kaufman <bu***@kaufman.net>
wrote:

>>Jerry Stuckle wrote:
>>>Sanders Kaufman wrote:
>>>>If not - then the whole security issue is resolved by using $_GET and
$_POST correctly, right?

Yes, you can use $_GET and $_POST (and $_SESSION). And if you leave
register_globals off, then you *must* use them. Less chance for error.

So - as long as I explicitly reference $_SESSION[] when continuing a
session, I'm not subject to the security vulnerabilities of
register_globals, right?


If it is possible to switch register_globals OFF I would very strongly
recommend it. Most hosting companies will have the ability to switch
it on/off per domain or server and it will be much better for
peace-of-mind of you get it switched off.

I recently had a problem when the site that I had been working on
in-house started coming up with all kinds of problems when it was run
on the 'proper', commercial host. Turned out that register_globals was
on, even though they were running PHP4.3 (nice eh?!) and I had session
variables like $_SESSION['userid'] and later in my code I had used
what I assumed would be local variables like $userid ... and of course
they were the same thing and were corrupting each other! Grrr Turning
register_globals off for that domain fixed the problem immediately.

>>One more thing - on the session token.
I notice that PHP puts it in the query string.
Is it possible to force that into a cookie?


This is another configuration issue that you should be able to discuss
with your host.

Chris R.
Chris,

I make it even easier. I won't host with a company which has
register_globals enabled. And I tell them why I'm switching.

After all - if they don't understand the security risk (or don't care
about it), I don't know what other security gaps they might have. It's
a big red flag, IMHO.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Dec 6 '06 #35
Message-ID: <j6******************************@comcast.comfro m Jerry
Stuckle contained the following:
>>>
doesn't cause an error of $MyVar hasn't been explicitly assigned a value
in your code, but it is in the $_SESSION, $_POST, $_GET or $_COOKIES
(forgot the last one)


$_REQUEST ?

$_REQUEST is just a synonym for both $_POST and $_GET. But I don't use
it - it's too easy for a hacker to substitute $_POST values in the $_GET
request.

If I want the form to be posted, I always use $_POST.
Me too. I was just offering that as a suggestion for one you forgot

--
Geoff Berrow (put thecat out to email)
It's only Usenet, no one dies.
My opinions, not the committee's, mine.
Simple RFDs http://www.ckdog.co.uk/rfdmaker/
Dec 6 '06 #36

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
10538
by: Donald Firesmith | last post by:
I am having trouble having Google Adsense code stored in XSL converted properly into HTML. The <> unfortunately become &lt; and &gt; and then no longer work. XSL code is: <script type="text/javascript"> <!]> </script> <script type="text/javascript"
3
2452
by: H. S. | last post by:
Hi, I am trying to compile these set of C++ files and trying out class inheritence and function pointers. Can anybody shed some light why my compiler is not compiling them and where I am going wrong? I am using g++ (GCC) 3.3.5 on a Debian Sarge system. The compiler complains: //**************************** //****************************...
2
15895
by: ESPNSTI | last post by:
Hi, I'm trying to use a generics dictionary with a key class that implements and needs IComparable<>. However when I attempt to use the dictionary, it doesn't appear to use the IComparable<> to find the key. In the example below, accessing the dictionary by using the exact key object that was used to add to the dictionary works. (see code...
11
3143
by: tomgee | last post by:
I saw it many times, // T.h: class T { public: static T* instance(); private: T() {}
16
1856
by: soorajk007 | last post by:
Hi friends, Im not an expert in the low level activities of C and I need to know how the following works- what is the difference b/w the way -1<<4 and -1>>4 works?? Plz plz explain bit by bit as much as possible... Thanx in advance.. Bye Sooraj
2
2227
by: per9000 | last post by:
Hi, *background* I want a class containing an int (a list of sets of integer). This should be hidden for the user and he/she should be able to insert his/her favourite data structure so to be a little fancy I thought I'd do a Ctor like this: // this is the "core": private int sets;
5
3799
by: sam_cit | last post by:
Hi everyone, I have the following code and it gives a linker error on MS vc++ 6.0. error LNK2001: unresolved external symbol "protected: __thiscall Singleton::Singleton(void)" (??0Singleton@@IAE@XZ) #include <stdlib.h> class Singleton
0
175
by: Matthew Fitzgibbons | last post by:
Urizev wrote: I've run into a similar problem. Basically, when you refer to a class from __main__ (i.e., the .py file you're actually running) versus from an imported module, Python doesn't realize they're the same class. Your Singleton implementation is creating one instance for __main__ and one for everything else. I'm sure there's...
0
7276
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7182
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7408
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7581
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7142
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7548
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
4773
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3259
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
488
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.