CMS Made Simple: Session getting reset between page views - php

I have a form in a template which is posted to a PHP script. This script sets some variables in the $_SESSION array, then redirects back to the same page using the standard:
header("Location: index.php?page=enquiry-form");
The problem is that whenever the page loads after refirection, the session only contains the following three variables:
cmsuserkey
cms_admin_user_id
cms_admin_username
...all of mine have disappeared.
I'm calling session_start(); in my php script
I've set the config option: $config['use_smarty_php_tags'] = true;
The user doesn't need to be logged in to use the form (in fact the site doesn't use logins at all).
Can anyone suggest anything I'm not doing/doing wrong?
Thanks,
Rich

I had the same problem once and fixed it by addin exit() after the redirection to save the session:
header("Location: index.php?page=enquiry-form");
exit();

I've had a similar problem (though I wanted to use data from the CMS Made Simple session in another php-file). For me the cause was the following (as stated in my comment on the question):
CMS Made Simple (CMS from now on) does makes its own session name. This means that when you run session_start() in a separate php-file, it will not have the same session name. Therefore, the php-file won't be able to access CMS's session data, and CMS won't be able to access the php-file's session data.
The solution logically follows from the cause, you need them both to use the same session name.
CMS sets its session name in include.php which should be in the app's root folder.
$dirname = dirname(__FILE__);
...
$session_key = substr(md5($dirname), 0, 8);
#Setup session with different id and start it
#session_name('CMSSESSID' . $session_key);
So, in your php file you will need to do the following (before calling session_start();):
//Substitute the string $dirname for the result of __FILE__ in **include.php**!!!
$dirname = '/data/web/somefolder/someotherfolder/'
$session_key = substr(md5($dirname), 0, 8);
#session_name('CMSSESSID' . $session_key);
//Now you can call session_start();
Doing this lets your php-file access CMS's Session. If you use any plugins that put essential data in the session, you'll want to be careful not to erase any of that data.
NOTE: I use CMS version 1.8.2, this solution may not work if you use a different version.

Related

Applying session to correct location?

I have no idea if I worded that question correctly, but I worded it very carefully. So, basically here's the thing. I have two directories on my local machine.
/server/core/
and
/server/clients/
The "core" is what handles all of the data processing, this is done so that if I ever need to update my application then I will just have to update the "core" and all of the "clients" that include and call functions that are located in the "core" will be updated automatically. I believe the term for this is a "Dynamic website".
So, basically here's the thing.. I'm using very basic sessions for the time being just to start learning, but I will definately change things around once I'm at a more advanced level. Currently on my "core" i have the following code located in login.php
if(canLogin) {
if(!isset($_SESSION)){session_start();};
$_SESSION['email'] = $email;
header('Location: index.php');
}
Which will load the 'index.php' which is located on the "client" directory. Here's how I have this done.
The following code is located in /server/core/
function createIndex($SQLConnection, $SQLConfig, $PDOConnection) {
global $action;
global $days;
if(!isset($_SESSION)){session_start();}
if(empty($_SESSION['email']))
{
createLogin($PDOConnection, $SQLConfig);
}
}
The following code is located in /server/clients/
<?php
$Configuration = include_once 'inc/Configuration.php';
include_once 'inc/Connection.php';
include_once '/opt/lampp/htdocs/eDashboard2/core/index.php';
createIndex($NormalConnection, $Configuration, $PDOConnection);
?>
Which generates the Index.php file on the core and relays the website back using echos. Please ignore the multiple SQL Connections as it was for testing and will be removed.
So basically, what the problem is, is that the session isn't being saved, or... rather, if I had to guess the session is being stored on /server/core/ and not on /server/clients/
The end-result is that the user is always asked to log in, instead of being able to continue onto the website like they can in the "Client-Only" version of this. (( The client only version was just a static website like you would normally see, the dynamic approach is something I took upon myself to attempt to learn just for the experience ))
How can I make this so the session will be stored for the person logging in.
Use session_set_cookie_params to set the directory to the parent directory:
<?php
$params = session_get_cookie_params();
session_set_cookie_params($params['lifetime'], '/server');
If the sessions also have to exist between subdomains of your domain, you need an additional parameter:
session_set_cookie_params($params['lifetime'], '/server', '.website.com');

How should I make variable global for all the pages in PHP

