Where exactly do I put a SESSION_START? [duplicate] - php

This question already has answers here:
When do I have to declare session_start();?
(2 answers)
Closed 9 years ago.
So I'm starting my own website and I have the login file pretty much made. I just need to figure out where to put the session_start to keep the user logged in. Where exactly do I put the session_start? Do I put it right in the login file? Or where do I put it?
Thanks for the help

Put it after your PHP start tag <?php ... like this
<?php
session_start();
//... your code....
//more code....
Read more on sessions from the PHP Manual. Here
Note : Also keep in mind, you need to call session_start(); on each and every page if you are making use of session variables.

Put it right after the start tag, or else headers will have been send, and the session, AFAIK, has to be the first header sent
<?php
session_start();
//session code here
?>

Right after <?php tag.
Be sure that there is NO output before this function (even a space symbol or so).

You want to put session_start(); at the top of your page before any other code. However, if you are using includes to make your life easier, it's best to put it at the very top of a file that is included in all files. For instance, when I make a website, I put all of my header code and footer code in separate files and include them in the other files. I also have a functions file that is included in every other page of the website. So for my index file, it may look something like this:
<?php include_once("includes/header.php"); ?>
<div id="content">
Website Content
</div>
<? include_once("includes/footer.php"); ?>
Then, my header file would start like:
<?php include_once("includes/functions.php"); ?>
<!doctype html>
<html>
<body>
Then at the top of my functions file:
<?php session_start();
[functions]
?>
In this way, the functions files' code gets ran first, therefore the session start code is the very first thing hit. Why? You cannot have any type of output to the browser before starting a session.

it's better to have a separate file other than your login to do some common stuffs.
i think your login file will be generally handling user verification and validation thing. so don't include that file on every page.
have one more file that
includes all required files
keeps all your analytic scripts
initializes global variables
and this file you can start with <?php session_start(); ?>

session_start() needs to go in every page/file that refers to $_SESSION (obviously the login page is included).
Because you should only be calling it once, I tend to write a lazy_session_start() method (and tend to put it in an include file):
/**
* Lazily calls session_start (to prevent warnings).
*/
function lazy_session_start() {
if (!isset($_SESSION) || !is_array($_SESSION)) {
session_start();
}
}
It could be called like so (before you need to use $_SESSION):
<?php
//you must either declare "lazy_session_start" function
//or import the file containing the function definition.
require_once('lazy_session_start.php'); //or something.
lazy_session_start();
//... you may now use the $_SESSION array.

Related

Unable to setcookie() when SSI-include a PHP header file

Really lost here on what to do next. Lets say, I have
header.php
<?php
setcookie("the_cookie","data",time()+60);
?>
//followed by HTML codes
index.htm
<!--#include file="header.php"-->
<html>
//standard html stuff here
</html>
When I include header.php in any of my html file, it fails to set cookie. This is despite
<!--#include file="header.php"-->
it being the very first line on my html document and setcookie being the very first line of the header.php The Apache server is SSI enabled. So I am certain the #include works as I have other HTML codes after the setcookie() function , and it shows correctly.
But when I run header.php itself, the cookie is set correctly. Has anyone here has ran into such situations before and knows what needs to be done?
Thank you in advanced
Gary Cho
I had the same problem, I solved it by using $_SESSION[] instead of setcookie(). Another benefit is that you can use also echo $_SESSION[] in the same php run that you set your $_SESSION[] value. I hope it works for you as well.

Alternate Headers with SSI and PHP

