can session variables survive from php -> html -> php? - php

the question is really simple, but i searched it many different ways and the results were not related to my question.
so if i have a session variable in a php file if i open an html page after that and then a php file again, will i be able to retrieve the data ? or do they all have to be adjacent?
I tried php->html->php but i couldn't get the variables on the other side. maybe Im doing something wrong.
Thanks in advance

Not 100% sure what you mean, but if by "open" you mean in the browser, the calls do not need to be adjacent. You just need to do a session_start() in every PHP script in which you want to use session data.

Adjacency is not something that is really relevant for this question.
in PHP way of things, sessions are essentially files that contain serialized data on the server. The browser that called a script containing session_start() call receives a special token that identifies the session on the server, and it is normally (though not necessarily) stored as a cookie.
This effectively means that any php script that uses session_start() and receives a session id (via cookie or otherwise) will read and could use session data, unless it was removed from the server file system between the calls, or the session has expired (frankly, I'm not sure whether PHP removes the expired sessions on the server side).
Accessing anything outside of this model with the browser (html page, or even other sites) will not affect it in any way, unless these actions change or remove session id.

yes...session variable can survive php->html->php.
But on every php page ...very first line should be session_start()

This easy way (I guess): Set a cookie storing the session ID on the first php page. This way, every other php page can access the session ID and use it to restore the stored data, not matter how many (even foreign) pages were in between.

Related

PHP - Issues with session variables

I'm having an issue on my website. I'm not posting any code because I don't think there is anything relevant to show and I've done things alike several times. My question is just about logic.
I have a page that sends ajax requests to two other php files. These files use session variables to build some JSON.
The problem is some session variables are seen only by one php file. When I check the output of var_dump($_SESSION) I can see that one file sees all the session variables, and the other one can only see the ones it has set in the previous calls. When I check the session IDs, I can see that both files have different session IDs.
Do you have any idea about what could be the problem, or just tracks to follow?
check whether you have session_start() in both pages before using the sission variables
I finally solved it. The problem was linked to the domain name. When you use subdomains, or don't add "www", the browser thinks it's a different domain and doesn't send the cookies, then a new session is initiated.

How to keep track of one php variable in another php file in command line without any session concept?

I am trying to give user an option to register into the system and want to link the page to another php file say detail.php page with all the database variable remain active in that file. Please anyone can help me out..??
Other alternatives are cookies, (encrypted) POST parameters sent to that page or if you are using include statement to include the contents of that file in the current page, you may as well define your variables just before include and those can be used in the included file.
P.S.: Use of sessions is recommended; though its not clear from your question, why you dont intend to use sessions.
Any options you may have rely on the client sending some form of way of identifying the initial user.
You basically have 3 options:
Keep resending all of the data you need to complete the registration to every page via a form (i.e. as either GET or POST data).
Storing the data in a COOKIE and sending that with each request.
Storing the data serverside and using the session (and PHP session COOKIE)
Personally, I'd recommend sticking with using the session as it limits the amount of data being sent between requests. The only reason I can think of not to do this is if you multiple application servers and no shared storage for your sessions (i.e. memcache or database)
If you want to elaborate on your OP and explain why you don't want to use sessions, I'd be happy to give you a more indepth answer.

Storing large amounts of info within a cookie

I'm working on a demo tool (PHP, jQuery, XHTML), so far so well, except that I have an issue, I need to save certain information temporarily and I'm doing it through cookies, however the cookies' limit in Apache is 4Kb and I have no longer space within the cookie, so I'm wondering how can I keep saving inside the cookie without a problem if I still don't want to send any information to databases nor text files.
I don't know if maybe by using path or other domain I might be able to work things out.
I would really appreciate any help you can provide me :).
Sessions are like Cookies but they just give the client a unique ID ("session ID") and keep the rest of the data on the server.
Of course this is stored within a database or file but that's totally transparent to you, there's no messing about with SQL queries or file reads or anything.
You just need to replace all $_COOKIE with $_SESSION and put session_start(); at the top of your code: http://www.tizag.com/phpT/phpsessions.php
One downside though: PHP sets all session cookies with no timeout, which the browser usually treats as "delete this cookie whenever the browser is closed". See this question for workarounds: How do I expire a PHP session after 30 minutes?
First you should consider if saving that much data in a cookie is really needed. Maybe you can compress your information or just dont need all of it?
The reason is: the cookie is send at every request to the server (this might more then 1). If you serve images from the same domain, you may get over 20 requests each is sending this large cookie. Assuming your cookie holds 5kb of data, you have 100kb just to loop your information through.
see: http://developer.yahoo.com/performance/rules.html#cookie_size
if you need your information just for the current session, why not saving it into a session var (or memcache etc.pp.)?
Maybe its okay if you just save an id in the cookie and if nothing to this id is in your session, you load it from database and save it in the session. so you have a one-time access per session.
Maybe its better if you provide some more background information.
You could create multiple cookies, but it's a bad idea. The cookies will go across the wire with every request. Consider putting your session information in a database or cache tier.
I guess you could store non-sensitive information with a DOM element. If you are using jQuery you can use .data() - http://api.jquery.com/data/
However, after the page does a full reload its gone.