Question
I want to make $associate_name and $app_key global variable so I can access them on any page I want. Below is the code from my header file and the get variables are coming to index page. It works fine on index page as the $_GET data is available but when a user moves onto next page but with the same header file included it throws an error saying Undefined index. Please let me know how can I make this variable available on all pages. Thanks!
Code
$associate_name = $_REQUEST['an'];
$app_key = $_REQUEST['key'];
define('associate_name',$associate_name);
define('app_key',$app_key);
//echo "Sorry but there seems to be a problem in your code. We can't find one of the following: App name or App key";
$select_associate = "SELECT * FROM associate_account WHERE associate_name='".associate_name."' and app_key='".app_key."'";
$assoc_result = mysql_query($select_associate) or die($select_associate.mysql_error());
if(mysql_num_rows($assoc_result)<=0){
echo "Oops there seems to be a problem in your iFrame code. Please login into your Associate panel and copy/paste the link again.";
}else{
$row_assoc = mysql_fetch_assoc($assoc_result);
$associate_name=ucwords($row_assoc['associate_name']);
$app_logo=$row_assoc['app_logo'];
$app_intro_content=$row_assoc['app_intro_content'];
$bg_color=$row_assoc['bg_color'];
}
Put those variables you want as session or cookie data. Otherwise, you would have to resort to the global keyword, which is a very bad way of doing things in modern PHP applications.
It would be like this (for session):
$_SESSION["myvar"] = <value>;
It's a bit more complicated with cookies, but this should get you going ;)
Have all your variables/constants in a separate file may be constants.php
Include that constants.php wherever you want to access that variable.
Use $_SESSION
Sessions are your choice in case the value is modified. Otherwise (the value is constant from your configuration and not from user's modification, go for Constants

$_SESSION wont work without filename in URL?

I'm currently working on a site where I'm trying to make use of the session variables.
I have a controller script (index.php) that begins with session_start(); and has two different HTML files included within if statements. Everything works all groovy when I go to /quote/index.php, the session variables that I've set are echoed on the page as expected, however if I remove 'index.php*' from the URL so it points to just /quote the page loads however none of the session variables show up.
I'm not using session_destroy anywhere in my scripts and the session variables aren't echoing '0' so I'm fairly sure they aren't being unset, it seems as though they are just ignored without the filename in the URL!
Any insight as to why this is occuring would be awesome,
Thanks
/quote/index.php (with extraneous bits removed):
<?php
session_start();
if (isset($_GET['form']))
{
include 'form.html.php';
exit();
}
if (isset($_GET['fetchquote']))
{
$width = mysqli_real_escape_string($link, $_POST['width']);
$height = mysqli_real_escape_string($link, $_POST['height']);
$_SESSION['height'] = $height;
$_SESSION['width'] = $width;
}
include 'quote.html.php';
?>
The session variables are echoed in quote.html.php
what are the two file names?
seems that one of the file that you are including is named index.html and resides in the mysite.com/quote/ itself. And if I am not wrong, if in a directory there are index.html and index.php then the index.html is loaded by default unless the file is explicitly specified in the url. So it seems in your case when you are not specifying the index.php explicitly,the index.html is being loaded.Of course this is the case only if there is an index.html there in the directory.
Make sure you are also using session_start() at the top of the PHP pages where you want to echo the session variable. And make sure index.php is the only index in your root.
You are checking if an option is set via the GET method. Where is your form using the GET method?
Post your entire script and you'll get much better answers.
This has probably something to do with the validity scope of the session ID cookie. Because if the cookie path is set to /quote/, the cookie will only be available in /quote/ and beyond.

Include CodeIgniter/Php web application within a genreated php page

The context:
I have a web application (e-commerce in few steps) written in php, I am writing a new version with CodeIgniter.
I have to include it within php pages generated by a CMS (sitezen).
/* generated html */
<?php include('my_app/index.php); ?>
/* generated html */
I cannot do anything about the CMS part, like working with an other one...
My problem:
With I cannot start the session before the header has been sent, I also get warnings when using the session but I can disable them.
My Workaround:
I didn't find any help relevant to my problem. The only workaround I could think of for the old php version is to send an ajax request to a php file starting the session.
This is working but there might be a better/cleaner solution, and I don't know how to do it with the CodeIgniter version.
I'd like to avoid using Iframes too!
If anyone knows a way to do it, or has any hint, it will be highly appreciated!
CodeIgniter is a good framework for doing everything in it (as most frameworks), but doesn't like being 'included' from outside.
Why do you need to include him into a different CMS? You may do the CMS in CodeIgniter (that's the base purporse of CodeIgniter), or the e-commerce in sitezen.
If it is because of the surrounding styles, the best it occurs to me is to have it coded also in CodeIgniter. That's not great because you have to mantain styles twice, but it is one of the cleanest ways of achieving what you want.
Warnings are there because of a reason: disabling them does not prevent the result from happening.
What happens to you is that you try to start a session that has already been started. In order to avoid that, you must give the second session a different name from the first. (In a call previous to session_start(), you'll want to call session_name().
Bad news are that once a session has been started, previous data from the session is no longer accesible, so if the CMS stores stuff in the session on __destruct(), the $_SESSION array where it stores the new data in will not be the same $_SESSION() used at the beginning of the CMS bootstrap.
And if you don't start a second session, you'll mix the CodeIgniter and sitezen variables inside the same array (beware of name collisions).
Code like this will NOT work (so, nesting sessions / restoring sessions is, as far as I know, not possible):
<?php
function show() {
echo "We are on [{$_SESSION['name']}] <br />\n";
}
session_name('SUPERSESSION'); session_start();
$_SESSION['name'] = "Super";
session_name('SESSION_ONE'); session_start();
$_SESSION['name'] = "ONE";
show(); # We are on [ONE]
session_destroy();
session_name('SESSION_TWO'); session_start();
$_SESSION['name'] = "TWO";
show(); # We are on [TWO]
session_destroy();
session_name('SESSION_ONE'); session_start();
show(); # We are on [empty] <- resume sessions does not work
session_destroy();
show(); # We are on [empty] <- nested sessions dont work
session_destroy();
To avoid headers already sent warning, start your code with ob_start() in your index.php, and ob_end_flush() at the end
Can't really be done without hacking the CMS considerably.
A CMS provides you with tools to do a specific job, so you are restricted to the CMS capabilities. Similiarly CI is a framework to help develop apps.
do you really have to include it within the CMS pages?
Why not create a link like:
site.com/my_store_app/codeigniter-stuff
then just link to it from within the CMS. You can reuse the existing template, so visually it will look like it's "within" the CMS, but you will be able to eliminate all these other problems.
You're essentially taking two completely different systems and attempting to stick them together.
I'm not sure if it would work for you but you could decide to include them trough curl. Another option is to include the pages directly. Do note that I'm not sure if this would work but if it does you won't be able to send PHP variables to it except trough the link.
include('http://www.example.com/codeigniter/controller/method/id');
Try this. If it works you can do something like this to control it:
include('http://www.example.com/codeigniter/'. $controller .'/'. $method .'/'. $id);
Note: sessions won't work on this method. If you really want sessions to work your best bet would be to separate the applications.
www.example.com <-- your cms
www.example.com/store <-- your webstore in CI

providing login check, page redirect in all pages in php

I am making a simple Dynamic Website using PHP, where i allow the user to login and then access specific pages. So here's what i have done so far.
The logged in values are taken though $_POST variables in a php script where it fetches values from database for registered users. If the user is found i do the following:
session_register('userid');
$_SESSION['userid'] = $username;//this is taken from $_POST
$_SESSION['accesslevel'] = $access;
at the beginning of the php script i have put session_start();
Now here comes my problem.
At every page now i have to check if the user is allowed to view that page or not, if he ain't then he must be redirected to login.php, if he is then the page load must continue.
Now so far what i have learnt is that only way to maintain values across php pages is to use $_SESSION variables, and which ever page i am using Session Variables i must write session_start() on each page as the first line, else i will be getting Headers Already Sent error..
Strangely i exactly have done that but still get erros with the "headers already sent".
SO i want to what is the best way to design a website, where i have to use Session variables across most of the pages, and keep these common checks at a common place..
Can i use include() feature some how?
Are sessions only way to communicate data across php pages.
What is a better way?
I have the following code :
<?php
session_start();
if(!isset($_SESSION['user']))
{
$_SESSION['loc'] = "adminhome.php";
header("location:ettschoollogin.php");
exit();
}
?>
Which resides on top of every page which wants to check if the user has logged in.
And this is teh script to check for login
<?php
session_start();
include("connection.php");
$userid =$_POST['userid'];
$userpwd =$_POST['userpwd'];
$query="Select UNAME,UPASSWORD,SCHOOL,uaccess from schooluser where uname = '$userid'";
$result=mysql_query($query) or die("couldn't execute the query");
$row=mysql_fetch_array($result);
$useraccess = $row["uaccess"];
$school =$row[2];
if(($row[0]==$userid)&&($row[1]==$userpwd))
{
session_register('userid');
$_SESSION['userid']=$userid;
$_SESSION['school']=$school;
if($useraccess =="admin")
{
header("Location:adminhome.php");
}
if($useraccess !="admin")
{
header("Location:school_main.php");
}
}
else
{
header("Location:ettschoollogin.php?err=1");
}
?>
i was aware of the common error of having extra spaces after "?>", BUT I STILL GET IT.
Thanks guys, i missed out and the "connection.php" file actually had extra spaces after "?>" i had removed it before, but some how the file got rewritten again.Thanks a lot.
Yes, you can use include. Put all your common functions in a separate php file and "include" it at the top of each file.
You can use cookies to store information (typically just an id that you use to look up additional information in the PHP page). Normally, PHP sessions are handled using cookies though. See setcookie in the docs.
You are probably getting the error messages due to stray characters outside of a <?php ?> block. A common error is to have an extra blank line at the end of an include file, after the ?>. That blank line will be output and your headers will have been sent. If that isn't the problem, you will just need to make sure you move the session related code above any code that might generate some output (eg by using print or echo).
•Can i use include() feature some how?
Yes. You can do whatever you want before your session_start() call, only, you must not have outputted anything, not even a single space or character. Probably you have already outputted something, maybe on an automatic inclusion or apache prepend.
•Are sessions only way to communicate data across php pages.
•What is a better way?
Other ways are cookies, post and get parameters. But sessions are the only way to securely pass data among pages without sending them to the client and back (which may pose security risks)
Write ob_start(); at the top of your code and then you dont get the error of "headers already send"

Categories