I have two headers: one to display for a logged in user, and one to display when logged out/not a member. I also have a footer that should be duplicated on each page.I had the idea to use SSI to include the header and footer.
As of now, we haven't started much server-side processing, and thus don't keep track of logged in/logged out users. As such, for now, I just want to use the page that is including the header to determine which to display. I had the idea to use a PHP file as the header instead of an SHTML file, so I could do some processing to determine which header to show.
So is it possible to determine which page is calling the include with PHP?
Am I going about this all wrong? If so, what solution is more appropriate?
For example, each html page fits this general layout:
<html>
<header>
<!-- relevant header calls -->
<header>
<body>
<div id="body">
<!--#include virtual="header.php"-->
<!-- actual page content -->
</div>
<!--#include virtual="footer.shtml"-->
</body>
</html>
And in header.php I want something like:
<?php
if(/*page is a non-logged in page*/){
echo(/*logged out header*/);
} else {
echo(/*logged in header*/);
}
?>
So is it possible to determine which page is calling the include with PHP?
No idea. But if it is possible it will be via $_SERVER. Put this in your header.php for testing:
<?php
echo '<pre>';
print_r($_SERVER);
echo '</pre>';
However, if the page is being requested as *.html with Server-Side Includes I can't even begin to predict what kind of havoc this is going to play with PHP Sessions. I have doubts that session_start() will ever be able to set proper headers in this context, or if the PHP session cookie will ever be sent to the client or be passed through SSI back to PHP.
As far as I am aware/concerned SSI should only ever be used to include static content or dynamic content that does not rely on any sort of interaction with the user, including something as basic as if they're logged in or not. SSI is a kludge between static and dynamic pages and should be referred to as "kinda-sorta-dynamic-but-not-really".
Short answer: SSI is going to be a massive pain in the ass, ditch it and just use PHP include().
Edit: Your page would look something like this at the most basic level, and is not really any more complex than using SSI. If you took a more MVC-oriented approach [namely the C and V parts] it would become more manageable:
<?php
session_start();
// other initialization
?><html>
<head>
<!-- relevant header calls -->
<head>
<body>
<div id="body">
<?php
if($_SESSION['is_logged_in']){
echo(/*logged out header*/);
} else {
echo(/*logged in header*/);
}
?>
<!-- actual page content -->
</div>
<?php include("footer.php"); ?>
</body>
</html>
For the sake of ease in programming it's best to use one or the other. It's best to go with PHP exclusively because:
Massive support community at php.net
In most implementations it's faster than using the SSI because PHP is designed to do all of the processing and parsing of PHP code, whereas an SSI has to read your SHTML page (after it's written) and sift between comments and includes, then include all of the components.
If you're including PHP pages as SSIs you're making Apache wait on PHP, whereas if you were using PHP alone it would have already delivered the page.
You can do things with databases and a lot more with PHP.
PHP pages can't be accessed from the server without being processed, so there is less risk of someone exploiting your code vulnerabilities if you're using standard practices.
SSIs are plainly readable as code (and very limited).
You can include an SSI with PHP if you're running PHP as an Apache Module, using the function virtual(), but why would you want to? You can include() just about anything into PHP.
Example
I'm going to use an account management site as an example. To make the header dynamic you'll need to find the $var for the page calling it (I'm going to use $_SERVER['REQUEST_URI']). There are several reserved server variables in PHP that you can reference to make calls depending on circumstances. So let's say the authorized directory where all logged in pages go is called "auth" your common shell file might look like this:
<?php
//Check for the page the person is asking for
session_start();
$root = $_SERVER['DOCUMENT_ROOT'];
//Check for the "auth" directory
if(preg_match('!^/?auth!',$_SERVER['REQUEST_URI'])){
//Do some check to see if they've been authenticated... this one is not secure, but you get the idea
if($_SESSION['logged_in']){
//Require the correct header
require_once($root.'/includes/logged-in-header.php');
} else {
//They don't belong or they're not logged in, kick them back to the login page.
header("Location: /login.php?e=1");
die();
}
} else {
//It's not an authorization required page, so show the standard header.
require_once($root.'/includes/non-auth-header.php');
}
//let's find out the page that's loading the shell.
$pageName = preg_replace('!/([^/]+)$!',"$1",$_SERVER['SCRIPT_NAME']);
switch($pageName){
/*Auth pages*/
case "billing.php":
require_once($root.'/includes/billing.php');
break;
case "account.php":
require_once($root.'/includes/account.php');
break;
case "logout.php":
require_once($root.'/includes/logout.php');
break;
default:
//show the login page
require_once($root.'/includes/login.php');
}
require_once($root.'/../shell.php');
require_once($root.'/includes/footer.php');
?>
So if you were in the auth directory and you were not logged in, you would get the homepage. If you're in the auth directory on the billing.php page and you are logged in, the site would load the billing page.
The auth/billing.php code might look like this:
require_once("$_SERVER['DOCUMENT_ROOT'].'/../shell.php');
The include/billing.php code would contain all of workings of the page and it can be formatted in HTML, but you'd probably pull that stuff from a database.

include header vs include page

I'm currently using include 'header.php' and include 'footer.php' in every page, and as far as I know that's how most people do it. I thought of a way that I personally thought would be better, however. I thought of making index.php, then in the index include the page. This would both eliminate the need for a footer and eliminate the need for include twice in every page. I'm really new to php, however, so I don't know how I would do this. I tried using POST and GET methods, but it doesn't seem to work. What I want to achieve is including pages in the header using a URL such as http://mysite.com/index.php?page=history and then load history.php. If I need to clarify something, just ask. Sorry if I don't accept an answer right away, I'm really drowsy. I'll get to it when I can.
It is not a problem if you include 2 pages in a file, like header.php and footer.php...
Just writing 2 lines of code in each page is not a matter.
You can decide what pages you want to include dynamically in every page by using if statement, instead of passing the page name in the url.
If you'll do it via index.php, you will no doubt do it wrong.
Nothing bad - every newbie does it this way.
Just because you're thinking of includes, while you should be thinking of templates.
You can make it via index.php, no problem. But there should be not a single HTML tag in this index! As well as in the actual page.
No matter if you're doing it in separate pages or via index.php, the scenario should be the same:
Get all data necessary to display particular page.
Call a template.
Thus, your regular page would look like
code
code
code
include 'template.php';
while index.php would look like
get page name
sanitize page name
include page
include 'template.php';
now you can decide what to choose
First off i agree with Meager... Take a look at soem frameworks. Most will use a two step view which essentially does this althoug in a more complex and flexible way.
With that said it would look something like this:
<?php
$page = isset($_GET['page']) ? $_GET['page'] : 'home'; // default to home if no page
if(file_exists($page.'.php')) {
// buffer the output so we can redirect with header() if necessary
ob_start();
include($page.'.php');
$content = ob_get_clean();
}
else
{
// do something for error 404
}
?>
<html>
<head></head>
<body>
<?php echo $content; ?>
</body>
</html>
You could get more complex than that. One thing you want to do uis make sure you dont blindly assume that the page in the $_GET var is safe... make sure the file exists on your server or otherwise sanitize it...

How can I redirect using a PHP script called from an SSI?

On a WAMP server, I have a server-side include in a file, a.shtml, composed of the following code:
<!--#include virtual="./req.php"-->
The contents of req.php are:
<?php
Header("Location:index.php");
echo "still here";
?>
When I open a.shtml, I see the text still here, but the page has made no attempt to redirect itself. Why is this? And is there any way to make it work?
Thanks for the help
EDIT: The reason I want to do this is because I have some session variables that I want to influence the way the PHP script acts. If the session variables are not set, I need it to redirect to a login page. I know I can just write the entire thing in PHP, but I'd like to do it this way if possible. If it's not possible to change header information from an included PHP file from SSI, then I'll just do it entirely in PHP.
it's impossible
you don't need that.
just address tour script that set session variables directly, not through ssi
MAYBE (with capital letters Lol), you can pull this off if you call that script in an IFRAME and that IFRAME outputs some JScript like window.parent.location = <some_url_here> forcing its parent to change its location... Its just fast-thinking from my part, I might be wrong with IFRAMEs' parent-child relation to the original document, as I haven't tested the "idea" myself :)
If your req.php returns the following html code, the redirect will happen:
<html><head>
<title>HTTP 301 This page has been moved</title>
<meta http-equiv="Refresh" content="0;URL=https://www.example.com/index.php">
</head>
<body></body></html>
But: "Google Warning: Using The Meta Refresh Tag Is Bad Practice"

PHP session and multiple mixed PHP/HTML sections in one page

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
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.
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.

Categories