Multiple PHP Sessions - php

I am to build a PHP application for a website that already has another PHP application running on the same domain/server.
My app will of course be using sessions, and I don't want my sessions to interfere with the existing app.
For example if I want to use $_SESSION['username'], maybe the other app also uses $_SESSION['username'], which could be a problem.
I'm not looking for an extra layer of security, I trust the application I'm sharing the host with. I just want to avoid bugs.
One way would be to do something like $_SESSION['MY_APP_NAME']['username'], but I want to know if there is an easier way.
I see on the PHP documentation that there is a function called 'session_module_name'. The name sounds good, but the docs don't really explain what it is for.
Any advice?

There is an easier way: session_name.
Prior to calling session_start(); call session_name("something"); (where you change something to whatever you want it to be called).

Another thing that may help you in keeping apps separate is move the session storage to another place either setting session.save_path in php.ini to a folder of your choice or calling session_save_path() before session_start().

Related

Is there a way in PHP to use persistent data as in Java EE? (sharing objects between PHP threads) without session nor cache/DB

Is there a way in PHP to use "out of session" variables, which would not be loaded/unloaded at every connexion, like in a Java server ?
Please excuse me for the lack of accuracy, I don't figure out how to write it in a proper way.
The main idea would be to have something like this :
<?php
...
// $variablesAlreadyLoaded is kind of "static" and shared between all PHP threads
// No need to initialize/load/instantiate it.
$myVar = $variablesAlreadyLoaded['aConstantValueForEveryone'];
...
?>
I already did things like this using shmop and other weird things, but if there is a "clean" way to do this in "pure PHP" without using caching systems (I think about APC, Redis...), nor database.
EDIT 1 :
Since people (thanks to them having spent time for me) are answering me the same way with sessions, I add a constraint I missed to write : no sessions please.
EDIT 2 :
It seems the only PHP native methods to do such a thing are shared memory (shmop) and named pipes. I would use a managed manner to access shared objects, with no mind of memory management (shared memory block size) nor system problems (pipes).
Then, I browsed the net for a PHP module/library which provides functions/methods to do that : I found nothing.
EDIT 3 :
After a few researches on the way pointed out by #KFO, it appears that the putenv / setenv are not made to deal with objects (and I would avoid serialization). Thus, it resolves the problem for short "things" such as strings or numbers but not for more large/comples objects.
Using the "env way" AND another method to deal with bigger objects would be uncoherent and add complexity to the code and maintenability.
EDIT 4 :
Found this : DBus (GREE Lab DBus), but I'm not having tools to test it at work. Has somebody tested it yet ?
I'm open to every suggestion.
Thanks
EDIT 5 ("ANSWER"):
Since DBus is not exactly what I'm looking for (needs to install a third-party module, with no "serious" application evidence), I'm now using Memcache which has already proven its reliability (following #PeterM comment, see below).
// First page
session_id('same_session_id_for_all');
session_start();
$_SESSION['aConstantValueForEveryone'] = 'My Content';
// Second page
session_id('same_session_id_for_all');
session_start();
echo $_SESSION['aConstantValueForEveryone'];
This works out of the box in PHP. Using the same session id (instead of an random user-uniqe string) to initialize the session for all visitors leads to a session which is the same for all users.
Is it really necessary to use session to achieve the goal or wouldn't it better to use constants?
There is no pure PHP way of sharing information across different
threads in PHP! Except for an "external"
file/database/servervariable/sessionfile solution.
Since some commentators pointed out, that there is serialize/unserialize functionality for Session data which might break data on the transport, there is a solution: In PHP the serialize and unserialize functionality serialize_handler can be configured as needed. See https://www.php.net/manual/session.configuration.php#ini.session.serialize-handler It might be also interesting to have a look at the magic class methods __sleep() and __wakeup() they define how a object behaves on a serialize or unserialize request. https://www.php.net/manual/language.oop5.magic.php#object.sleep ... Since PHP 5.1 there is also a predefined Serializable interface available: https://www.php.net/manual/class.serializable.php
You can declare a Variable in your .htaccess. For Example SetEnv APPLICATION_ENVIRONMENT production and access it in your application with the function getenv('APPLICATION_ENVIRONMENT')
Another solution is to wrap your variable in a "persistent data" class that will automatically restore its data content every time the php script is run.
Your class needs to to the following:
store content of variable into file in __destructor
load content of variable from file in __constructor
I prefer storing the file in JSON format so the content can be easily examined for debugging, but that is optional.
Be aware that some webservers will change the current working directory in the destructor, so you need to work with an absolute path.
I think you can use $_SESSION['aConstantValueForEveryone'] that you can read it on every page on same domain.
Consider to refer to it's manual.

PHP Identical Variable Names

I'm really inexperienced when it comes to PHP and hoping someone can clarify something for me when it comes to how variables are handled in PHP.
I have a PHP Web App that I created and needed to make a quick duplicate of, so I simply copy and pasted this app into a new folder on the same server.
I am wondering are there any concerns if the apps, in 2 different folders, have the exact same variable names?
I'm thinking of an accidental overwrite situation. If "no", then can someone explain to me why there is no concern?
No, there will not be any collisions between application global variables as long as the two application directories are truly separate and don't include files from one another. When a PHP script runs, the HTTP request that initiated it can be thought of as an isolated incident. It is separated and isolated from all other requests to the same application (even concurrently) and from other applications.
Each script gets its own variable namespace when execution starts, and that environment is terminated and deleted from memory when the script completes.
Now, if you happen to be using $_SESSION and both applications use the same value for session_name() and run on the same domain name, there is the possibility that values persisting in $_SESSION can collide between your application instances. This is simply solved by changing the value for one of the applications from the default PHPSESSID:
// Application 1
session_name("APP1");
session_start();
// Application 2
session_name("APP2");
session_start();
You probably are already aware of this, but I'll say it to be complete. Wherever possible, it is advised to abstract out aspects of the code that can be shared between the two application instances and included by both of them. This is in keeping with the DRY principle, and will save you lots of headaches if you ever have to make modifications to the code both applications share.
In my opnion you may or may not use indenticle variables names in different folders. this depends on the functionality of your app. you need to do a little research on google 'scop of global and local variables in php'.
In short, yes, you can duplicate the app into new folder, you just need to update/reset the paths (for example the include files paths) and database connection strnigs (if your app use database to store data).

Own SuperGlobal Variable in PHP?

I was reading something about SuplerGlobals like $_SERVER or (see more detail PHP Manual Superglobals) the other day, now, I'm asking me:
Is it possible to implement own SuperGlobals?
Beside of Constants...
So for example user A writes something in the Variable which, if User B is calling it can see.
Something like a server wide Session Variable or something.
Please don't be to hard, if its a silly question :)
I know there are couple of ways outside, like SQL, Xml and Stuff, but maybe...
Your whole idea of PHP superglobals it wrong.
These variables are always available in terms of just one script runtime, no the whole site.
PHP doesn't have context which can be shared between users. You should some replacement like SQL server or file. You may also check some extensions like memcache which might help you achieve your goal.
I was reading something about SuplerGlobals like $_SERVER or (see more detail PHP Manual Superglobals) the other day, now, I'm asking me:
Is it possible to implement own SuperGlobals? Beside of Constants...
Yes it is possible if you've got the PHP runkit extension.
So for example user A writes something in the Variable which, if User B is calling it can see
That's not what superglobals do - they are variables which exist in global scope (i.e. for the duration of an instance of a script).
If you want to share data between different invocations then you need to send it to your storage tier or (in the case of data for a single client) out to the browser.
Since what you are describing here is effectively a shared session, then the sensible place to implement this would be in the session handler.
This is not possible, you can only see your own session data.
To achieve this you would need to store the data somewhere else. in text files or in a MySQL database would be the most common.
i suppose you can use (asterix)export yourvar="something"(asterix) and to receive it using getenv
sry, dont know how to embed asterix=`, but it is better to avoid it...
If you use apache following could be used:
http://php.net/manual/en/function.apache-setenv.php
same idea, enveroinment variable

Should I Make Database Connection With PHP Includes

I've been told that it is unsecure to make database connections inside a PHP includes. For example If I have a login page and add an "include('process.php')" at the top of the page that has a database connection, is that unsecure?
For example If I have a login page and add an "include('process.php')" at the top of the page that has a database connection, is that unsecure?
No.
Maybe the person who told you this was talking about something else - like including a file using a dynamic value coming from a GET parameter, or using remote http:// includes, or as #AlienWebguy mentions, having the password include inside the web root. But using includes in itself is not insecure.
It's only insecure if you are storing your passwords literally in your PHP files. They should be declared outside of the web root. That being said, the lack of security is not due to the use of the include() function.
In and of itself, no, it is not insecure. How it's implemented inside the include is of course a different story.
That's the way I've always done it. I make sure that the include is in a different directory that has open permisions and that the directory your writing in has locked permisions. Hopefully that makes sense.
This question is way too broad to get a good answer from anyone. Short answer is no, there's nothing inherently insecure about including a file that connects to a database. However, if you write code that isn't written properly, then yes it may be insecure to do this.
Since using "include('process.php')" is exactly the same as pasting 'process.php' into the code of the other file, that should not be, per se, a security issue. The insecurity could be in your code, not in the fact the you use the "include". In fact, it could maybe improve the safety of your code, due the reuse.

accessing values globally

I have 2 files namely:
uploading.php
emaillinks.php
both include a file inc.php which has all the include files and initiate database connection.
a variable is declared in file uploading.php, i wanted to know how can i access it in emaillinks.php, i cant include uploading.php in emaillinks.php.
I want to avoid cookies because data is big and always different.
what is the best option to make it accessible by emaillinks.php?
Thank You.
Depending on what it is, you could put it into the database or into the session ($_SESSION)
If you can't include you'll need to go with session variables or cookies.
Reading your question the words "registry pattern" suddenly popped into my head. This might be a bit of overkill for your needs, but it might be worth looking into.
You'd probably have to do a lot of refactoring to make this solution available. So you'd probably be best using the session, database or some text file to store your variable.
Here is a good article on using a registry, though (if you're interested).

Categories