setCookie in PHP script - php

I am working with a simple PHP script that I want to set a cookie on. I do not want this page to refresh. Currently, the page is where I go to upload pictures, and the page refreshes when the upload is done causing the upload to never go through.
<?php $password = "basicadminpassword";
setcookie('password', $password, time()+60*60*24*365, '/', '.myurl.com'); ?>
<?php
// If password is valid let the user get access
if (isset($_POST["password"]) && ($_POST["password"]=="$password")) {
?>
PROTECTED DATA
<?php } else { ?>
<div align="center">
You must have a password to upload pictures.<br /><br />
<form method="post">
<input name="password" placeholder="ADMIN PASSWORD..." type="password" size="25" maxlength="15"><input style="display:none;" value="go" type="submit">
</div>
</form>
<?php } ?>
After the user types in basicadminpassword we wont be asked for it again which will stop the refreshes from happening. If you know of a better way that would be great to hear also!

I don't know what you're doing but you shouldn't save your password plain in a cookie. For security reasons that not a really good idea. Compare the password and save in a session weather the user is logged in or not.
session_start();
$_SESSION['loggedOn'] = true;

Related

Make a form sticky with php session

I am trying to create php multipage forms, and I use PHP sessions for this purpose.
However, when there is an error in user input and I want the form to ask user to fill in the form again with correct inputs, the forms field will not hold the data that the user has already put in so the user has to start things all over again.
How to make forms sticky with php session?
Thanks
My code is as bellow
<?php
// Session starts here.
if (!isset($_SESSION)) session_start();
?>
<form action="registration.php" method="post">
<center><h8>Please create your user name and password</h8></center>
<div class="imgcontainer">
<img src="phone.gif" alt="Welcome" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required value="<?php if(isset($_POST['username'])) echo $_POST['username'];?>">
<label><b>Password</b></label>
<input type="Password" placeholder="Enter Password" name="password" required>
<label><b>Confirm Password</b></label>
<input type="Password" placeholder="Confirm Password" name="confirm" required>
<span id="error" width=100%>
<!---- Initializing Session for errors --->
<?php
if (!empty($_SESSION['error'])) {
echo "<error>".$_SESSION['error']."</error>";
unset($_SESSION['error']);
}
if (isset($_POST['username'])){
$_SESSION['username'] = $_POST['username'];
echo $_SESSION['username'];
echo $_POST['username'];
}
?>
</span>
<br>
<input type="reset" value="Reset" />
<input type="submit" value="Next" />
</div>
and the registration php contains
<?php
if (!isset($_SESSION)) session_start();
// Checking first page values for empty,If it finds any blank field then redirected to first page.
if (isset($_POST['username']))
{
if (($_POST['password']) === ($_POST['confirm']))
{
foreach ($_POST as $key => $value)
{
$_SESSION['post'][$key] = $value;
}
}
else
{
$_SESSION['error'] = "Password does not match with Confirm Password.";
if (isset($_POST['username'])){
$_SESSION['username'] = $_POST['username'];
echo $_SESSION['username'];
echo $_POST['username'];
}
header("location: createlogin.php"); //redirecting to first page
}
}
Something like this:
<input name="var" value="<?= isset($_SESSION['var']) ? $_SESSION['var'] : null ?>" />
Try the other way around. Linking the form-action to the current page, and if all fields are valid; redirect it to the next page (registration.php). This way you'd still have all the post-data, you can process everything that needs to be saved in the session- and you can redirect after all of the logic is done.
My two cent would be keep the same page to validate the content and for the form.
You can include other PHP files from a single page depending on if the form is valid.
This way, you keep the same $_POST between both pages and don't need to store the posted data in a session variable.
Otherwise, if you want to keep the same architecture, you need to use the $_SESSION variables instead of the $_POST ones in your input value, such as the answer by delboy.
Replace:
<?php if(isset($_POST['username'])) echo $_POST['username'];?>
With:
<?php if(isset($_SESSION['username'])) echo htmlspecialchars($_SESSION['username']); ?>
^ Note: htmlspecialchars is used to prevent a reflected XSS if the users enters " as username.
The problem is, your data posted to registration.php, so you can't get the posted value in your original file. You are trying to use $SESSION but that's not recommended, and not right. Your whole solution is wrong.
Forget about session and separated files, put everything to registration.php file together.
You can check if user posted or not with $_SERVER['REQUEST_METHOD'] variable.
if($_SERVER['REQUEST_METHOD'] == 'POST'){
print 'Something just posted';
}
PS: Don't forget secure the password before you store it! :)

