global variables in a loaded page - php

I have my index page which uses a script to load another page into a div
$('#TransportPlanning').click(function() {
mainpage = $('#FloatMain')
mainpage.load('create_diary.php')
});
The page loads ok into my div, but I want to share php variables from one page to another, I thought the newly loaded page would be able to reference the main index variables but this is not the case , I have tried global but still not working
Any help please ?

To Share Variable Between Two Different PHP Scripts, Make It Super Global :
Use
session_start();
// store session data
$_SESSION['key']=value;
In index.php And read it in crate_diary.php as :
session_start();
$key=$_SESSION['key'];
And Do That ($key) Variable Specific code in create_diary.php.
Using Session or Cookies Prevent Unethical Use of Your Sensitive Data. You Can Also Use Cookies Instead Of Session. But Dont forget to unset session after you've done with it. Specially When you are dealing with cookies because Session will get automatically destroyed when user closes browser but this isn't true with cookie.

Global variables are not shared across scripts.
Pass them as query arguments instead, like:
mainpage.load('create_diary.php?key=value');
The value will be available within your create_diary script in $_GET['key']

Related

What can destroy a $_SESSION variable php?

I am working on a webapp in php, and my session keeps getting destroyed on only certain views of my application and I can't seem to find out why. I can't upload all the code here because there is too much, so I want to know what can destroy a session and I will look for the problem.
The weird part is that it happens inbetween two views, for example it fully loads the first view with no problem (I checked with echo statements at the end of that view to make sure it was still active) and when I click on a link the session variable is destroyed before loading the next view.
if it happened only on certain view, is there any session unset or session destroy? and maybe you need to add session_start() on controller which have those view (linked). (read also https://www.sitepoint.com/php-sessions/ about session_start section )
You can destroy ALL the session array :
session_destroy();
Or only unset some parts :
unset($_SESSION('your_thing']);
An other way is to put empty some parts of the array:
$_SESSION['your_thing'] ='';
All are correct, but if you destroy all the session, on the next page you have to set session_start(); if you want use session, but you 'll lose all informations.
the best way is to use unset or empty the array ...
You can use the session_destroy();-function to destroy the whole session (and all $_SESSION-values with it) or you can the unset-function to destroy a value by key as if $_SESSION was an array.
Make always sure you're using session_start() the right way. On top on every page you are using the sessions. The session keeps destroying because the session was never made. To make it work, be sure you have set up the session start like this example:
<?php
session_start(); // Be on top
?>
<!DOCTYPE html>
<!-- The rest of your page
I hope this will help you

PHP session variables life

Newbie question, but I'm wondering if I'm missing something elementary here.
If I register a session variable in a page - isn't this variable supposed to be accessible from another page on the same site?
First, I register a variable in the file session_var_register.php:
<?php
$_SESSION["myusername"] = 'user';
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
When I open this page, it writes:
Session var myusername is set to user
As expected.
Then I open another tab and another page, check_session_var.php:
<?php
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
This page is blank.
Isn't the point of a session variable that it should be accessible in the browser session, until the session is programatically destroyed or the browser closed?
I'm using IE 8 and Firefox 24, btw. Identical results.
You forgot
session_start()
On top, before using
$_SESSION
PS: Remember to call session_start() in every page you want to use $_SESSION.
The PHP docs state that you must call session_start() to start or resume a PHP session. This must be done before you try to access or use session variables. Read more here.
session_start();
Your session variables will be available on different pages of the same site but on top of each of these pages you must have at least:
session_start();
It works but not in all cases. You must also use the same session name (essentially a cookie name that stores id of your session) on all pages. Moreover cookies (which are essential (mostly) for sessions to work) may be made visible only in specific directory. So if for example you share the same host with other guys that use sessions too you do not want to see their variables and vice versa so you may want to have sth like that:
1) session_name( 'my_session_id' );
2) session_set_cookie_params( 0, '/my_dir', $_SERVER['HTTP_HOST'], false, true );
3) session_start();
You may also want to see your session variables on other servers and in such case custom session handlers may be useful. Take a day or two to implement yourself - great way to understand how sessions work hence I recommend.
Method
session_start();
Description
session_start() creates a session or resumes the current one based on a session identifier >passed via a GET or POST request, or passed via a cookie.
Usage in your case (and in the most of cases):
Put it before the $_SESSION usage.
Reference: session_start()
First Of all start session on that page
session_start();
your page like this way
<?php
session_start();
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>

