tags:

views:

102

answers:

2

If I have a page with multiple <?php ... ?> sections interspresed with pure HTML sections. I notice that a $_SESSION varible set in one <?php ... ?> section is not available in another on the same page.

So, what's the best practise?

1) call session_start() as the first line of each <?php ... ?> section?

2) only have one <?php ... ?> section which covers the whole page? If so, I have to wrap each HTML section in echo, which is annoying of they are HTML form elements. Maybe heredoc them?

It's my first time to try this sort of thing, but I am not the first one to do so - what's the accepted best practise?


Edit: Aplogies, my stupid fault. One of the sections PHP started with <? and not <?php

+3  A: 

If I have a page with multiple sections interspresed with pure HTML sections. I notice that a $_SESSION varible set in one section is not available in another on the same page.

The sections of php tags <?php ... ?> have nothing to do with session. Make sure that you put:

session_start()

on top of your page.

Sarfraz
+! thanks. That was my understanding (from reading, not actual practise, but it isn't working that way. A single page with 3 PHP sections. Session_start() in the first, set a $_SESSION[] variable in the second, var_dump() in the third and it is null. Caveat - I am using Xampp and the pages are on lcoalhost - this has given other problems in the past.
Mawg
oops, sorry - bad code - see editted question above.
Mawg
@mawg: o right those are silly but hard to find mistakes sometimes :)
Sarfraz
+1  A: 

As long as you set the header before doing any output, you shouldn't have any issues with the session (as the function session_start() also set the header).

There is really no problem having multiple PHP sections on a page. But I would highly recommend, to do all the logic (reading from database, processing form data) in a separate file OR in the first section.

Kau-Boy
+1 thanks. AS I said above, it might be an Xampp issue. I will upload to a real website, not localhost, and tgry there.
Mawg
oops, sorry - bad code - see editted question above.
Mawg