How to make the website remember login, in order to prefill a input field? (PHP, MySQL)

EDIT: Problem fixed. I appreciate the replies I got, both for their help and the rapid response they was. The two answers I got was both rather identical, but I chose one of them to mark it as solved.
I have, for some time tried to get this to work but I can't and thus I am coming here, hoping for help.
I am currently trying to create a login, register and comment function on my website. Registering is working, logging in with those credentials also work, and I have got a filter to prevent empty-field entries.
Once I log in I have it echo out the possibility to go to the comment page, and my plan there is to allow the users to write a comment, see the comments below, and the author name will be grabbed from their login username. See where I am going? That is exactly what's not working, though. I can't get it to grab the username from the login field, and I am quite sure it has something to do with that the website doesn't remember the login, and I'm unsure how to set cookies and such if thats where the fix would be.
So, TL;DR - How do I get the website to remember a login, then insert it into a field?
Above the code is the website design itself, connection with the database, and session_start();.
Login.php code
<?php
if(!isset($_POST['submit_login'])) {
// Checks whether anyone have clicked the submit button, as long as they don't, show the form
echo '
<div class="loginform">
<h2>Please login to continue</h2>
<br />
<form action="login.php" method="POST">
Username : <input type="text" name="username_login"><br />
Password : <input type="password" name="password_login"><br />
<br />
<input type="submit" name="submit_login" value="Submit">
</form>
</div>
';
}
if(isset($_POST['submit_login'])) {
// Checks whether they have clicked on the submit button or not, if they have, check if the fields are filled or empty, as well as check it with the database.
$username_login = $_POST['username_login'];
$password_login = $_POST['password_login'];
$loginCmd = "SELECT * FROM tblUsers WHERE username='$username_login' AND password='$password_login'";
$result = mysql_query($loginCmd);
if(empty($username_login)) {
echo "<center>Wrong username.</center>";
}
else if (empty($password_login)) {
echo "<center>Wrong password.</center>";
}
else if (mysql_num_rows($result) == 0) {
echo "<center>User does not exist.</center>";
}
else {
mysql_query($loginCmd);
echo '<center>Logged in. Welcome '.$username_login.' !</center> <br />';
echo '<center>View/post comments here</center>';
}
Comments.php code
<div class="commentform">
<h2>View and post comments and thoughts here!</h2>
<p>All fields required</p><br /><br />
<form action="comments.php" method="POST">
Author : <input readonly type="text" name="author" value=''> <br /><br />
Comment : <textarea name="comment" class="insertcomment"></textarea><br />
<br />
<input type="submit" name="submit" value="Submit">
</form>
</div>
<br />
<hr>
<br />
<?php
if(isset($_POST['submit'])) {
// Checks if they have clicked on the submit button, if they have, send it to the database
$comment = $_POST['comment'];
$author = $_POST['author'];
$insertComment = "INSERT INTO tblComments(comments, author) VALUES ('$comment', '$author')";
if(empty($comment)) {
echo "<center>No text found in comment field.</center>";
}
else if(mysql_query($insertComment) ) {
echo "<center>Comment posted</center>";
}
}
Once you validate the login then you can store the username in a session array which is persistent between pages :
<?php
// this goes on top of the php page where ever you want to use session variable
session_start();
//once user login is valid then you can store username like this
$_SESSION["username"]=$username; //$username is what you used while validating the login
?>
On some other page you can get this value back as long as you have session_start on top:
<?php
//2 nd page
session_start();
echo $_SESSION["username"];//This will print username which you stored while logging
?>
For more information on sessions visit w3schools or php.net
You have two options to store the username between pages: Cookies, which are stored on the user's computer, or sessions, which are stored on your server. Consider sessions for any security-based authentication as cookies can be easily manipulated by your users.
Cookies:
$expiry_time = time() + 604800; // Expire in 7 days (time is in seconds)
setcookie("username", "administrator", $expiry_time); // set the cookie
echo $_COOKIE["username"]; // read the cookie
Sessions:
session_start();
$_SESSION["username"] = "administrator"; // set the session variable
echo $_SESSION["username"]; // read the session variable

How do I set whether a form redirects to a new page or not?

So I'm trying to create a simple log in page with php and html. It's pretty simple. First, a user inputs their username and their password, then clicks the submit button.
If the username/password combo is invalid, "Invalid log in." is printed, and the user is redirected back to the log in page.
If the username/password combo is valid, "Logging you in..." is printed, and the user is redirected to another page. All POST data must be kept when redirecting.
I can't figure out how to change the form's action.
Code snippet below. Please look past potential SQL injections. I will deal with them later.
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" id="form">
User Name:<input type="text" name="userName" id="userName">
Password:<input type="password" name="password" id="password">
<input type="submit" name="submit" id="submit" value="Submit">
<input type="reset" name="reset" id="reset" value="Reset">
<?php
$username = $_POST['userName'];
$password = $_POST['password'];
//(omitted) function that checks whether the credentials are valid or not
if (password_verify($password, $hash)) {
echo "Logging you in...";
//TODO: function that redirects user to another page
}
else {
echo "Invalid log in.";
}
?>
You can do this with the header function and choose where to redirect.
Per other's suggestion, nothing should be echoed before calling header. We can check if the current request is a POST or a GET. For POST, we can do authentication, and for GET, we output the form. We can use the $_SESSION variable to check if we are redirected from a successful or failed login attempt.
<?php
session_start();
if (isset($_POST['userName'])) {
$username = $_POST['userName'];
$password = $_POST['password'];
if (password_verify($password, $hash)) {
$_SESSION['login_success'] = true;
header('Location: user.php?login_success=1');
} else {
$_SESSION['login_success'] = false;
header('Location: index.php');
}
}
if (isset($_SESSION['login_success']) && !$_SESSION['login_success']) {
echo "Invalid log in.";
unset($_SESSION['login_success']);
}
?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" id="form">
User Name:<input type="text" name="userName" id="userName">
Password:<input type="password" name="password" id="password">
<input type="submit" name="submit" id="submit" value="Submit">
<input type="reset" name="reset" id="reset" value="Reset">
In user.php, we can check the $_SESSION variable as well.
<?php
session_start();
if (isset($_SESSION['login_success']) && $_SESSION['login_success']) {
echo "Successful login.";
unset($_SESSION['login_success'])
}
As I understand it, you want to first show the text and then redirect. Your flow is as follows:
user enters credentials,
user gets confirmation of process,
user gets logged in
This way, the server will handle 3 requests (send credential form screen, send confirmation of process screen, send logged in/index). I don't see why you would need to show he is logging in. From a UX perspective, the user will know he is logging in (he filled in the form and pressed the button) and it could break his experience as the screen may flash content, confirming log-ins is non-standard. Also, people don't like waiting. So you could skip that and use User3678068's code.
If you really want to use this flow. You could use a Javascript redirect on the second page, with a timeout function (so users actually see the confirmation), while maintaining serverside state using $_SESSION or another cookie solution.
UX-wise, this is not an ideal solution because of aforementioned reasons and because it is harmful to visitors that have Javascript turned off.
Alternatively, you could send a Javascript notice on the credential form page, telling the user he's logging in. People without Javascript won't see the notice but get logged in anyways.

Is a stale session stopping post variables being submitted

I have had this issue intermittently for some time, but I only just had it happen repeatedly enough to actually trouble shoot it. It happened repeatedly in FF but I have seen it in Chrome as well.
I have login form as below, it is very simple, email address and password and a submit button
<form method="post" action="login.php" id="valid" class="mainForm">
<fieldset>
<div class="">
<label for="req1">Email:</label>
<div class="loginInput"><input style="width: 100%;" type="text" name="email" class="validate" id="req1" /></div>
<div class="fix"></div>
</div>
<div class="">
<label for="req2">Password:</label>
<div class="loginInput"><input style="width: 100%;" type="password" name="password" class="validate" id="req2" /></div>
<div class="fix"></div>
</div>
<input name="action" type="hidden" value="log_in" />
<div class="">
<div class=""><input type="checkbox" id="check2" name="remember_me" value="1"/><label>Remember me</label></div>
<input type="submit" value="Log me in" class="submitForm" />
<div class="fix"></div>
</div>
</fieldset>
</form>
Submitting the above form wouldn't log me in, it just displayed the login form again as if nothing was submitted. So I amended the login.php file that is submitted to, and at the very top added print_r($_POST);
When I submitted the form again all it displayed was an empty array. It was like the form variables just weren't being sent. I tried several accounts, and got a blank array each time.
I then tried to enter an email address that I new wasn't in the database, and to my amazement the $_POST array populated with the fake email and password. I then tried a real account again and it was blank.
The last thing I did was to deleted the session cookie in FF for the site, and then try again. To my surprise I could then log in OK. I logged in and out a few times after that with no problem at all!
So my question is: What was that session cookie doing to prevent the post variables from being sent (if that was what was actually happening) and why did it populate the $_POST array if I entered a fake email address? The print_r($_POST) I did was the very first thing in the script, before any other processing or includes, yet it still was empty??
I guess I don't really know how browsers deal with session cookies, but this behaviour has me completely clueless.
Any advice on how to troubleshoot this, or general session advice.
EDIT - PHP Code for the login.php
<?php
print_r($_POST);
include '../inc/init.php';
$action = fRequest::get('action');
if ('log_out' == $action) {
fSession::destroy();
fAuthorization::destroyUserInfo();
fMessaging::create('success', '<center>You were successfully logged out</center>');
}
if (fAuthorization::checkAuthLevel('user') || fAuthorization::checkAuthLevel('buser')) {
fURL::redirect('index.php');
}
if ('log_in' == $action) {
# Set session variables etc...
}
The init.php include at the top sets the database connetion strings and starts the session etc... I am using FlourishLib Un-Framework set of classes which includes a session class.
Thanks
try this code please
$actions = array('log_in', 'log_out');
$action = fRequest::getValid('action', $actions);
if ($action == 'log_out') {
fSession::clear();
fAuthorization::destroyUserInfo();
fMessaging::create('success', URL_ROOT . 'index.php', 'You were successfully logged out');
fURL::redirect(URL_ROOT . 'index.php');
}
if ($action == 'log_in') {
if (fRequest::isPost()) {
try {
$valid_login = fRequest::get('username') == 'yourlogin';
$valid_pass = md5(fRequest::get('password')) == 'md5(youpassword)';
if (!$valid_login || !$valid_pass) {
throw new fValidationException('The login or password entered is invalid');
}
fAuthorization::setUserToken(fRequest::get('username'));
fURL::redirect(fAuthorization::getRequestedURL(TRUE, URL_ROOT . 'index.php'));
} catch (fExpectedException $e) {
fMessaging::create('error', fURL::get(), $e->getMessage());
}
}
include VIEWS_DIR . DS . basename(__FILE__);
}

How to stop people accessing hidden pages where a login is required?

I am doing a project in school, I need to know a simple way to stop poeple from entering the site without a session. I have alot of pages I don't believe I spent the time pasting code on every page. Also I have menu bar that is included in every page thanks to php, so i was wondering wat type of code would I have to put in the menu to block user without a session. The rest of the content code is on the pages that I want to hide. I believe that you can login by typing out the url and allow users to see hidden pages that are for logged in users.
Please do not use a plain cookie. Sessions are the way to go. Or if can't use sessions and must use a cookie, sign the cookies first to be able to verify that your application was really the one to set it.
<?php
session_start();
if (!isset($_SESSION['authenticated'])) {
header('Location: login.php');
exit;
}
... whatever logged in users should see ..
If you don't want to use session, then use cookie.
<?php
/*Just add this piece of PHP code to top of any page you
don't want not-logged in users to see */
if (!isset($_COOKIE['logged']))
header("Location: login.php"); //It redirects the user to your login page
?>
<html>
<body>
...
</body>
</html>
Login page could be like this:
<?php
if (isset($_COOKIE['logged']))
header("home.php");
if ($_POST['submit']) {
//get username and password
$uname = $_POST['uname'];
$pass = $_POST['password'];
if ($uname=="correct" && $pass=="correct"){ //EDIT
setcookie('logged','1');
header("Location: home.php"); //Redirect to home page
}
else echo "Wrong combinaton!";
}
?>
<html>
<body>
<form action="login.php" method="post">
<label>Username</label><input type="text" name="uname" /><br />
<label>Password</label><input type="password" name="pass" /><br />
<input type="submit" name="submit" value="Login" />
</form>
</body>
</html>

Categories