PHP cookies setting - php

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.

Related

php session not being deleted after setting its lifetime

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.

Session array resets on submit?

I have test.php:
<html>
<?php
if (!isset($_SESSION))
{
echo 'session is not yet set';
session_start();
$_SESSION['comments'] = array();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
<input type="text" name="comment">
Click the button!
<input type="submit"/>
</form>
<?php
array_push($_SESSION['comments'], $_GET['comment']);
echo 'Current array count: ' . count($_SESSION['comments']) . '<br>';
foreach($_SESSION['comments'] as $comm)
{
echo $comm.'<br>';
}
?>
</html>
What should happen is that any text entered in the textbox should be pushed to the session array, but every time I click on submit, what is printed is the text I just entered instead of appending/storing the previous entries. I only get 1 as the array count all the time.
Every time I hit submit, session is not yet set always shows at the top of the page even when I have the if condition.
I can't seem to find what's wrong?
You need to do this:
<?php
session_start();
if (!isset($_SESSION))
{
?>
Otherwise you have header output from the HTML tag and the session can't start properly.
You should start the session at the top of the page always.
session_start(); //start the session
Then we can check session is exist or not.
if(!isset($_SESSION['user'])){
// your code
}else{
// your code
}
session_start() does not just start a NEW session. If the client already has a session it resumes that session. PHP Manual
If you are using sessions, just have session_start(); at the top of the page and PHP will do the lifting of starting or resuming a session.

Maintaining PHP Session Variables

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!

Possible to manipulate $_POST variable in php script and express it in another php script?

I've been trying to do form validation without using the url. So I thought that I would create a hidden field in my form and send it over to my validation php script. What I was hoping I would be able to do is set what ever errors there are in the form to this hidden field and return it. However once I get out of the scope it destroys whatever I set. I thought $_POST had global scope? Maybe I declared I set the hidden field wrong? I have placed the code below.
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/databaseConnect.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/functions.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/users.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/userDetails.php';
//get the refering url to be used to redirect
$refUrl = $_SERVER['HTTP_REFERER'];
if(isset($_POST['register'])){
//declare a temp error array
$tempError;
//check if the form is empty
if(empty($_POST['Email'])&&empty($_POST['Email Confirmation'])&&empty($_POST['Password'])&&empty($_POST['Password Confirmation'])
&&empty($_POST['Stage Name'])&&empty($_POST['Main Club'])){
$tempError = 'Please fill in the form.';
}else{
//set variables
}
if(!empty($tempError)){
//start a session to declare session errors
$_POST['errors'] = $tempError;
//redirect back to referring url
header('Location:'.$refUrl);
exit();
}else{
//log user in and redirect to member home page
}
}
Basic form (I excluded the input field as it would be really long)
<div class="col-md-6 well">
<span class="jsError"></span><?php if(isset($_POST['errors'])){ $errors = $_POST['errors']; } if(!empty($errors)){ echo '<p class="alert alert-danger text-center">'.$errors.'</p>'; } ?>
<form class="form-horizontal" role="form" method="post" action="controllers/registrationController.php" id="registration">
<input type="hidden" name="errors" value="<?php if(isset($_POST['errors'])){echo $_POST['errors']; } ?>">
</form>
I looked into using the $_SESSION variable method too but the stuff I found was either a bit complicated or it involved me starting a whole bunch of sessions everywhere (would make my code messy in my opinion).
$_POST is populated from the contents of the data passed by the browser to the server. When you send a Location header it causes the browser to load a new page, but since it will have no form data, nothing will be passed.
If you need to pass data from page to page then $_SESSION is the way to go. All that is required is a session_start() at the top of the pages that need access, and you can store your $_POST data like this:
$_SESSION['postdata'] = $_POST;
Retrieving it becomes
$email = $_SESSION['post']['Email'];
The alternative is to echo the data as a hidden <input> in a new form, but that will require a new form to be submitted and I get the feeling you want something seamless.
Note also that $_SERVER['HTTP_REFERER'] is not guaranteed to be accurate, or even present. You shouldn't rely on this for production code. It might work for you with your browser in your test set-up, but that's no guarantee it'll work for other browsers. Find another way.
You can achieve this by using javascript instead of a redirect, but the only way to pass data through a redirect is via the URL, the session, or cookies.
$_POST['errors'] = $tempError;
//redirect back to referring url
?>
<html><head><title></title></head><body>
<form id="temp_form">
<?php
foreach($_POST as $k=>$v) {
?><input type="hidden" name="<?php echo htmlentities($k); ?>" value="<?php echo htmlentities($v); ?>" /><?php
}
?>
</form>
<script type="text/javascript">
setTimeout(function() { document.getElementById('temp_form').submit(); },100);
</script>
</body>
</html>
<?php
die();

Can't store session data between pages

I have faced a problem in all of my php projects is that since i used OOP is that if there is a user submitting a form
when it goes to processing it and if it has an error i save a message in the session and redirect them to the same page
this is a sample and of course when it redirects it wipes all the fields that was there
like let's say i have a register form that had
<?php if(!empty($message)) { echo $message } ?>
<form action ="forms/register.php">
first name: <input type="text" name="first_name" />
username:<input type="text" name="username" />
<input type="submit" value = "submit" />
</form>
and this is what the code in forms/register.php
if(isset($_POST['submit'])) {
$first_name = $_POST['first_name'];
$username = $_POST['username'];
if(empty($first_name) || empty($username) {
$session -> message("please fill in all the fields");
redirect("../register.php");
} else {
// do something else like insert query
}
}
my problem is if first_name or user_name is empty and it redirects to register.php
and it echos the error message no problem in that
but the fields are empty the first_name and the user_name are empty
so the user has to fill it all again
so one of my friends suggested to save it in the session or something
so i would like to know if that is possible then how and what i mean by how so nobody would get it wrong, i mean the way not the code to just copy it and paste it
Thanks in advance
and sorry for being long and annoying
You can store whatever values you want to keep persisted in the form after the page redirects in session variables, then retrieve those values on the form page and echo them in the value attribute of the form elements.
session_start(); $_SESSION['nick'] = $_GET['nick'];
more / better examples:
http://php.net/manual/en/function.session-start.php
Not sure what issue you exactly are facing (also what $session is inside your workflow?).
However, i recommend using PHP inbuild session support.
http://php.net/manual/en/features.sessions.php
From the above link itself:
<?php
session_start();
if(isset($_SESSION['views']))
{
$_SESSION['views']=$_SESSION['views']+1;
}
else
{
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
}
?>
Above code simply keeps track of page views. $_SESSION variable persists between page loads and you should be using the same for all your session requirements.

Categories