Writing to a PHP Session Variable from Ajax

Ok, this is starting to annoy me, as it's quite simply and works elsewhere, but on this current task it doesn't, so here I go!
There is a main page which relies on either a session variable being set or not to display certain information.
Let's say this page is located here: http://dev.example.com/some_page.php
e.g.
if (isset($_SESSION["some_var"])) { /* it's set so do whatever */ }
else { /* not set so do whatever else.. */ }
There is an ajax page triggered by jQuery $.ajax() to call and set this session variable to null to change the action of the main page, let's say it's located here: http://dev.example.com/ajax/some_ajax_page.php
It's code looks like so:
<?php
if (!isset($_SESSION)) session_start();
$_SESSION["some_var"] = null;
When the main page is reloaded after the ajax is triggered, the session var "some_var" is still intact, but if it's echoed after the "null" in the ajax page then it is set to "null".
Basically it doesn't seem to write to the global session, only to the local path.
Does this make sense?
Any help please? Also if you want more clarification with anything let me know!
The session_start() function will handle the attempt to create and persist a session for you, as defined by PHP's configuration, or optionally at runtime if you set your own save handler. Make sure you read the documentation here:
http://us2.php.net/manual/en/function.session-start.php
For your code, you want to make sure to call session_start() at the beginning of any page in which you'd like to save or access session variables. So your page above may look like:
<?php
session_start();
$_SESSION['myvar'] = 'some value';
Then in a different page you can try to access that value:
<?php
session_start();
if ($_SESSION['myvar'] == 'some value') {
// do something
}
That should work fine.
Get rid of the check for session. If this is the only file your calling just do this:
<?php
session_start();
$_SESSION["some_var"] = null;
Also, are you using framework that auto-regenerates session ID on each request? If so, you'll might have problems.
If you have a dev machine to play with and permissions to do so, you can manually delete all sessions in the /var/lib/php/session/ directory. As you use your site, only one session file should be created. You can also inspect that file to see what is getting written and when.
Seems that you are using different sessions vars. One for the AJAX call and another for the normal pages calls. This may occur when you do not init both call in the same way (or using the same starting code that initializes the sessions)
Be sure to session_start() both calls using the same session_id.
// try in both calls
session_start();
echo session_id(); // must return the same id in both calls
Why don't you use unset? It is the proper way to do it.
Turns out the application I was working on had it's own session_handler and if it was not included before requesting the session data, it was always invalid, eventhough it was the same session_id.

Problems accessing same SESSION variables from different files