PHP Session not written after Output(echo or print_r on external ajax Call)

I´m having some serious trouble debugging this particular problem and I hope someone has a clue what i´m doing wrong.
I have a Custom CMS system working that uses Paragraphs as building blocks that get updated using Ajax(prototypejs) calls and functions that parse the HTML chunks in given order, clean them up and save this data in associative arrays in a Session variable.
Users log in, Session is created and I can check for this session without problem in every page I need it. The system works directly on the definitive websites, so the user can see his updates on realtime and browse the site as a normal user would do, but editing.
So, nothing new here. But here is the weird thing.
Enduser site on edit mode(admin user logged in): path "/"
After the logged status is verified, a function processes the editable content and saves an associative array to session, it also starts some javascript objects for editing every paragraph. Data is actually saved, I can use an external script to check if it´s there after this php script ends.If I load a new page(new content), Session gets updated with new data)
Admin User modifies a paragraph using an Inplaceeditor and this HTML chunk is send via Ajax to a php script that starts the named session, reads the present session data, checks if a paragraph should be modified, appended or deleted and reassigns values to existing array keys in $_SESSION. if i make a var_dump() o print_r to $_SESSION after assigning new data is there.After that the script echoes the processed html, and ajax updates the original paragraph on the calling page.
This script is in /admin/cms/...etc, that means at least 4 directories inside the root of the site.
When the script ends, I check using the same session dump script to see if data was really written/commited, but no, $_SESSION has only the original data from the calling page.
Same ID, same session name, same session_start() but no data gets written.
This whole operation is very quick, so I though it could be a speed problem, scripts ends before session_write_close can make his work.
But if I add a new key to $_SESSION array and put some data there, data gets updated and written. If i don´t output anything on this script and just process data and set session variables it also get´s updated and written.
It´s like some members of $_SESSION array are getting blocked to update.
What i did to track this error and what i´m sure i´m not doing wrong.
1.- register_globals are off of course
2.- session_name() and session_start() are always present and in the given
order. I used to have multiple
session_start() -close on a same page
to use several named sessions, but to
refine the problem this is not longer
so.
3.- I use session_write_close() after session data is processed. Also
tried without, letting php decide
when to commit data, but no luck.
4.- I`m using only cookies for SID.
5.- sessions are stored on /tmp, i can see the data getting updated.
I also tried using a custom save
handler on DB, but same problem,
"_write" got only called when no output as present.
I searched php.net, stackoverflow, google, etc for this subject. I never ask without investigation, this is my first time in many years...but it´s just so unlogical it must be something tiny a haven´t thought of.
The most weird thing is that when I just process data without output $_SESSION gets updated ok. But if i modify this script afterwards by adding the output and try again, instead of just having the new(last) value present I get the original value back, the one created by the calling page at first place, sometimes after playing around a few times! PHP can´t cache values between scripts or?I dont have globlals on.
I´m really clueless. This system worked flawless on PHP4.3, since i´m using 5.3.3 for two moths my users where caliming data where getting mixed up, so i checked and yes, there are serious problems. Today I updated to (5.3.6) and I can´t get this session values commited.
Script code called via Ajax:
<?
session_cache_limiter('nocache');
session_name("CMS_ses");
session_start();
include('../htmLawed/htmLawed.php');
include("utils_cms.php");
include("../../../php/utils_array.php");
$value=$_POST['value'];
$editorId=$_POST['editorId'];
$clase=$_POST['clase'];
$editorId=str_replace("pre","",$editorId);
$value=html_entity_decode(stripslashes($value),ENT_QUOTES);
if (strlen(trim($value))==0)
{
die();
}
$value="<div id=\"$editorId\" class=\"$clase\">$value</div>";
$newXHTML=$value;
$retorno=CMS_nuevoBloque($newXHTML,$editorId);
$_SESSION['data']['CMSeditores']=$retorno[1];
$_SESSION['data']['CMScont']=$retorno[2];
session_write_close();
print_r($retorno[0]); //Offending part...without everything works
?>
really nothing strange here....main page code is even simpler, no strange php directives, etc.
Here is the header of the caller page
include 'php/db.php';
$len=$_GET['len'];
$sec=$_GET['sec'];
$cont=$_GET['cont'];
$admfin=$_GET['admfin'];
$fecha=$_GET['fecha'];
$token=$_GET['token'];
$cur=$_GET['cur'];
$PHP_SELF=$_SERVER['PHP_SELF'];
session_cache_limiter('nocache');
session_name("CMS_ses");
session_start();
$passvar='';
unset($adm);
if ((!empty($_SESSION['cms_logged'])) and (!isset($admfin)) )
{
$nivelpermisos=$_SESSION['cms_logged_group'];
$useractual=$_SESSION['cms_logged'];
$adm=1;
}
elseif (empty($_SESSION['cms_logged']))
{
unset($useractual);
}
//.........rest of the code
UPDATE: I did late night tests and found someting i don´t understand.HElP please:
It has not only to do with Sessions but also with Mysql Querys. Same code, but instead of trying to write to $_SESSION array i made a simple update to a Innodb table using the session_id. When i Output some code, the update does get executed,(i can output the query string and no mysql_error() or notice) problems, but checking the database the row doesn´t get updated. Letting the output out if the script and Query does get commited. Only common thing is sessions are started and output is made.
I restarted Apache, etc(who knows) but no luck. Then i made something really stupid, because this is a server side thing. I changed my browser to Firefox(using safari) and everything works! Ok, recheck, back to safari, nothing works. Both running side by side, same issue. PHP is server side, how can different browsers handle code different, can a browser say to apache rollback, request not handled or call the same script twice without notice(checked safaris developer console and the script is called only once) ? Can safari resubmit data silently because it "thinks" ajax failed? I checked headers using firebug and Safaris developer tools , nothing strange but whenever i make a Ajax call with safari, the caller page reloads data(Aka conection to server...).
I really don´t understand nothing.
I had a similar problem to this (if I have understood correctly). I needed to force session data to be written (for a custom session driver) after scripts have finished running. A shutdown function can be registered which should run after scripts have finished.
Maybe this will solve (or help you to solve) your problem.
http://php.net/manual/en/function.register-shutdown-function.php
Thank's for your help. I was doing everything in the right order and still session data was not being written. Session names where necesary because sometimes we test many sites on the same domain using the same custom CMS. So, finally, after making lots of test and no luck, i found that register globals was active on this server(we never use it, code was written having this option off in mind of course), but it messes with sessions!. Switching this off made a huge change. No more problemas. I also made a custom session handler in DB, so i could track the problems in an more centralized way.
Conclussion: Never use register globals + named sessions, an complex data in sessions.
Anyway, i will give this issue more time and more tests. Ajax calls are also sometimes too fast, i had to put a sleep command so writing the session data was really done.Thanks
I am not sure but few suggestion i think may be helpful.
delete session cookies before refreshing the page for testing purposes :)
Ensure that you're not assigning any arrays with a key containing the pipe character (|). This will prevent the session data from being serialized and saved.
Do session_regenerate_id(true); many cases session_write_close doesn't seem to matter with out session_regenerate_id. or just do session_start() after session_write_close() if you are relying on SID ; and in your case i think this is what is causing problem to you as you are ending the current session every time and not re starting it for the next page. hope u get my point. Further more To Make sure data is actually flushed out to the browser use ob_end_flush();
i could not understand the connection between
$_SESSION['data']['CMSeditores']=$retorno[1];
$_SESSION['data']['CMScont']=$retorno[2];
and
$nivelpermisos=$_SESSION['cms_logged_group'];
$useractual=$_SESSION['cms_logged'];
i think you need to paste some more code where the data part is causing problem instead of admin login part.
i hope this helps you.:)
Is there any reason you're establishing the session name twice? I've had issues in the past where I would establish the session without a name, then another piece of script (not mine) was naming the session. Even at the end of the script I was able to print out the session variable, but once I went to a new page my session had been forgotten. It wasn't until I copied the name included in the 2nd script into my session call that it was solved.
Check that there's no other session names being used; also, maybe try only naming the session once, at the first call to the session?
Question: Are you calling session_start() first thing... before ANY output to the browser and before any variables are assigned?
Sounds silly but give it a try.
Also, why are you using session names? Really not necessary unless you have a lot of session variables with the same name serving different purposes and if thats the case then you need to fix that first!
I had a similar problem but it was having with ie few years back. IE manipulates the header on its own way and that causes strange php bugs that you can find in php.net archives.
#Diego Pino Navarro, please see this help page and find Safari and it's issues with php.
I also found "Safari "forget" http-authentication's logon-information".

how do php share data without access a DB

I have two pages and I want to pass data to each other.
How can I do this without accessing a DB?
Sessions? Cookies? someother magical way?
If you know how, can you please post sample code?
Thanks
Session variables is one way:
$_SESSION["variable"] = "value";
This variable can then be read/modified by another page.
Also note, that you need to start the session by calling start_session(); at the beginning of your script.
And Cookies are another way... You can also try writing in and out of a file instead of a DB
How does a user get between these two pages? I assume a Form based solution is out of the question...
Amongst the possibilities, here are some that I think about :
You could $_SESSION (see Session Handling) -- if both pages are accessed by the same user, without too much time between the two accesses, so the session doesn't expire.
You could store your data to a file ; that'll work fine if :
The amount of data is big
You want it to persist for a long time
But you'll have to do some cleaning-up by yourself
Another idea would be some external daemon, like memcached
But, as it's a caching engine, it's not necessarily good for storing data : the data that is cache can be removed from the cache even if it has not expired yet (i.e. if there is no place left in cache, memcached will remove some least used data)
Of course, if the data is small and you don't mind it going back and forth through the network, and both pages are accessed by the same user using the same browser, you could use cookies
Only a couple of possibilities, though ; my preferences would probably be :
$_SESSION
or files
Depending on your situation.

Categories