php relocate when user logged in - php

Currently creating a html sign in form consisting of a email address and password saved in a file called index.php.
Above my <html> tag I've created relevant php scripts to check whether the information provided matches that of what is saved in my database.
After a small number of if statements, I'm trying to use the header() function redirect the user to a new page.
Though, this doesn't seem to be working and I'm pretty stuck for why.
My HTML form -> form action='index.php' which directs itself to itself, so I'm not sure if that is potentially causing an error?
My HTML:
<form action="index.php" method="POST">
<table style="width:100%">
<tr>
<th><input type="text" name="email" required placeholder="Email" /></th>
</tr>
<tr>
<th><input type="password" name="password" required placeholder="Password" /></th>
</tr>
<tr>
<th> <input class="button" id="sign-in-show" type="submit" value="Sign in" name="submit" /> </th>
</tr>
<tr>
<th> <p style="float:right; font-size:13px; margin-top:0px;"> Forgot password? </p> </th>
</tr>
</table>
</form>
I'll also post all my php code, as only posting my header() code seems a bit pointless:
$conn = new mysqli($servername, $username, $password);
if($conn->connect_error) {
die ('Connection Failed');
} else {
echo ('Connection Established <br>');
if(!mysqli_select_db($conn,'Oreon')) {
die('Database could not be reached ' . $conn->error);
} else {
// First get the row containing the email address provided
$sign_in_token = "SELECT * FROM core_customer_information WHERE email='".$email."' LIMIT 1";
$result = mysqli_query($conn, $sign_in_token);
// Check if the query has returned a row
if(mysqli_num_rows($result) == 1)
{
// Store needed variables
while($row = mysqli_fetch_assoc($result))
{
$tempPassword = $row['password'];
$checkActivation = $row['activated'];
// Check if the account has been activated
if($checkActivation=='0')
{
die('Your account has not yet been activated');
}
// Check if password matches hashed crypted password
else if (password_verify($user_password, $tempPassword))
{
$_SESSION['sessionEmail'] = $email;
header('Location: http://www.google.com');
exit();
}
}
}
else
{
die ("Incorrect email address or password: " . $conn->error);
}
} // close brackets db selected
}
}
At the moment, I'm just trying to redirect to Google just for testing purposes.
Would appreciate if someone could help me.
Thanks in advance (and sorry for having to post all of my code)

Related

Php code executing the error line while fetching data for a login page

<?php
session_start();
include_once 'dbconnect.php';
if (isset($_SESSION['user']) != "") {
header("Location: home.php");
}
if (isset($_POST['btn-login'])) {
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res = mysql_query("SELECT * FROM telecomt_user WHERE email='$email'");
$row = mysql_fetch_array($res);
if ($row['password'] == md5($upass)) {
$_SESSION['user'] = $row['user_id'];
header("Location: home.php");
} else {
?>
<script>alert('wrong details');</script>
<?php
}
}
?>
This is my code for fetching data from database to let the user to log in by email and password. My table name is "telecomt_user".
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="email" placeholder="Your Email" required /> </td>
</tr>
<tr>
<td><input type="password" name="pass" placeholder="Your Password" required /></td>
</tr>
<tr>
<td><button type="submit" name="btn-login">Sign In</button></td>
</tr>
<tr>
<td>Sign Up Here</td>
</tr>
</table>
</form>
And this my html form code. The code works fine in localhost but when I uploaded it to my server it does not work. It always executes this line:
<script>alert('wrong details');</script>
Is it problem in my database? But I am using the same name and pattern what I used in my localhost and also my sign up form works with the same database. My "dbconnect.php" file is also okay. What is the problem?
instead of $row['password'] , can you try to type the column of the password in the string, for example $row[0] (if password column is the first column).
I think you have to put break point in each condition like
if(your condition){
echo "something";exit;
}else{
echo "nothing";exit;
}
Better to do checking on query only email and password
$res=mysql_query("SELECT * FROM telecomt_user WHERE email='$email' AND password='md5($upass)'");
$row=mysql_fetch_array($res);
Now condition login or not
if(count($row)>=1){
//login
}else{
// credentials wrong message
}