I'm developing a site using Wordpress.
My permalink structure is set to show post/page name. So accessing a page called store will look like this: www.mysite.com/store/?some=arguments
In all my WP templates, I'm able to output all my SESSION variables using print_r($_SESSION);
Doing the same from a file called from jQuery.ajax only outputs some of the SESSION varaibles.
I've used the following code to see if the cookie path is same for both files, and they are:
$sessCookie = ini_get('session.cookie_path');
echo 'session.cookie_path: '.$sessCookie;
I also have this code in my files to make sure session is started:
if (!session_id())
session_start();
Why am I not able to output the same session variables from a WP template and a php file called from jQuery.ajax?
UPDATE
jQuery.ajax calls jquery.php file. At the top of this file, it has the following code:
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-blog-header.php');
This code fires functions.php. In this file I have the following code:
function session_manager() {
if (!session_id())
session_start();
// Get variables in query string
$_SESSION['action'] = (isset($_GET['action']) ? $_GET['action'] : '');
$user_geo_data = get_geoip_record();
$_SESSION['user_geo_location'] = get_object_vars($user_geo_data);
}
When functions.php is fired from jquery.php, it seems that session_id() returns false, thus I create a new session.
Is there a way to keep using the same session?
UPDATE 2
It seems that WP config kills all GLOBAL variables when initialized.
http://wordpress.org/support/topic/wp-blog-headerphp-killing-sessions
Wordpress can use its own session handler, and overrides the default session handler to do so. So in essence you've got two different sessions, even though they share the same ID. The cookie path is merely how the client-side cookie operates. What you need to check is session_save_path(), and check if WP is running sessions through the database instead of the default file handler.
The reason two sessions are fired up is because the first one is browser-based (through a cookie) and the second one, with Ajax, is essentially server-side and doesn't have access to the session cookie.
The session cookie is where the session ID is stored and is used to identify an existing session. A server-side Ajax script doesn't have access to the browser's cookies, thus fires up a new session.
It can be worse if the main script uses an alternate session "save handler" than the Ajax script, resulting in two separate sessions, stored in two different places.

Why can't I access session variables from my AJAX-called PHP script?

I have one PHP script with a session variable, set like so:
$_SESSION['VAR1'] = "test"
Now, I am using AJAX via a jQuery-initiated POST request, and so I have a script named ajax.php which has all the required functions.
And when I try access my session variable (echo $_SESSION['VAR1']) in ajax.php, it produces nothing.
Does session does not work from AJAX requests?
You need do this on every page that accesses the session before you access it:
session_start();
That means on both the page that sets the session variable and the AJAX page that tries to retrieve it. Both need to call session_start().
As long as the AJAX request calls a script in the same domain (and thus gets access to the session cookie) there is no reason why it couldn't get access to the session variables. An AJAX request after all is just another HTTP request.
Make sure that the domain names for both pages (i.e. the AJAX container and the AJAX script are same). Here is an example:
http://mydomain.com/login.php (set session variables here)
http://mydomain.com/ajax-container.php (session variables are visible here)
http://mydomain.com/ajax-script.php (session variables are visible here)
http://www.mydomain.com/ajax-script.php (session variables are NOT visible here)
Another one:
http://www.mydomain.com/login.php (set session variables here)
http://www.mydomain.com/ajax-container.php (session variables are visible here)
http://www.mydomain.com/ajax-script.php (session variables are visible here)
http://mydomain.com/ajax-script.php (session variables are NOT visible here)
I also caught myself on having one little, tiny, hard to see, space just before "< ? php " This ended up sending information back and disallowing the session to start because header information was already sent. May not be the case for anyone else, but it tripped me up and brought me to this page in search of an answer.
Make sure no content has been echoed (not even a whitespace) before calling session_start().
To be safe, put the code as the first code of whatever template you used for the page. The function will not work if content has been sent to the browser.
To test and see where the problem is, call the page as a stand-alone, instead of through AJAX and ensure that it works before AJAXing it.
An addendum to what Salman A wrote:
If you set a session variable in an https:// file and try to access it with a http:// file you will not be able to...
https://www.example.com/index.php - call session_start() and set session variable
http://ww.example.com/index_tmp.php - unable to access session variable
and vice versa...
http://www.example.com/index.php - call session_start() and set session variable
https://ww.example.com/index_tmp.php - unable to access session variable
Rather:
https://www.example.com/index.php - call session_start() and set session variable
https://ww.example.com/index_tmp.php - Able to access session variable
And:
http://www.example.com/index.php - call session_start() and set session variable
http://ww.example.com/index_tmp.php - Able to access session variable
My own error was BOM character in my ajax file.I was need to use session variable in a ajax called php file.I tried to start session by session_start() but "cannot modify header information" occurs.I removed BOM character and code works very well.
In jQuery or JavaScript, you can get the session value like this:
var StepIndexval = '<%= Session["StepIndex"].ToString() %>';
alert(StepIndexval);

Categories