POST form variables to another php file after validation - php

<?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.

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! :)

Login functionality in HTML page

I have created a HTML page which takes user-id and password from user and then check there validity through database. Till now i was directing them to another page after successful login. But now i want to update same page after login. Just like www.facebook.com ; when we are NOT logged in its asks for user-id and password, but if we are login our profile contents are displayed on the same page i.e. facebook.com. What i was doing; directing it to page "login.php" which of course you can access without login.
For example there is a page "movies.com" which allows user to watch some movies after login; before i was just directing them to another page say "successful_login.com" after they login. It was a funny approach, but was working for my college assignments.
PS. Am just a noob, sorry if i asked something funny.
<?php
if(mysql_connect("localhost","root","")==false)
{
die ("Connection Failed");
}
mysql_select_db("data");
if($_POST)
{
$id=$_POST["email"];
$pwd=$_POST["password"];
$pwd=hash( 'sha256', $pwd);
$sql=mysql_query("SELECT* FROM admin_data WHERE id='$id' AND pass='$pwd'");
if($sql)
{
header("Location: login.php");
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<form method="POST">
<h1>Welcome</h1>
<div class="inset">
<p>
<label for="email">Login</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="password">PASSWORD</label>
<input type="password" name="password" id="password">
</p>
</div>
<p class="p-container">
<span>Forgot password ?</span>
<input type="submit" name="Login" id="Login" value="Log in">
</p>
</form>
</body>
</html>
To use the session variable you need to start session at the top.
session_start();
Now store the email value in the session in here.
if(mysql_num_rows()>0)//It was originally if($sql)but I am using mysql_num_rows
//The reason for saving the value in the session here is this.
First you want to make sure that user have valid credential to log in.
{
$_SESSION['email']=$id
header("Location: login.php");
}
In your form you can do something like this
session_start();//Start the session at the top so you can use the session variable.
then simply use if else statement.
if($_SESSION['email']==TRUE)
{
$email=$_SESSION['email'];
//Now you can run the query by using $email to fetch the record of the user.
}
else
{
//Show them a form or redirect them to another page.
}
Note:mysql is deprecated and is going to be dropped soon. Use mysqli or P.D.O

Error with Admin login page in PHP and mySql

When i run this code everything seems to be fine... But when I login with the right username and password i get the following: That information is incorrect, try again Click Here I should be taken to the index.php file.
I also have echo the sql query and it gave me this Resource id #4
Can anyone spot the problem here.
Here is the PHP
$manager = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["username"]);
$password = preg_replace('#[^A-Za-z0-9]#i','',$_SESSION["password"]);
include"db_connection.php";
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' and password='$password' LIMIT 1");
$existCount = mysql_num_rows($sql);
if ($existCount ==1){
while($row = mysql_fetch_array($sql)){
$id=$row["id"];
}
$_SESSION["id"]=$id;
$_SESSION["manager"]=$manager;
$_SESSION["password"]=$password;
header("location:index.php");
exit();
}else{
echo'That information is incorrect, try again Click Here';
exit();
}
}
?>
Here is the HTML:
<html>
<head>
<title> Admin Login Page</title>
<head>
<body>
<div align="center" id="mainWrapper">
<div id="pageContent"><br/>
<div align="left" style="margin-left:24px;">
<h2> Please log in To manage the store</h2>
<form id="form1" name="form1" method="post" action="admin_login.php">
User Name: <br/>
<input name="username" type="text" id="username" size="40"/>
<br/></br>
Password: <br/>
<input name="password" type="password" id="password" size="40">
<br/>
<br/>
<br/>
<br/>
<br/>
<label>
<input type="submit" name="button" id="button" value="LogIn">
</label>
</form>
</body>
</html>
Look at your first two lines. You're using $_SESSION whereas the form submitted data will be in $_POST.
You have an extra curly brace, }.
As good practice, never build a query from unescaped strings (especially if they are stored in $_SESSION since they can be easily hijacked), never store a user's password in raw format in the database, and never save a raw password to the session. All these issues make your application very vulnerable and with great security risks which not only are subject for revealing users' sensitive data, but also can compromise your system. This being said, you should use mysql_real_escape_string() to escape user input when querying the database, you should encrypt your password with MD5/SHA/whatever (maybe add a salt too) and you should store only the user ID in the session because the other don't matter anyway.
Also, there is no reason to loop over the query results, since you are sure to have only one record returned.
Furthermore, I assume that the code you have posted is incomplete. Otherwise, your session variables won't work because you have not started a session with session_start(). Also, if you want to work with the username and password provided in the form, you must use $_POST["username"] and $_POST["password"], since this is how you grab the posted data, not by using sessions.

PHP password protected page cookie

I have a very simple PHP password protected page. I'd like to add a session cookie so the browser will stay logged (say for 7 days).
Here is my current code:
<?php
$password = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8";
if (sha1($_POST['password']) == $password) {
?>
Password Protected Content
<?php
}
else {
?>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Password: <input type="password" name="password" class="formpart" />
<input type="submit" name="Submit" value="Login" class="login-button" />
</form>
</body>
</html>
<?php
}
?>
I have no idea where to start, so I'd really appreciate some help. Thanks in advance!
Please make yourself a look on this things for PHP:
session_start()
Next take a look here: How to change the session timeout in PHP?
$_SESSION[]-Array
Also your code will never jump into the password protected content block.
$password = "password";
if (sha1($_POST['password']) == $password) {
Let's say you gave in the right password ("password") - so the if would ask:
if 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8 equals password.
You are using hashing, but that is not needed here.
Your requirement is a very classical practice. You can read a tutorial here: http://www.phpnerds.com/article/using-cookies-in-php/2
Notes:
Compare hash to hash
Never save your plain-text password in a cookie
More secure: don't save hashed passwords in cookies like the tutorial.
Just store a session hashed code and using a DB table session to map
it with the user's sessions.
Hope it helps.

php login page with mysql and session

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');

Categories