Once the user signs in (in login.php) they are redirected to control.php. If they close the browser and reopen control.php they are asked to resubmit the form. How can I use the cookie I set up, instead of resubmitting the form?
login.php
<?php session_start(); /* Starts the session */
$logins = array('username' => 'pass12');
if(isset($_COOKIE['userME']) && isset($_COOKIE['passME'])){ //if cookie is set do this
$Username=$_COOKIE['userME'];
$Password=$_COOKIE['passME'];
echo $Username.'-'.$Password;
if (isset($logins[$Username]) && $logins[$Username] == $Password){
/* Success: Set session variables and redirect to Protected page */
$_SESSION['UserData']['Username']=$logins[$Username];
header("location:control.php");
exit;
} else {
/*Unsuccessful attempt: Set error message */
$msg="<span style='color:red'>1Invalid Login Details</span>";
}
}
else{ //else new person
/* Check Login form submitted */
if(isset($_POST['Submit'])){
/* Check and assign submitted Username and Password to new variable */
$Username = isset($_POST['Username']) ? $_POST['Username'] : '';
$Password = isset($_POST['Password']) ? $_POST['Password'] : '';
/* Check Username and Password existence in defined array */
if (isset($logins[$Username]) && $logins[$Username] == $Password){
/* Success: Set session variables and redirect to Protected page */
$_SESSION['UserData']['Username']=$logins[$Username];
setcookie('userME',$Username,time()+60*60*24*10,'/','71.12.145.29');
setcookie('passME',$Password,time()+60*60*24*10,'/','71.12.145.29');
header("location:control.php");
exit;
} else {
/*Unsuccessful attempt: Set error message */
$msg="<span style='color:red'>2Invalid Login Details:<?php echo $Username.'-'.$Password?></span>";
}
}
}
?>
<form action="" method="post" name="Login_Form">
<table width="400" border="0" align="center" cellpadding="5" cellspacing="1" class="Table">
<?php if(isset($msg)){?>
<tr>
<td colspan="2" align="center" valign="top"><?php echo $msg;?></td>
</tr>
<?php } ?>
<tr>
<td colspan="2" align="left" valign="top"><h3>Login</h3></td>
</tr>
<tr>
<td align="right" valign="top">Username</td>
<td><input name="Username" type="text" class="Input"></td>
</tr>
<tr>
<td align="right">Password</td>
<td><input name="Password" type="password" class="Input"></td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" type="submit" value="Login" class="Button3"></td>
</tr>
</table>
</form>
control.php
<?php
session_start();
echo "Hello, ".$_COOKIE['userME'].'<br>';
if(isset($_SESSION['UserData']['Username']))
{
if (isset($_POST['submit'])) {
switch ($_POST['submit']) {
case 'room_light':
//execute code here
break;
case 'blink':
echo shell_exec("sudo ruby /home/pi/Desktop/PiControl/blinkPin1.rb");
break;
}
}
?>
<form method="post">
<input type="submit" name="submit" value="room_light">
</form>
<?php
}
else
{
header("location:login.php");
}
?>
The usual way to deal with this is to actually create three web pages :
A form web page, that displays the form and on submission sends to page 2 ;
A checking web page, that checks the password, sets the cookie(s) and immediately redirects to page 3 ;
A result web page, that uses the cookie set by page 2.
Thus, when reloading page 3, it will immediately reuse the cookie set by page 2.
Besides, you should avoid storing the password in a cookie. You could at least store in the cookie hash('sha256', $password) ; and check against the (precomputed) hashes of passwords.
This way, the password never resides on disk and only in memory, which is better for security reasons. You can check out more information on this subject using the following links, courtesy of Fred -ii- : Is it secure to store passwords in cookies? ; php, is there a safe way to store password in cookies? ; Is it safe to store the password hash in a cookie and use it for “remember-me” login?
There would be even better hashing schemes, such as salting with a random values, but that would perhaps complicate too much for the application you're writing.
Related
When I click the login button, it redirects me to the wrong page. Why? The code does not behave the way it is intended to.
Login Page:
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form method='post' action='registration.php'>
<table width='400' border='5' align='center'>
//when i hit login , it redirects to wrong page
<tr>
<td colspan='5' align='center'><h1>Login Form</h1></td>
</tr>
/* I don't know what is wrong with this code */
<tr>
<td align='center'>Password:</td>
<td><input type='password' name='pass' /></td>
</tr>
//when i hit login , it redirects to wrong page
<tr>
<td align='center'>Email:</td>
<td><input type='text' name='email' /></td>
</tr>
<tr>
<td colspan='5' align='center'><input type='submit' name='login' value='Login' /></td>
</tr>
//login button not working
</table>
</form>
<center><font color="red" size="5"><a href="registration.php">
Sign Up Here</a></font></center>
</body>
</html>
<?php
mysql_connect("localhost","root","");
mysql_select_db("users_db");
//when i hit login , it redirects to wrong page
if (isset($_POST['login'])) {
$password = $_POST['pass'];
$email = $_POST['email'];
$check_user = "select * from users where user_pass='$password' AND user_email='$email'";
$run = mysql_query($check_user);
//when i hit login , it redirects to wrong page
if (mysql_num_rows($run)>0) {
echo "<script>window.open('welcome.php','_self')</script>";
}
else {
echo "<script>alert('Email or password is incorrect')</script>";
}
} //when i hit login , it redirects to wrong page
?>
From what I can see, when you click "Login" you should end up on a page called "registration.php" which I assume does something like this :-
<?php // registration.php
$pass = $_POST['pass']; // NOTE: Every hacker on the planet can see
$email = $_POST['email']; // this, so use some kind of filtering !
// Match $pass & $email to record in table
// If match print welcome and set-up session
// else print Email or password is incorrect
?>
I can see a few items to fix:
A robust approach to redirecting employs code like this:
header('Location: http://example.com/dir');
exit();
JavaScript as a redirection device will generally work, but it's rather brittle - the page is fully loaded before it executes, whereas a header is acted upon by the browser earlier.
To get that to work, you need to handle it before HTML output (at the start of the script) not after it. To do this, move your PHP block to the start of the file.
You also have SQL injection vulnerabilities in your code - to fix this either escape your user input, using mysql_real_escape_string($_POST['email']), or better yet swap to a newer database library, and use parameter binding.
When the user gets the credentials correct, it is normal to set a session variable to indicate this - presently you're just redirecting to another page. What's to stop the user just going there directly?
It looks like you are storing passwords in plain text. This is not a good practice, since if the database is stolen by hackers, any of your users who reuse their email/password combinations in other popular sites are at risk of further hacking. You should use a strong hash and salting approach, such as that provided by password_hash().
for some reason when I click login it dose not work gives me a error, its the button click event related to the form. ive got a url.
When click login you are meant to be able to login but it dose not work.
im quite new to using this level of php so any help would be wonderful/
http://stuweb.cms.gre.ac.uk/~ob219/logsystem/
password is password
and user beep
Code for index
<?php
session_start();
$errorMessage = '';
if (!empty($_POST['user_name']) && !empty($_POST['user_password']){
include 'library/connect.php';
$user_name = $_POST['user_name'];
$user_password = $_POST['user_password'];
$sql = "SELECT user_id FROM Login WHERE user_name = '$user_name' AND user_password = '$user_password'";
$result = mysql_query($sql) or die('Query failed. ' . mysql_error());
$row = mysql_fetch_array($result);
if (mysql_num_rows($result) == 1) {
$_SESSION['user_logged_in'] = true;
$_SESSION['id'] = "$row[user_id]";
header("Location: user.php");
}
else {
$errorMessage = 'Sorry, wrong username / password';
}
include 'library/close.php';
}
?>
<html>
<head>
<title>login</title>
</head>
<body>
<?php
if ($errorMessage != '') {
?>
<p align="center"><strong><font color="998000"><?php echo $errorMessage; ?></font></strong></p>
<?php
}
?>
<p align="center"><b>Passwords and user names stored in database with personalised message</b></p>
<form name="formLogin" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table width="400" border="1" align="center" cellpadding="2" cellspacing="2">
<tr>
<td width="150">User name</td>
<td><input name="user_name" type="text" id="user_name"></td>
</tr>
<tr>
<td width="150">Password</td>
<td><input name="user_password" type="password" id="user_password"></td>
</tr>
<tr>
<td width="150"></td>
<td><input name="btnLogin" type="submit" id="btnLogin" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
The string you are posting to is literally:
<?php echo $_SERVER['PHP_SELF']; ?>
If you just want to post to the same page, you can just leave out the action element from the form. (Is it a good practice to use an empty URL for a HTML form's action attribute? (action=""))
After further searching into what is going on, I figured it out!
You are using
http://stuweb.cms.gre.ac.uk/~ob219/logsystem/index.html
you need to change your file to (.php)
http://stuweb.cms.gre.ac.uk/~ob219/logsystem/index.php
Also yes you do have apache installed! See here
Your PHP isn't being processed. It's just being printed inline with the HTML. Since you have
open and close php statements, my guess is that you may have this file saved as index.html and don't have Apache set to parse HTML as PHP.
View your page source to confirm.
Try saving your file as index.php. You may also need to add this to a .htaccess file in the same folder:
DirectoryIndex index.php
Few corrections:
Firstly as #Advocation said leave out the action element empty if you want to post in the same page.
Your missing brackets in if statement.
Change this:
if (!empty($_POST['user_name']) && !empty($_POST['user_password']){
To:
if ((!empty($_POST['user_name']) && !empty($_POST['user_password'])){
Use php isset() function to check whether the variables are set or not and use htmlspecialchars($_SERVER["PHP_SELF"]) to prevent $_SERVER["PHP_SELF"] exploitation.
Besides to prevent sql injection, you should use PDO or Mysqli and you can use session_id() function and can bind IP address to prevent session hijacking.
$ip = getenv ( "REMOTE_ADDR" );
Like quasivivo said, none of your php is being processed by your server, I posted a picture to show you what is going on. Are you sure you have apache installed? and not ASP?
As you can see, all your script isn't processed by your server! This is a major problem, make sure you don't have any passwords variables, because anyone can see them. like for example:
$db_password = 'ilovelamp';
It is working in my server correction the lines
if (!empty($_POST['user_name']) && !empty($_POST['user_password']))
You have forgotten to close if condition ")"
I'm trying to make a login page with session() function and I had some problem with the code, but I don't know why.
What I want to do after that is in my admin page I want it to say "welcome (the username that inserted in the form)", but I dont know how.
I tried with session() but its shows me:
PHPSESSID
What should I do?
This is the code
<?php
$sid = $_POST["username"];
session_start();
include("../inc/passwords.php");
if ($_POST["ac"]=="log") { /// do after login form is submitted
if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if submitted
$_SESSION["logged"]=$_POST["username"];
} else {
echo 'Incorrect username/password. Please, try again.';
};
};
if (array_key_exists($_SESSION["logged"],$USERS)) { //// check if user is logged or not
header('Location: index.php'); //// if user is logged show a message
} else { //// if not logged show login form
echo '<table align="center" border="0">
<h3 style="color: #555" align="center" class="">بالرجاء تسجيل الدخول للمتابعة</h3>
<form action="login.php" method="post"><input type="hidden" name="ac" value="log">
<tr><td>الاســـــــم</td><td>:</td><td><input type="text" name="username" size="20"> </td></tr>
<tr><td>كلمة السر</td><td>:</td><td><input type="password" name="password" size="20"> </td></tr>
<tr><td> </td><td> </td><td><input class="buttons" type="submit" value="تسجيل الدخول"></td></tr>
</form>
</table>';
};
?>
Just for knowledge:
Most important things to be remember.
Always start session after php tag starts.
e.g.
<?php
session_start();
If you start it like:
<?php
$sid = $_POST["username"];
session_start();
It will through error message : headers already sent etc
I would recommend taking a look at the piece of code:
if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if submitted
$_SESSION["logged"]=$_POST["username"];
}
You need to make sure the $_SESSION["logged"] is actually set. Perhaps try performing an echo on it. If it is empty, it would be the logic not evaluating to true.
Also make sure you do a session_start() on your index.php page.
it wont work using session with the welcome thing
try by using mysql
like
when the admin puts it name and password
his name is putted in a table in mysql
and in the index for the admin page
you query the table
like
$username = $_POST['username'];
mysql_query(SELECT username FROM admins where username='$username');
<?php
//index.php
session_start();
if (isset($_SESSION['username'])) {
header('Location: Pro_Lesson.php');
}
if (isset($_POST['username'], $_POST['password'])){
if(empty($_POST['username']) || empty( $_POST['password'])){
echo "username or password are empty";
}else {
header('Location: login.php');
}
}
?>
<html>
<head>
</head>
<body>
<h3>User Login</h3>
<table border="0">
<form method="POST" action="index.php">
<tr><td>Username</td><td>:</td><td><input type="text" name="username" size="20"></td></tr>
<tr><td>Password</td><td>:</td><td><input type="password" name="password" size="20"></td></tr>
<tr><td> </td><td> </td><td><input type="submit" value="Login"></td></tr>
</form>
</table>
</body>
</html>
how can I post the form data to another php page after success validation for username and password ? and is it secure ?
You could do it:
$_SESSION['posted'] = $_POST;
In other php page:
print_r($_SESSION['posted']);
I'm not really sure what you are asking, but I'll take a stab.
You probably only care about the username (or a userid). What you should do is store that the user authenticated in a cookie (or session based cookie). Just storing the user's username (or user id) in a user editable cookie is a Very Bad Idea (tm). What you should do is have a table on the backend of session IDs which the cookie stores a randomized hash of the primary ID then you could use that to look up what information you stored about that user.
Seems complicated, but it's really not. I can expand more on this if you would like.
You could do what felipsmartins suggests, but you shouldn't be storing the user's password anywhere.
I'm following a php video tutorial (it's not online sorry) from Lynda.com and used the following code, but I got the following error
Error 310 (net::ERR_TOO_MANY_REDIRECTS): There were too many redirects.
could this be a problem with my code. i.e. the fact that the code has two redirect_to in the first 10 or 15 lines, or is it talking about something else?
<?php require_once("../../includes/initialize.php"); ?>
<? if(!$session->is_logged_in()){
redirect_to("login.php"); } ?>
<?php
$logfile = SITE_ROOT.DS.'logs'.DS.'log.txt';
if($_GET['clear'] == 'true') {
file_put_contents($logfile, '');
//add the first log entry
log_action('Logs Cleared', "by User ID {$session->user_id}");
//redirect to this same page so that the URL won't
//have "clear=true" anymore
redirect_to('logfile.php');
}
?>
<?php include_layout_templates('admin_header.php');?>
« Back<br/>
<br/>
<h2>Log File</h2>
<p>Clear log file</p>
<?php
if (file_exists($logfile) && is_readable($logfile) &&
$handle = fopen($logfile, 'r')) {//read
echo "<ul class=\"logentries\">";
while(!feof($handle)) {
$entry = fgets($handle);
if(trim($entry) != "") {
echo "<li>{$entry}</li>";
}
}
echo "</ul>";
fclose($handle);
} else {
echo "Could not read from {$logfile}.";
}
?>
//Remember to give your form's submit tag a name="submit" attribute
if (isset($_POST['submit'])) {//Form has been submitted.
$username = trim($_POST['username']);
$password = trim($_POST['password']);
//Check database to see if username/password exist
$found_user = User::authenticate($username, $password);
if ($found_user) {
$session->login($found_user);
log_action('Login', "{$found_user->username} loggined in.");
redirect_to("index.php");
} else {
//username/password combo was not found in the database
$message = "Username/password combination incorrect.";
}
} else {//Form has not been submitted.
$username = "";
$password = "";
}
?>
<?php include_layout_template('admin_header.php'); ?>
<h2>Staff Login</h2>
<?php echo output_message($message); ?>
<form action="login.php" method="post">
<table>
<tr>
<td>Username:</td>
<td>
<input type="text" name="username" maxlength="30" value="<?php
echo htmlentities($username); ?>" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" maxlength="30" value="<?php
echo htmlentities($password); ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="login" />
</td>
</tr>
</table>
</form>
<?php include_layout_template('admin_footer.php'); ?>
You have an endless loop of redirecting.
"login.php" redirects to "login.php" if you're not logged in. "login.php" redirects to "login.php" if you're not logged in. "login.php" redirects to "login.php" if you're not logged in. "login.php" redirects to "login.php" if you're not logged in. etc.
You should probably make the redirect happen only when the current page is not "login.php"; i.e. remove that logic from this page.
<? if(!$session->is_logged_in()){
redirect_to("login.php"); } ?>
Therein lies your problem I think. You're checking on your login page, to see if someone is logged in or not. If they're not, you'll redirect to your login page, starting a new request, and it'll perform the check again.
Login page asks, is the user logged in? No! Redirect them to the login page
Login page asks, Is the user logged in? No! Redirect them to the login page
Login page asks, Is the user logged in? No! Redirect them to the login page
ad-infinitum
People shouldn't have to be logged in to use the login page, so remove the check to see if someone's logged in before they use said page.
Check if your login page redirects if you're not logged in.
Make sure there is no output before you redirect
Make sure you exit after you have done the redirect. In your code example you will end up with some whitespace before you call the redirect function as a result of that empty line between your require and if check. If I was you, I wouldn't jump in and out of php as much as you do when there is no need to. All the way down to your first link, I see only php, but yet you have 3 <?php and one <? (which is also a bad idea. I'd stick with using only <?php).