I have a simple file to set a session variable
<?php
session_start();
$_SESSION['my_name'] = "dave";
?>
and a simple file to see the stored variable
<?php
session_start();
echo $_SESSION['my_name'];
?>
if I call the file in the browser the session value is displayed correctly but if I make a ajax call using for example using http://requestmaker.com/ or https://www.hurl.it/ then the body response is blank. I can't see what is going wrong here its driving me nuts.
Any ideas
Cheers
Dave
You're trying to watch $_SESSION['user_name'] variable when you saved the $_SESSION['my_name']. variable
Correct one of the identifiers.
Its inappropriate to use third party http-request sites and still expect the session variables to be valid since the request is then coming from a different domain to your server.
Related
I’m pretty much a complete beginner when it comes to PHP and have been having some problems with displaying a Welcome Username message on a HTML page and where to place session_start(); on the page.
Here’s the relevant part of the HTML page: can one place PHP directly into the page like this?
<div class="col-sm-4">
<h2><p>Welcome, <?php echo $_SESSION['Username']; ?>.</p></h2>
Right at the top of the page (before the HTML) I’ve also put:
<?php
session_start();
?>
<!doctype html>
(is this session start in the right place?)
Not sure if I’m going about this in the right way though :/
Thank you very much for your time; very much appreciate it as well as other helpful replies here.
EDIT Everything works once I changed the pages extension to PHP rather than HTML
can one place PHP directly into the page like this?
Yes. Gathered you use the <?php ?> tags, like you did, and the file has the .php extension; you can.
(is this session start in the right place?)
Also correct.
You haven't said what error you're receiving but I'm assuming you'll have a undefined index 'Username' error (if you don't, turn ON php error reporting and you'll probably see it) this happens because, unless you set the value previously, your 'Username' index inside the $_SESSION array was not defined by $_SESSION['Username'] = "Mosh Mage"
Hope this helps :)
Your code is correct but never forget to store the user name to $_SESSION['username'] or else your it will echo nothing. Before you can store user information in your PHP session, you must first start up the session.
Note: The session_start() function must appear BEFORE the html tag: in your case correct as well.
School yourself with sessions at http://www.w3schools.com/php/php_sessions.asp
I'm desperately trying to pass a variable between browser windows. I have a php page (test.php) which opens another page (another.php) in new window. I also have some variable that needs to be encrypted/decrypted and passed WITH encryption password. I've created a session like this:
session_start();
$_SESSION['test'] = array(
'var1' => $encryption_password,
'var2' => $some_encrypted_stuff
);
But of course in new window 'test' session is NULL. I've tried different options, but all failed. I do can create a file and write data there, but this doesn't seem secure to me.
Can anybody give me a working example for this issue? Can't find anything by myself.
UPDATE
OK, my main task is to encrypt variable in one php file and decrypt in another. There's one condition tho: encryption password can NOT be read from initial storing place by 2nd php file - only by the the 1st one.
As far as I'm concerned, writing it to a file is probably NOT a good approach. You're trying to achieve a variable retrieval, and nothing more.
I'm not sure why your test variable is null. I just tried making this test myself and I could access everything just fine.
Your code that you provided SHOULD be writing the data to the session variable. First, be sure you're not killing the session somewhere later in that first script. Second, double and triple check your code to access the session variable. Without seeing your code it's hard to tell, but on the second page my only guess is that you're either misspelling the access to the variable, or you're forgetting to start the session again!
Here is the code for both of my files:
First page:
<?
session_start();
$_SESSION['test'] = array('var1' => "somevalue", 'var2' => "someothervalue");
?>
<a href='other.php'>Go</a>
Second page:
<?
session_start();
var_dump($_SESSION['test']);
?>
That works fine for me- I get the full session variable spat back out. Give it a shot and let us know if you're still having issues (with more of your code so we can better understand whats up). Good luck!
I'm writing a php code processing a lot of data, sometimes interactively. In my starting php page i call the function session_start() before sending any other data to the browser. Then, i put some data into the $_SESSION[] array, like this:
$_SESSION['something'] = $variable;
After, there is a form, what is sent via GET and XMLHttpRequest.
getrequest.open("GET", "data_processing.php?var="+onevalue+"&another_var="+twovalue, true)
getrequest.send(null)
Another php script recieves the user data from this GET, and there i'd like to use the data stored in $_SESSION as well. But $_SESSION seems to be empty. I've never used sessions, what is the correct way to make available variables to consequent php scripts?
Are you sure you called session_start first?
See: http://php.net/manual/en/function.session-start.php
I finally found the solution: another script still used the session, so i had to insert session_write_close(); then it works fine. Thank you for all the answers!
I think I forgetting something in my code but can't find what.
On my server I have simple logging.php file.
If I pass user/password parameters then a new session is created.
If I pass loggout the session is destroyed.
If I pass report the list of current session variables are reported on screen.
If I test the code writing urls in my browser all works fine. First invoke .../logging.php?user=xxx&password=xxx. The session is started and the session variables are reported to me. And finally I destroy the session passing the logout parameter.
If user request a report or a logout and no session exists a HTTP-401 error code is returned to client.
On the other hand I have a piece of JavaScript code that I can inject on web page using a bookmarklet. Once code is injected I show a toolbar where user can write user/password and send to server.
The logging actions seems to works fine, and server returns me a 200 status code, but later if I make a request to logout the server returns me a 401 error, which mean no session exists.
I was using chrome and looking at HTTP request and responses can see that when I logging the server returns in the response different values for PHPSESSIONID.
That means two different AJAX request are considered different sessions. The server seems to not recognize the second request from AJAX as if it was started by the same client.
Repeat, the PHP code works fine if I execute using browser directly but not with AJAX request, so I think I forgetting something in AJAX.
Any ideas?
Thanks in advance.
Update
To be more concise, my problem is calling php from JavaScript. It seems there are no sessions started.
Imagine a very simple PHP code:
logging.php: given a user/password starts a new session and also stores 'user' names as a session variable.
request.php: which returns the user name stored as session variable.
logout.php: which destroys the session.
My first AJAX request start a PHP session. That seems fine because a PHPSESSIONID cookie is returned from server. Also I store the user name as session variable.
The second AJAX request tries to get the user name (stored in the session) but it gets nothing and in addition a new PHPSESSIONID cookie is returned from server.
I know it seems impossible and more when I'm testing using browser url request and works fine, but it's the truth.
I'm forgetting something on AJAX, expiration times or something similar?
Update again
I made some tests and I found the problem but not the solution.
My JS code is injected through a bookmarklet.
When I inject the code in a HTML page from my server, the AJAX requests works fine. The first (logging) request gets a PHPSESSID which is passed in subsequent request to the server.
On the other hand If I load google.com and inject the code, the first (logging) request gets the PHPSESSID too but later it is not sent with next requests.
Anyone has experienced the same issue? which is the problem?
Thanks in advance.
Update again, again
Ok finally I found my problem. Because my JS is injected from a different domain (current page is from domainA and my JS code comes from domainB) cookies are not cross domain, so PHPSESSID can be shared.
A possible soulution is when I logging I will return the PHP session ID in pice of JSON data and use it for subsequent calls.
If I'm correct, you're trying to log in a user by making an AJAX request to a URL, with the username and password provided in the URL? That's not really a safe construction, the password is very vulnerable this way?!
I would advice you to implement jQuery, and transer the login details using the $.POST command:
http://api.jquery.com/jQuery.post/
Make sure all your files (also those requested by AJAX) contain session_start(); on top of the file.
When every file contains session_start(); and you're using the same $_SESSION variables to check if a user is loggedin, it should work!
Are both of your AJAX requests coming from the same page? The requests are Asynchronous, so it may be that the "logged in?" request is returning its result before the "log in" request goes through.
From what you have asked, I hope your code is (at its beginning more or less) something like:
A file logging.php like this:
<?php # file : loggging.php
if(!ini_set('session.auto_start'))
// more stuff
if(!empty($_REQUEST['user']) && !empty($_REQUEST['passwd'])) {
session_regenerate_sid(); // This is important (1)
$_SESSION['user'] = $_REQUEST['user'];
// Whatever
}
A file request.php like this..
<?php # file : request.php
if(!ini_set('session.auto_start'))
// Whatever stuff to process data
var_dump($_SESSION);
// Or a nice foreach($v as $i => $x) {
// echo("[$i] => $x\n<br />");
// } instead :)
And your logout.php should read something like..
<?php # file : logout.php
if(!ini_set('session.auto_start')) session_start();
session_destroy();
You are probably not calling either session_start() or you are calling it twice.
To check this out try this: change all your session_start() lines for:
session_name('MYCoolNewName');
session_start();
Now your session should not read PHPSESSID, instead it should be MYCoolNewName.
If it is not, then your problem is the aforementioned.
(1) I put as important session_regenerate_sid() because opened authenticated sessions are a threat out there. I'll demonstrate it with an example.
Alice visits coolwebsite.com/login.php, which gives her a SID which I'll call AliceSID.
Alice tells Bob to visit coolwebsite.com/login.php?PHPSESSID=AliceSID, and when Bob does Alice could log in his account unless Bob's session was regenerated.
I'm trying to use the header() function to create a redirect. I would like to display an error message. Currently I'm sending the message as a parameter through the URL, however this makes it look quite ugly.
Is there a way to pass this value as a post variable instead?
Any advice appreciated.
Thanks.
Dan, You could start and store a session in PHP then save the message as a session variable. This saves you from having to transfer the message in an HTTP request.
Manipulating Sessions
//Start the session
session_start();
//Dump your POST variables
$_SESSION['POST'] = $_POST;
//Redirect the user to the next page
header("Location: bar.php");
Now, within bar.php you can access those POST variables by re-initiating the session.
//Start the session
session_start();
//Access your POST variables
$temp = $_SESSION['POST'];
//Unset the useless session variable
unset($_SESSION['POST']);
To read more about sessions, check out: http://php.net/manual/en/function.session-start.php
The header function is used to send HTTP response headers back to the user so actually you cannot use it to create request headers :(
One possibility is to use the CURL but I don't think it is worth of what you are doing.
Provided that you have local access to the page displaying the error, instead of redirecting you could include it in the page which caused the error and then programmatically display the error message.
if(something_went_wrong()) {
require_once('errors.php');
display_error('something really went wrong.');
}
The errors.php file would then contain a definition for display_error($message), which displays the formatted message.
When passing variables between modules I have found it easier to construct an array from the variables, convert the array to json and store it in a db table with two columns, a varchar key and a text data. The json would go in data and the key could be anything you want. Then in the target module you just read that back, convert the json back to an array and voila, you have your variables. No $_POST, no $_SESSION, no fuss, no muss, quick and easy. Of course that assumes you have access to a database, although you could use a file on the server. $_POST is useless since it needs a and $_SESSION can be cranky and can lead to unexpected results. Otherwise you'd almost have to use ajax.