Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a simple login page and
login.html - gets input username and pwd in form
login_result.php - connect to server and start session & form little form validation
note.php - this is the main page for user to choose other sub pages. so far I only display the user name on the screen to test the session works.
for viewing purpose, I've changed to html. please follow link to see what's wrong...
login_result
note
Your links seem to be of no help. Anyways I will give a little intro as to how to work with basic login and sessions.
login.html: The form which should be in the login.html page. Method MUST be POST as you are passing sensitive information to another page. Also note the names of the input fields.
<form role="form" method="POST" action="login_result.php">
<label for="UID">UserID:</label>
<input class="form-control" type="text" name="UID" required>
<br>
<label for="pwd">Password:</label>
<input class="form-control" type="password" name="pwd" required><br>
<button class="btn btn-default" type="submit">Login</button>
</form>
login_result.php: This is where the validation takes place.
<?php $username = trim($_POST['UID']); //UID is the name of the username input field
$pass = trim($_POST['pwd']); //So is pwd
if(strcmp($username,"admin") === 0 && strcmp($pass,"admin") === 0 )
{
session_start(); //start session
$_SESSION['username'] = $username;
//store userdata for further use.
//My page is simple so it just stores the username
header("Location: note.php"); //redirect to your "success" page
}
else
{
//Wrong credentials
header("Location: login.html");
}?>
The verification is basic here. I usually employ hashing but for now this will do fine
note.php: Reuse the Session variable to display the username like,
<h3>Welcome, <?php echo $_SESSION['username']; ?> </h3>
You must also check for each page if the session is active, and redirect to the login if its not, else there is no meaning to the login.
in_all_pages: Add this at the beginning,
<?php
session_start(); //start the session
if (!isset($_SESSION['username']) || empty($_SESSION['username']))
{
//redirect to the login
header("Location: login.html");
exit();
}
Remember to destroy the session like:
logout.php:
<?php
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
header("Location: login.html");
?>
To use PHP, the files must have .php extension.
Said that, to use the sessions you have to use this code line at the start of every php line:
session_start();
Related
I am a php newbie and practicing with php sessions. Basically, I have a login form which will be shown to a user ONLY if the session does not exist otherwise the page says "User Already Logged In".
I have set the session life time and cookie time using :
session_set_cookie_params(60);
ini_set('session.gc_maxlifetime', 60);
I want the session to be destroyed after 1 minute so that the user will have to log in again. but in my implementation, the session still exists for a long time and the users are logged in.
in my login.php i have:
1: if visited login.php with POST req, then check login credentials
2:if SESSION['logged_in'] is set then do not show the form, echo "already logged in"
<?php
require_once("helpers.php");
session_start();
if(!empty($_POST)){
loginUser($_POST['user_id'], $_POST['pass']);
}
<?php
if(!isset($_SESSION['logged_in'])){
echo "<br>SESSION IS NOT SET UP";
?>
<HTML>
<HEAD>
<LINK rel="stylesheet" type="text/css" href="style.css">
<SCRIPT src="test.js"></SCRIPT>
</HEAD>
<BODY>
<H1>Please login</H1>
<FORM action="login.php" method="post">
<span class=formlabel>Username:</span>
<INPUT name="user_id" type="text" class="forminput" require><BR>
<span class=formlabel>Password:</span>
<INPUT name="pass" type="password" class="forminput" require><BR>
<INPUT type="submit" value="Login" style="width:80px;margin-left:100px;margin-top:3px;"><BR><BR>
Don't have an account? Click here to register.
</FORM>
</BODY>
</HTML>
<?php
}else{
echo '<strong>user already logged in.<br></strong>';
}
?>
Then in my helper.php I have a function:
1: check user id and password in data base
2: if it exists then set a session.
function loginCheck($user_id, $pass){
//here goes code which checks if user_id & pass exists
//store in $RESULT if exists
if(!empty($result)){
session_set_cookie_params(30, '/');
ini_set('session.gc_maxlifetime', 30);
$_SESSION['username'] = $user_id;
$_SESSION['logged_in'] = true;
}
}
Now when ever i log in as a user then the session starts and the login form dissapears, which is the correct behavior that i want. But the session never ends, i mean even if i refresh the page after 10 minutes the form doesn't show up and says "user already logged in".
also:
1: do the sessions gets destroyed by itself after their maxLifetime?
2: if not do we have to destroy it ?
thank you
The gc_maxlifetime value is the number of seconds after which data will be seen as garbage and potentially cleaned up. You'll want to make sure this value is set high enough so that your sessions aren't destroyed too early, but you can't rely on sessions being destroyed after this amount of time.
If you want sessions destroyed after a specific period of time, then you should store a timestamp, and then use that timestamp and the presence of the session to see if the session is still alive. Something like this:
$_SESSION['last_access'] = time();
Then later on, to check if it's still active:
if ( isset( $_SESSION['last_access'] ) && $_SESSION['last_access'] - 60 > time() ) {
// The session is still alive
} else {
// The session should be destroyed
session_destroy();
unset( $_SESSION );
}
Then, your future checks for the presence of any $_SESSION value will work the way you expect.
I would like to maintain 3 $_Session variables after login. My login modal submits to my index.php page and this seems to be the only place I can access the session variables I set when the user logs in. How do I pass these variables to the next page the user visits? I know I can use hidden inputs in forms but what if the brows the site using the menu? I would like to store a users session variables in a session include file but I have the same issue passing the values of the variables from page to page.
-Mike
File a.php:
<?php
session_start();
$_SESSION['saveme'] = 'from file A';
?>
File b.php:
<?php
session_start();
echo $_SESSION['saveme']; // if you visited a.php previously, you will see "from file A"
?>
Setting a session variable in any file makes it available anywhere else.
You can store you values in session on one page(index in your case as you mentioned) then later on you can get those values on any page if session in started on that page. Session store those value till same session alive.
code to set values in session:
<?php
// Start the session
session_start();
?>
<?php
// Set session variables
$_SESSION["xyz"] = "xyz";
$_SESSION["abc"] = "abc";
echo "Session variables are set.";
?>
Code to get session values:
<?php
// Echo session variables that were set on previous page
echo "value of xyz is " . $_SESSION["xyz"] . ".<br>";
echo "value of abc is " . $_SESSION["abc"] . ".";
?>
The form of your modal
<form action="index.php" method="post">
Username <input type="text" name="username" />
Password <input type="password" name="password" />
</form>
Then you catch it in your index.php
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
// Check if user exists and password matches
$_SESSION['username'] = $_POST['username'];
$_SESSION['logintime'] = time();
$_SESSION['something'] = 'else';
}
In any other page you can use the values like
<?php
session_start();
if (isset($_SESSION['username'])) {
echo 'Welcome ' . $_SESSION['username'];
}
All who have provided answers thank you. This overlooked detail was all on me and though I have been out of the dev game for a while I should have known better.
My hosting service by default makes all file permissions read/write only...to access session variables I changed to read/write/execute and was successful.
Again thanks!
I hate to say it but I have been working on what should have been a 30 minute assignment for a good 6 hours now with little to no progress. I am attempting to capture a name and email in a form, and set them to cookies that will last 10 minutes. While the cookies are active, the page should skip the form and just display the input. I have tried this with both cookies and sessions and cannot get it to work.
At this point I have written and deleted at least a hundred lines of code and just can't really see what the problem is. This is my first time working with PHP. Any help would be appreciated.
Currently this code creates the form, takes the info and posts it to the page correctly. When I go back to the page, it shows the form again. I assume this means the cookie isn't setting / sticking.
<?php
if (!empty($_POST)) {
setcookie('Cname',$_POST['name'], time()+600);
setcookie('Cemail', $_POST['email'], time()+600);
// header("Location:HW2.php");
}
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$visibleForm = True;
if(isset($_COOKIE['name'])){
$visibleForm = False;
}
if(isset($_POST['submit'])){
$visibleForm = False;
echo "Your Name: ";
echo $_COOKIE['Cname'];
echo "<br>";
echo "Your Email: ";
echo $_COOKIE['Cemail'];
}
if($visibleForm){ // close php if form is displayed
?>
<form action ="HW2.php" method="post">
Name:<font color = red>*</font> <input type="text" name="name"><br>
E-mail:<font color = red>*</font> <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php // back to php
}
?>
</body>
</html>
I rewrote your script using sessions, so that your data is actually stored on the server and the client only has a session cookie which is a reference to the server-side data, so the client has no way of tampering with that data.
While this may not be important for your homework, this is definitely important when you deal with user accounts and privileges (imagine an "admin" cookie that tells if the user is admin or not - anyone can manually set that cookie and that's it, he's an admin on your website).
This wasn't tested and may not work at all - feel free to downvote my answer if that's the case.
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set("session.cookie_lifetime","600"); // sets the session cookie's lifetime to 10 minutes / 600 seconds
session_start(); // starts the session, this will create a new session cookie on the client if there's not one already
if (isset($_POST["name"]) && isset($_POST["email"])) { // if there's POST data
$_SESSION["name"] = $_POST["name"]; // this saves your values to the session so you can retrieve them later
$_SESSION["email"] = $_POST["email"]; // same here
};
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
$visibleForm = !isset($_SESSION["name"]); // visibleForm will be the opposite of isset, so if there's a "name" in the session then the form will be invisible
if ($visibleForm) { // if there's no session data, we display the form
echo '<form action ="HW2.php" method="post">Name:<font color = red>*</font> <input type="text" name="name"><br>E-mail:<font color = red>*</font> <input type="text" name="email"><br><input type="submit" name="submit" value="Submit"></form>';
} else { // this means there is some data in the session and we display that instead of the form
echo "Your Name: ";
echo $_SESSION["name"];
echo "<br>";
echo "Your Email: ";
echo $_SESSION["email"];
};
?>
</body>
</html>
First of all, you must add the session_start() at the highest level of your code as it is essential for any of this to work. session_start() actually generates the PHPSESSID cookie and is also the session identifier; you won't need to set anything to the PHPSESSID cookie using setcookie() if you use session_start().
For a basic way to do what you're trying to achieve, I'd try to set sessions whenever the page loads and if there is a current session, then it will skip the form like you said.
$_SESSION['SESSID'] = $someVar;
$_SESSION['SESSNAME'] = "someOtherVar";
Then right before your form, check if any of those are set by using
if(isset($someVar) && isset($someOtherVar))
You know the deal.
Then create a button that does a session_destroy() so that it ends the current session.
The php code below is login_successful.php which is obtained after user logs in, in this page i want to display his 'username' and a logout link
<html>
<head>
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:home.html");
}
?>
</head>
<body>
Welcome $myusername //here i want to display logged in user's name
Login Successful
</body>
</html>
how should i put logout link in this page without using another logout.php file.
Why use another page for logout? Do it like this
<?php
if(isset($_POST['logout'])) {
//Unset cookies and other things you want to
session_destroy();
header('Location: login.php'); //Dont forget to redirect
exit;
}
?>
<form method="POST">
<input type="submit" name="logout" />
</form>
You have to check wheter session has his username and then display, something like:
session_start();
if(isset($_SESSION['username'])){
echo "Hello, " . $_SESSION['username']);
echo "Logout"
}
You can always call session_destroy() to (guess what) destroy your sessions! From the manual:
session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.
More important than use session_destroy() is to make sure you reseted the cookie (if any used) by setting it's time one hour back: time() - 3600, like:
setcookie ("YourCookieName", "", time() - 3600);
How do I pass information between PHP pages?
For example, I have a PHP script to process login input from a form, and then a separate PHP script to process further input for the user. However, I want the second PHP file to receive the input from the login form. In essence, I do not want the same script being run twice for the login.
You are looking for POST and GET variables, it's done in the method parameter of your HTML form:
login.php
<form name="myform" action="secondpage.php" method="post">
<div>Username: <input type="text" name="username" value="" /></div>
<div>Password: <input type="password" name="password" value="" /></div>
</form>
Then in this other page:
secondpage.php
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
if ($username != '') {
// do your validations here
}
Explanation
When you use the GET method, the parameters are visible in the URL, so let's say we change the method="GET" in login.php, you'll end up with something like secondpage.php?username=jsmith&password=1234. And then you could get the values using $_GET['username'].
Using POST makes it possible to send larger quantity of data (there is a vague limit to the size of a URL) and it's not visible in the URL. You should note though that it's still sent in clear text, so it does not means it's secure.
POST and GET were made for different purposes. GET should be use to extract information that you could want to extract again in the future, information that is not special to this very instant. It's useful to have mypage.php?product=123 because you'll potentially want to send this URL to a friend. A POST should be used when you'll modify the state of data: updating a product, creating a new user, deleting an article and so on. It's something you want to happen once.
Structure
In conclusion, I just want to add that normally you wouldn't necessarily want to use another PHP script just to avoid some code to run or not. So without knowing the specifics of your project, I can nevertheless say that you would probably want to do something like that to benefit from the same code (such as the form's HTML).
Please note it's simplified code.
login.php
<?php
$error = false;
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
// if, and only if something was posted... so not on first display
if ($username != '') {
// do your validations here
if ($properlyLogged) {
session_start();
$_SESSION['loggedAt'] = time();
header('Location: http://localhost/secondpage.php');
exit();
} else {
$error = true;
}
}
?>
<?php if($error): ?>Login failed. Please try again.<?php endif; ?>
<form name="myform" action="login.php" method="post">
<div>Username: <input type="text" name="username" value="<?php echo($username) ?>" /></div>
<div>Password: <input type="password" name="password" value="" /></div>
</form>
secondpage.php
<?php
session_start();
if (!isset($_SESSION['loggedAt'])) {
// if not properly logged in, return user to login
header('Location: http://localhost/login.php');
exit();
}
?>
You are now logged in!
Hope that's what you were looking for!
You can pass information between pages using GET or POST methods. GET would append the information you wish to pass as a querystring on the url such as:
loginprocess.php?id=JSmith&pword=HelloThere (this isn't exactly recommended for private information)
The other method is to send the information via POST so that it is hidden from the querystring.
More examples can be seen here: http://www.tizag.com/phpT/postget.php
If the data isn't that large you could redirect the user to the 2nd page with the data passed via the URL (GET variables). Otherwise, just run the seconds method in the same page, and use a function to do the final parsing of the data which can be included as the above user suggests.
Just a small extra to what was written before: the limit on the GET (parametrize URL) is a full URL, which means 1024 characters. If you need more than that, you have to use post.
You can take advantage of PHP sessions to share data amongst your PHP scripts. Basic example below, read more here.
login.php:
<?php
// initializes the session //
session_start();
// save user name and password to session //
$_SESSION["username"] = 'someuser';
$_SESSION["password"] = 'somepassword';
$_sESSION["valid"] = true;
?>
secondpage.php:
<?php
// start session handler //
session_start();
// check for a valid session //
if (!isset($_SESSION["valid"])) header("Location: login.php\n\n");
// continue page code here //
?>