Login form PHP is only returning blank fields

I have a issue with my login form. I'm trying to login with PHP and MySQLi but for some reason every time I press the login button. The fields within the form reset to blank fields. This is my code index.php
<html>
<head>
<title>User Login</title>
</head>
<body>
<form action="" method="post">
<table width="500" align="center" bgcolor="skyblue">
<tr align="center">
<td colspan="3"><h2>User Login</h2></td>
</tr>
<tr>
<td align="right"><b>Email</b></td>
<td><input type="text" name="email" required="required"/></td>
</tr>
<tr>
<td align="right"><b>Password:</b></td>
<td><input type="password" name="pass" required="required"></td>
</tr>
<tr align="center">
<td colspan="3">
<input type="submit" name="login" value="Login">
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
session_start();
$con = mysqli_connect("localhost","root","usbw","login");
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established:" . mysqli_connect_error();
}
// checking the user
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($con,$_POST['email']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$sel_user = "SELECT * FROM users WHERE user_email='".$email."' AND user_pass='".$pass."'";
echo $sel_user;
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
echo $check_user;
if($check_user == 1){
$_SESSION['user_email']=$email;
header('Location: loggedin.html'); }
else { header('Location: index.html'); }
}
?>
I hope someone can help me to fix this issue because I really need to build a login form for my website
There's a few things I'd like to point out about your code, but the primary issue you've been having all along is that you are sending headers before you are calling the session_start(); and header("Location: ..); functions. This causes "Headers already sent" warnings, and will not break your script, but it won't function properly. You should read How to fix "Headers already sent" error in PHP.
The code below has been altered some as well, I've made a few changes to it that you really should include
Using prepared statements, to protect your database against SQL injection (see How can I prevent SQL injection in PHP?) (never, never, never, never ever trust user-input!)
Using exit after calling a header("Location .."); function (see php - Should I call exit() after calling Location: header?)
The altered code is given below, and should be placed above ANY kind of HTML.
<?php
session_start();
$con = mysqli_connect("localhost","root","usbw","login");
if (mysqli_connect_errno()) {
echo "MySQLi Connection was not established:" . mysqli_connect_error();
}
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$pass = mysqli_real_escape_string($con, $_POST['pass']);
$sql = "SELECT user_email FROM users WHERE user_email=? AND user_pass=?";
if ($stmt = $mysqli_prepare($sql)) {
mysqli_stmt_bind_param($stmt, "ss", $email, $pass);
mysqli_stmt_store_result($stmt);
// Checking if the user was valid
if (mysqli_stmt_num_rows($stmt) > 0){
$_SESSION['user_email'] = $email;
header('Location: loggedin.html');
exit;
} else {
header('Location: index.html');
exit;
}
}
}
?>
<!-- HTML form goes here, nothing(!) before this PHP -->
What you really should do is to hash your passwords - from the looks of it, your passwords are stored in clean text in the database, this is a BIG no-no!
You should use password_hash() and password_verify() for that. It's really important to protect your user should your database be breached.
To troubleshoot further, you should enable error-reporting:
error_reporting(E_ALL);
mysqli_error
mysqli_stmt_error
When you have enabled this, PHP will tell you what's wrong if you just check your logs.
dude try this
<html>
<head>
<title>User Login</title>
</head>
<body>
<form action="" method="post">
<table width="500" align="center" bgcolor="skyblue">
<tr align="center">
<td colspan="3"><h2>User Login</h2></td>
</tr>
<tr>
<td align="right"><b>Email</b></td>
<td><input type="text" name="email" required="required"/></td>
</tr>
<tr>
<td align="right"><b>Password:</b></td>
<td><input type="password" name="pass" required="required"></td>
</tr>
<tr align="center">
<td colspan="3">
<input type="submit" name="login" value="Login">
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
session_start();
$con = mysqli_connect("localhost","root","usbw","users");
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established:" . mysqli_connect_error();
}
// checking the user
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($con,$_POST['email']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$sel_user = "SELECT * FROM users WHERE user_email='".$email."' AND user_pass='".$pass."'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user == 1){
$_SESSION['user_email']=$email;
header('Location: loggedin.html');
}
else {
header('Location: index.html');
}
}
?>

