Page 1 of 1

Session variable help

Posted: Mon Aug 22, 2005 12:42 pm
by mickyc1
hi i want to take the persons username and assign it to a session variable so that on the welcome screen says something like "welcome 'username'" etc. its probably easy, but im new to php so go easy on me :!:

Posted: Mon Aug 22, 2005 12:44 pm
by feyd
basics:

Code: Select all

<?php

session_start();

$_SESSION['username'] = 'larry';

?>
<html>
 <body>
  Welcome <?php echo $_SESSION['username']; ?>.
 </body>
</html>

Posted: Mon Aug 22, 2005 12:45 pm
by John Cartwright

Code: Select all

session_start();
$_SESSION['username'] = 'Jcart';
session_start(); has to be on line 1 of your script, or atleast before ANY output. Now this will assign your session variable to 'Jcart'. Now to access this variable on any other page you must have session_start(); before any output, and then simply echo $_SESSION['username'];

Posted: Mon Aug 22, 2005 12:46 pm
by mickyc1
cheers. how do i get the info from the users input in the username field :?:

Posted: Mon Aug 22, 2005 12:49 pm
by John Cartwright
That all depends? Do they login in through a form?

If that is the case when they submit the form simply have a $_SESSION['username'] = $_POST['username'];
that is of course assuming username is the field name. You might want to look into validating the input fields aswell.

Posted: Mon Aug 22, 2005 12:49 pm
by feyd
most basic form (unsecure)

Code: Select all

<?php

session_start();
$_SESSION['username'] = $_POST['username'];

?>

Posted: Mon Aug 22, 2005 1:26 pm
by pilau
Why is it unsecure?
And what can you do to secure it?

Posted: Mon Aug 22, 2005 1:29 pm
by feyd
inherant security in trusting anything from an outside source is low, typically. Granted, this example is less benign, but still has potential exploitation factors.

For instance, with the code as I wrote the example, if someone sent HTML along with it, that html would be sent to the user viewing it. Which could potentially do various things, such as give out information about the internals of the server, or execute some Javascript..

Posted: Mon Aug 22, 2005 3:03 pm
by pilau
And what can you do to secure it?

Posted: Mon Aug 22, 2005 3:29 pm
by feyd
validate, filter, and/or translate the information into something valid or puke it back at the user with an error... The security board is a good place to read up on how these things are done.