How to fix this PHP Forgotten Password Script?

So basically, I'm trying to make a simple, yet secure, forgotten password script.
There are two scripts, one that allows the user to enter their email address. This will then send them an email with a link that they must visit to save their new password.
The second script is where the link leads to. This script saves the new password.
For security purposes, I made a new table within my database called 'token'. It has three fields; token, email, used. Token is a random generated string of 10 letters and numbers, email is just that users email address, and used is an integer of either 1 or 0 indicating whether or not the token has been used.
You will be able to understand far more of my structure once you read over the two scripts. They are not to long, and not complex at all.
What is going wrong
Okay, so there is only one small thing going wrong, and this is within the reset-password.php script. This is where the users come to after they receive the email. Basically, I type in a new password, and click 'Reset Password', yet nothing happens. No errors or confirmations are shown, along with nothing changing within my database. I can't seem to debug this, and have been searching and trying for hours now. All help and suggestions would be greatly appreciated.
Please try to keep in mind that I am still a newbie at PHP and MySQL. Been working with PHP for approximately 8 weeks now, and MySQL for only 2.
forgot-password.php
<?php
//Forgotten password script
//Variable to save errors
$errors = array();
$email = $_POST['email'];
include 'config.php';
mysql_connect("$db_host", "$db_username", "$db_password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$query = "SELECT email FROM users WHERE email='" . $email . "'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if($num==0)
{
echo ("<div style='color:red;'>Email address is not registered</div>");
die();
}
$token = getRandomString(10);
$query = "INSERT INTO tokens (token,email) VALUES ('".$token."','".$email."')";
mysql_query($query);
//function to renerate the token
function getRandomString($length)
{
$validCharacters = "ABCDEFGHIJKLMNPQRSTUXYVWZ123456789";
$validCharNumber = strlen($validCharacters);
$result = "";
for ($i = 0; $i < $length; $i++)
{
$index = mt_rand(0, $validCharNumber - 1);
$result .= $validCharacters[$index];
}
return $result;
}
//Send the reset link to the user
function mailresetlink($to,$token)
{
$subject = "Password Reset";
$message = '
<html>
<head>
<title>Password Reset</title>
</head>
<body>
<p>Click on the given link to reset your password Reset Password</p>
</body>
</html>
';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: Password Reset <noreply#domain.com>' . "\r\n";
if(mail($to,$subject,$message,$headers))
{
echo "We have sent the password reset link to your email at <strong>".$to."</strong>";
}
}
//If email is posted, send the email
if(isset($_POST['email']))
{
mailresetlink($email,$token);
}
?>
<table align="center" style="padding-bottom:40px;">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>Email Address: </td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Reset My Password" /></td></tr>
<input type="hidden" name="register" value="TRUE" />
</form>
</table>
reset-password.php
<?php
//Reset password script
$token = $_GET['token'];
$email;
include 'config.php';
mysql_connect("$db_host", "$db_username", "$db_password") or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
if(!isset($_POST['newpassword']))
{
$query = "SELECT email FROM tokens WHERE token='" . $token . "' AND used = 0";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$email = $row['email'];
}
if ($email != '')
{
$_SESSION['email'] = $email;
}
else
{
echo "Invalid link or Password already changed";
}
}
$pass = $_POST['newpassword'];
$email = $_SESSION['email'];
//Save new password
if(isset($_POST['newpassword']) && isset($_SESSION['email']))
{
$query = "UPDATE users SET password = SHA('$password') WHERE email='" . $email . "'";
$result = mysql_query($query);
if($result)
{
mysql_query("UPDATE tokens SET used=1 WHERE token='" . $token . "'");
}
echo "Your password has been changed successfully";
if(!$result)
{
echo "An error occurred. Please try the again or contact us at admin#domain.com";
}
}
?>
<table align="center" style="padding-bottom:40px;">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
</form>
</table>
Please, if you need any more information or code, please do not hesitate to ask.
Thanks in advance!
I don't see anywhere where you are passing the token parameter to the server on the reset page after entering the new password parameter. You should have another hidden <input /> control, I would expect. $_SERVER['PHP_SELF'] does not return query string parameters. That is likely the cause of your current problem.
Specifically,
<table align="center" style="padding-bottom:40px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
</form>
</table>
should be
<table align="center" style="padding-bottom:40px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
<input type="hidden" name="token" value="<?php echo $_REQUEST['token']; ?>" />
</form>
</table>
Make sure you also change any $_GET['token']s to $_REQUEST['token'] as it will be GET the first time, then POST the second.
That being said, your much larger problem is the ability for me to bypass all your security by specifying ' or 1=1 or ' as my token. Or, I could be mean and do a nice '; update users set password = SHA('IKnowThisPassword') where username = 'admin'; --
Moral of the story being parameterized SQL (How can I prevent SQL injection in PHP?)

php not updating password nor token in the d.b

My forgot password is not updating the token table nor is it updating the password when changes it keeps echoing the error message below is the form code:
Forgot Password</strong></h3>
<form name="forgot" method="POST" id="forgot" action="includes/reset.php">
<div align="center">
<table width="372" border="0">
<tr>
<td width="181"><p> </p>
<p><strong>Password</strong></p></td>
<td width="181"><span id="sprytextfield1"><br />
<label for="label"></label>
<input type="password" name="passsowrd" id="password" />
<span class="textfieldRequiredMsg">Your password is required</span></span></td>
</tr>
<tr>
<td><p> </p>
<p><strong>Confenter code hereirm Password</strong></p></td>
<td><span id="spryconfirm2">
<label for="password"></label>
<input type="password" name="password2" id="password" />
<span class="confirmRequiredMsg">A value is required.</span><span class="confirmInvalidMsg">The values don't match.</span></span></td>
</tr>
</table>
</div>
<div align="center">
<p> </p>
<table width="98" border="0">
<tr>
<th width="44" scope="row"><input type="submit" name="submit" id="submit" value="submit" /></th>
<th width="44" scope="row"><input type="reset" name="clear" id="clear" value="Clear" /></th>
</tr>
</table>
</div>
<div align="center">
<table width="372" border="0">
<tr> </tr>
<tr> </tr>
</table>
</div>
</form>
and the reset.php is:
<?php
session_start();
error_reporting(0);
$token=$_GET['token'];
include("settings.php");
connect();
if(!isset($_POST['password'])){
$q="select email from tokens where token='".$token."' and used=0";
$r=mysql_query($q);
while($row=mysql_fetch_array($r))
{
$email=$row['email'];
}
If ($email!=''){
$_SESSION['email']=$email;
}
else die("Invalid link or Password already changed <a href='../index.php'>Click here to go back to the HOME PAGE<a/>");}
$pass=$_POST['password'];
$email=$_SESSION['email'];
if(isset($_POST['password'])&&isset($_SESSION['email']))
{
$q="update registration set password='".md5($pass)."' where email='".$email."'";
$r=mysql_query($q);
if($r)mysql_query("update tokens set used=1 where token='".$token."'");echo "Your password is changed successfully <a href='../index.php'>Click here to go back to the HOME PAGE<a/>";
if(!$r)echo "An error occurred";
}
so the issue is the following error message is echoed all the time:
Invalid link or Password already changed.
what should i do also if i add:
if(!isset($pass)){
echo '<form method="post">
enter your new password:<input type="password" name="password" />
<input type="submit" value="Change Password">
</form>
';}
then it works but opens it in new blank page which is un professional thats y am trying to add it to the html
Your else die is in the totally wrong place. You are always going to die because while will always evaluate to false as the loop ends.
If your intent was to die if the query fails you should do something like:
$r = mysql_query($q);
if (false === $r) {
die(mysql_error());
}
while ($row = mysql_fetch_array($r)) {
...
}
Of course my general advice is to not use mysql functions at all, as they are deprecated with PHP 5.5. You also should make sure you are explicitly handling all the possible outcomes for you queries and log meaningful errors to help you debug.
You have no token being passed in the code you presented
$token=$_GET['token'];
where is that token coming from in the script, it is not calling it from the database,
$q="select email from tokens where token='".$token."' and used=0";
also you are not guarding against any sql injection, that should really be addressed, unless I missed the part of the code where the token was being sent to the reset page, if so my apologies
$r=mysql_query($q);
while($row=mysql_fetch_array($r))
{
$email=$row['email'];
}
If ($email!=''){
$_SESSION['email']=$email;
}
else die
flowing down your code you run the query to select email where the token would be blank, i assume no email is returned so if the email is not blank do this, or else die... it must die because the the $email is blank
You're closing your while block too soon. Move the } below the die
I was going to edit your post, but there were so many formatting and syntax issues I'll post it as an answer instead.
<?php
session_start();
error_reporting(0);
include 'settings.php';
connect();
$token = $_GET['token'];
$pass = $_POST['password'];
if (isset($pass) && isset($token)) {
$q = 'SELECT email FROM tokens WHERE token=' . $token . ' AND used=0';
$r = mysql_query($q);
while ($row = mysql_fetch_array($r)) {
$email = $row['email'];
}
if ($email != '') {
$_SESSION['email'] = $email; // Why?
$q = 'UPDATE registration SET password=' . md5($pass). ' WHERE email=' . $email;
$r = mysql_query($q);
if ($r) {
mysql_query('UPDATE tokens SET used=1 WHERE token=' . $token);
echo 'Your password is changed successfully <a href="../index.php">Click here to go back to the HOME PAGE<a/>';
} else {
echo 'An error occurred';
}
} else {
die('Invalid link or Password already changed <a href="../index.php">Click here to go back to the HOME PAGE<a/>');
}
}
This shnould get you on the right track, please take note of tabs, curly braces and most importantly, be consistent in how you write code. Stick to single or double quotes, always use curly braces even on single line if/else statements.
However, as others have said, this code is still highly insecure and deprecated, but it should work.

PHP/MySQL login works on one server (PHP 5.0.2) but does not work on the other (PHP 5.1.6)

Here is a stripped down version of what I use to authenticate users, it works fine on my PHP v5.0.2/MySQL 4.0.21 server, but fails on my PHP v5.1.6/MySQL v5.0.45 server.
In the code below, should I be aware of anything that might not be supported by the newer version of PHP & MySQL? Global variables have been enabled.
<?php
if(!isset($HTTP_POST_VARS['username'])&&!isset($HTTP_POST_VARS['password']))
{
//Visitor needs to enter a name and password
?>
<h1>Please Log In</h1>
This page is secret.
<form method="post" action="<?php echo $PHP_SELF;?>">
<table border="1">
<tr>
<th> Username </th>
<td> <input type="text" name="username"> </td>
</tr>
<tr>
<th> Password </th>
<td> <input type="password" name="password"> </td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Log In">
</td>
</tr>
</table>
</form>
<?php
}
else
{
// connect to mysql
include('../cgi-bin/db.php');
$username = $HTTP_POST_VARS['username'];
$password = md5($HTTP_POST_VARS['password']);
if(!$db)
{
echo 'Cannot connect to database.';
exit;
}
// select the appropriate database
$mysql = mysql_select_db('quickwebcms');
if(!$mysql)
{
echo 'Cannot select database.';
exit;
}
// query the database to see if there is a record which matches
$query = "select count(*) from auth where
username = '$username' and
password = '$password'";
$result = mysql_query( $query );
if(!$result)
{
echo 'Cannot run query.';
exit;
}
$count = mysql_result( $result, 0, 0 );
if ( $count > 0 )
{
// visitor's name and password combination are correct
echo '<h1>Here it is!</h1>';
echo 'I bet you are glad you can see this secret page.';
}
else
{
// visitor's name and password combination are not correct
echo '<h1>Go Away!</h1>';
echo 'You are not authorized to view this resource.';
}
}
?>
I'm guessing it might be because of $HTTP_POST_VARS. Try replacing that with $_POST. If it still doesn't work, try putting the following snippet right after <?php:
// Enable displaying errors
error_reporting(E_ALL);
ini_set('display_errors', '1');
Try setting register_long_arrays = On in php.ini and see if that fixes your issues.
On another note you shouldn't be building your queries up like that. Look into using PHP MySQL escaping.

Categories