So, I have the following code:
<?php
mysql_connect("HOSTADDRESS", "USERNAME", "PASS") or die(mysql_error());
mysql_select_db("DATABASENAME") or die(mysql_error());
//Checks if there is a login cookie;
if(isset($_COOKIE["ID_my_site"]))
//If there is, it logs you in and directs you to the member page
{
$username = $_COOKIE["ID_my_site"];
$pass = $_COOKIE["ID_my_site"];
$check = mysql_query("SELECT * FROM userdata WHERE emailaddress = '$emailaddress'") or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{
if ($pass != $info["password"])
{
}
else
{
header("Location: members.php");
}
}
}
//If the login form is submitted;
if (isset($_POST["submit"])) { //If form has been submitted
//Makes sure they are filled in
if(!$_POST["emailaddress"] | !$_POST["pass"]) {
die("You did not fill in all required fields.");
}
//Checks it against the database;
if (!get_magic_quotes_gpc()) {
$_POST["email"] = addslashes($_POST["email"]);
}
$check = mysql_query("SELECT * FROM userdata WHERE emailaddress = '".$_POST["emailaddress"]."'") or die(mysql_error());
//Gives error if user doesn't exist;
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
die("That users does not exist in our database. <a href=register.php>Click here to register</a>");
}
while($info = mysql_fetch_array( $check ))
{
$_POST["pass"] = stripslashes($_POST["pass"]);
$info["password"] = stripslashes($info["password"]);
$_POST["pass"] = md5($_POST["pass"]);
//Gives error if the password is wrong
if ($_POST["pass"] != $info["password"]) {
die("Incorrect password, please try again.");
}
else
{
//If login is ok then we add a cookie
$_POST["emailaddress"] = stripslashes($_POST["emailaddress"]);
$hour = time() + 3600;
setcookie(ID_my_site, $_POST["emailaddress"], $hour);
setcookie(Key_my_site, $_POST["pass"], $hour);
//Then it redirects them to the members area
header("Location: members.php");
}
}
}
else
{
//If they are not logged in
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login</h1></td></tr>
<tr><td>Email Address:</td><td>
<input type="text" name="emailaddress" maxlength="60">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="pass" maxlength="12">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
<?php
}
?>
When I try to login via the website, even though the password is identical to the password on the database, it reads 'Incorrect password, please try again.' If I try the password with the encryption version which is found on the database, it also shows this message. Please could someone help me with this bug?
if(!$_POST["emailaddress"] | !$_POST["pass"]) {
use || so will be
if(!$_POST["emailaddress"] || !$_POST["pass"]) {
Related
I have a 'users' table which have two columns/attributes i-e username and password. this table holds admins of the website. now i have created a form that's used to delete one or more admins from the table mentioned above, but if currently logged in user tries to delete itself, it must not happen.
the problem i'm facing is: i have received the username and password of the currently logged in user from the session, but when i enters another admin details, still it gives me the error that currently logged in user is trying to delete itself.
FORM:
<form action="delete_user.php" method="post">
<fieldset><legend style="text-align:center; font-size:18px">Enter Details of the User You want to Delete</legend><br>
<label for="username">Username : </label><input type="text" name="username" placeholder = "Username"><br>
<label for="password">Password :</label><input type="password" name="password" placeholder = "Password"><br>
</fieldset>
<p id="btn">
<input type="submit" value="Delete" name="submit_delete_user" style="font-size:16px"><input type="reset" value="Reset" style="font-size:16px"><br>
<center>
Admin Home<br>
Logout
</center>
</p>
</form>
PHP file/CODE:
<?php session_start();
$server="localhost";
$user="root";
$password="";
$database="camouflage_studio";
$con = mysqli_connect($server,$user,$password,$database);
if (mysqli_connect_errno())
{
echo "Connection Error: " . mysqli_connect_error();
}
//reiving values from form
$username = mysqli_real_escape_string($con,$_POST['username']);
$password = mysqli_real_escape_string($con,$_POST['password']);
if(isset($_POST['submit_delete_user'])){
if(!empty($_POST['username']) && !empty($_POST['password'])){
if($username == $_SESSION['username'] && $password == $_SESSION['password']){
$sql_delete = "DELETE FROM 'users' WHERE username = '$username' AND password = '$password'";
if($result = mysqli_query($con, $sql)){
echo '<script language="javascript" type="text/javascript">
alert("Record Deleted Successfully!");
window.location = "admin.php";
</script>';
}else { echo '<script language="javascript" type="text/javascript">
alert("SQL Error!");
window.location = "delete_user_form.php";
</script>'; }
}else { echo '<script language="javascript" type="text/javascript">
alert("Sorry! You can not delete currently Logged in User");
</script>'; }
}else { echo '<script language="javascript" type="text/javascript">
alert("Please Fill the Form Completly");
window.location = "delete_user_form.php";
</script>'; }
}
?>
LOGIN (from where i'm getting currently logged in user details)
<?php session_start();
error_reporting();
$server="localhost";
$user="root";
$password="";
$database="camouflage_studio";
$con = mysqli_connect($server,$user,$password,$database);
if (mysqli_connect_errno()){
echo "Connection Error: " . mysqli_connect_error();
}
mysqli_select_db($con,"camouflage_studio");
if(isset($_POST['submit_login']))
{
if(!empty($_POST['username']) && !empty($_POST['password']))
{
$get_user_name = mysqli_real_escape_string($con,$_POST['username']);
$get_password = mysqli_real_escape_string($con,$_POST['password']);
$sql = "SELECT * FROM `users` WHERE username='$get_user_name' and password='$get_password'";
if($result = mysqli_query($con, $sql))
{
if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $get_user_name;
$_SESSION['password'] = $get_password;
header('Location:admin.php');
}
else{
header('Location:login_form.html');
}
}
else{
header('Location:login_form.html');
}
}
else {
header('Location:login_form.html');
}
}
?>
I think your if condition is opposite :
Try this :
if($username != $_SESSION['username']){
// delete user
} else {
// can not delete
}
Working on a website implementing login features for coursework. Currently have script files written but when i test it , it loads login.php which is what im using for the script.
<form action="login.php" method="post">
<div class="imgcontainer">
<img src="img/icons/avatar.png" alt="ELEAGUE" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" name="username" maxlength="40">
<label><b>Password</b></label>
<input type="password" name="pass" maxlength="50">
<button type="submit">Login</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#fff">
<span class="psw">Forgot password?</span>
</div>
</form>
And the script is
<?php
//Connects to your Database
$conect = mysqli_connect("db location","username","password", "forks") or die(mysql_error());
//Checks if there is a login cookie
if(isset($_COOKIE['ID_your_site'])){ //if there is, it logs you in and directs you to the members page
$username = $_COOKIE['ID_your_site'];
$pass = $_COOKIE['Key_your_site'];
$check = mysqli_query($conect, "SELECT * FROM users WHERE username = '$username'")or die(mysql_error());
while($info = mysqli_fetch_array( $check )){
if ($pass != $info['password']){}
else{
header("Location: login.php");
}
}
}
//if the login form is submitted
if (isset($_POST['submit'])) {
// makes sure they filled it in
if(!$_POST['username']){
die('You did not fill in a username.');
}
if(!$_POST['pass']){
die('You did not fill in a password.');
}
// checks it against the database
if (!get_magic_quotes_gpc()){
$_POST['email'] = addslashes($_POST['email']);
}
$check = mysqli_query($conect, "SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysqli_num_rows($check);
if ($check2 == 0){
die('That user does not exist in our database.<br /><br />If you think this is wrong try again.');
}
while($info = mysqli_fetch_array( $check )){
$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['password']);
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
die('Incorrect password, please try again.');
}
else{ // if login is ok then we add a cookie
$_POST['username'] = stripslashes($_POST['username']);
$hour = time() + 3600;
setcookie(ID_your_site, $_POST['username'], $hour);
setcookie(Key_your_site, $_POST['pass'], $hour);
//then redirect them to the members area
header("Location: members.php");
}
}
}
else{
// if they are not logged in
?>
any help is appreciated, thanks
I'm trying to write a code that takes two input values( username and password) and compare them with values in a table (named as user) in the database. Now, if the value inserted for the username is "admin" and also the password is "admin". I want to direct the admin to his page, and if the user has inserted his info, I want to direct him to his page also. My code below looks correct but I'm getting no response. How can this be fixed?
I wrote this code for html:
<form name="userLogin" action="LoginCode.php" method="POST" >
<h3>Login</h3>
<table width="450px">
<tr>
<td valign="top">
<label for="first_name">Your Name *</label>
</td>
<td valign="top">
<input type="text" name="user_username" maxlength="50" size="30" required>
</td>
</tr>
<tr>
<td valign="top">
<label for="last_name">Password *</label>
</td>
<td valign="top">
<input type="password" name="user_password" maxlength="50" size="30" required>
</td>
<tr>
<td></td>
<td><input type="submit" name="login" value="Login" required>
</td>
</tr>
</table>
</form>
And this is my LoginCode.php
<?php
include ("../Connections/map_connection.php");
if (isset($_POST["login"])) {
$user_username = $_POST["user_username"];
$user_password = $_POST["user_password"];
/* $user_email=$_POST["user_email"]; */
if ($username = 'admin' and $user_password = 'admin') {
$data = mysql_fetch_array($result);
session_start();
$_SESSION['name'] = $data['user_username'];
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + 400;
header("location: ..Admin/AdminIndex.php");
} else {
$sql = ("select * from user where user_username='$user_username' and user_password= '$user_password' ");
$result = mysql_query($sql);
if (!$result) {
echo "Error" . mysql_error();
} else {
$row = mysql_num_rows($result);
if ($row == 0) {
echo 'Invalid username or password';
} else {
$data = mysql_fetch_array($result);
session_start();
$_SESSION['name'] = $data['user_username'];
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + 400;
header("location: UserIndex.php");
}
}
}
}
?>
Check your if condition,
if ($username = 'admin' and $user_password = 'admin')
Here you are using single '=' i.e assignment operation instead of comparison i.e '=='.
Try this :
if ($username == 'admin' && $user_password == 'admin')
:::::::::::::::::::::::UPDATE:::::::::::::::::::::::::
What does this mean?
if ($username == 'admin' && $user_password == 'admin')
{
$data = mysql_fetch_array($result);
....
}
My point is without mysql_query() you are using mysql_fetch_assoc().
I fixed it !!
<?php
include ("../Connections/map_connection.php");
if (isset($_POST["login"])) {
$user_username= $_POST["user_username"];
$user_password= $_POST["user_password"];
if($user_username=='admin' && $user_password){
$sql= ("select * from admin where admin_username='$user_username' and admin_password= '$user_password' ");
$result = mysql_query($sql);
if(!$result){
echo "Error".mysql_error();
}
else
{
$row= mysql_num_rows($result);
if($row==0) {
echo 'Invalid username or password';
}
else
{
$data= mysql_fetch_array($result);
session_start();
$_SESSION['name'] = $data['admin_username'];
$_SESSION['start']=time();
$_SESSION['expire']= $_SESSION['start'] + 400;
header("location: ../Admin/AdminIndex.php");
}
}
}
else{
$sql= ("select * from user where user_username='$user_username' and user_password= '$user_password' ");
$result = mysql_query($sql);
if(!$result){
echo "Error".mysql_error();
}
else
{
$row= mysql_num_rows($result);
if($row==0) {
echo 'Invalid username or password';
}
else
{
$data= mysql_fetch_array($result);
session_start();
$_SESSION['name'] = $data['user_username'];
$_SESSION['start']=time();
$_SESSION['expire']= $_SESSION['start'] + 400;
header("location: UserIndex.php");
}
}
}
}
?>
having a bit of trouble with my login / reg forms
Basically when i register (create new user) it takes me to the login.php script and not the register script.
The login form is in the "header.php" page so its at the top of every page including the register form. But dont think that would be an issue?
Register form
<?php
include("config.php");
include("header.php");
?>
<div id="contentwrap">
<form name="myuserform" method="POST" action="register.php" onsubmit="return validateForm();">
<tr class='alt'>
<td>email address: <td><input type="text" name="email">
<tr class='alt'>
<td>Password: <td><input type="password" name="password">
<tr class='alt'>
<td>Your name: <td><input type="text" name="username">
<tr class='alt'>
<td><input type="submit" name="adduser" value="Sign me up!">
</form>
</div>
Register.php
<?php
if (isset($_POST['adduser']))
{
$error = "";
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$md5_pass = md5($password);
$email = mysqli_real_escape_string($connection, $_POST['email']);
if (!isset($username) || empty($username) ||
!isset($password) || empty($password) ||
!isset($email) || empty($email))
{
$error = "All fields must be filled out";
}
else if (user_exists($connection, $username))
{
$error = "Username already registered";
}
else if (strlen($password) < 6)
{
$error = "Password must be at least 6 characters";
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // check if email looks valid
{
$error = "Please enter a valid email";
}
if ($error == "")
{
//$query = "INSERT INTO users (email, password, username) VALUES ('{$email}','{$md5_pass}','{$username}')";
$query = "INSERT INTO users (username, password, email) VALUES ('{$username}','{$md5_pass}','{$email}')";
$result = mysqli_query($connection, $query);
if ($result)
echo " <b>Registered successfully!</b><br/>Please return to the <a href='index.php'>index</a> to login.";
else
$error = "Unable to create new user";
}
if ($error != "") // redo error string check since the last block may have set it
{
echo "Error: {$error}. Please return to the previous page.";
}
exit();
}
?>
Login.php
<?php
include("config.php");
if (isset($_POST['username']) && !empty($_POST['username']) &&
isset($_POST['password']) && !empty($_POST['password']))
{
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = md5($_POST['password']);
$query = "SELECT * FROM users WHERE username='{$username}' AND password='{$password}'";
$res = mysqli_query($connection, $query);
if (mysqli_num_rows($res) >= 1)
{
$row = mysqli_fetch_array($res);
if($row['rank'] == "banned")
{
echo "You have been banned from the site.";
exit();
}
$_SESSION['uid'] = $row['userid'];
$_SESSION['username'] = $row['username'];
if($row['rank'] == "admin")
$_SESSION['is_admin'] = true;
header("Location: index.php");
exit();
}
else
{
echo "Username/password invalid. Return to the <a href='index.php'> home </a>page";
exit();
}
}
echo "Something went wrong, try again"; <--- this is the result im getting
?>
here is the login form (apart of header.php)
<?php
if (!isset($_SESSION['uid']) || empty($_SESSION['uid']))
{
echo "<form action='login.php' method='post'>
Username: <input type='text' name='username' Placeholder='Username' style='width:100px;'/>
Password: <input type='password' name='password' Placeholder='Password' style='width:100px;' />
<input type='submit' name='submit' value='Log In' />";
echo "<div id='freeman'>
<a href='signup.php'> <img src='images/register.jpg' width='60px' height='60px' /> </a>
</div>";
} else {
echo "You are logged is as {$_SESSION['username']} • <a href='logout.php'>Logout</a>";
}
?>
The problem that when you register your not opening a session to consider the user as logged and acquire a session for him.
The other issue your not checking in your login script if the user already have a session which implies that he is already logged in
I'm stuck in login page. From home,user will login (form send to check_login) and from check_login user will be directed to page based on their role. However, I cannot pass through the login page. I mean I keep getting the error message from header('location: 1.php?error=1');
fyi, i've successfully connected to db. The data is there. But if I echo oci_num_rows, the result is 0..
Here is my code login.php
<form action="check_login.php" method="post" name="login">
<div class="error"><?php include('error-handler.php'); ?></div>
<p> Matric / Staff ID :</p>
<p><input type="text" name="id" size="20" maxlength="10" onkeypress="return isNumberKey(event)" required value=""/></p>
<p>Password :</p>
<p><input type="password" name="password" id="password" size="20" maxlength="8" min="6" required value="" />
<script type="text/javascript">
//add a show password checkbox
new ShowPasswordCheckbox(document.getElementById("password"));
//test the submitted value
document.getElementById('login').onsubmit = function()
{
alert('pword = "' + this.pword.value + '"');
return false;
};
</script>
</p>
<p><input type="submit" name="submit" value="Login"/></p> </form>
and here is my check_login.php
<?php
ob_start();
// Inialize session
session_start();
require_once('connection.php');
//if the login form is submitted
if(isset($_POST['submit']) && !empty($_POST['submit']))
{
$id = $_POST['id'];
$pass = $_POST['password'];
$stmt2= oci_parse($conn, "SELECT * FROM user1 WHERE id = '$id'")or die(oci_error());
$check2 = oci_execute($stmt2);
//Gives error if user dosen't exist
$check3 = oci_num_rows($stmt2);
if ($check3 == 0)
{
header('location: 1.php?error=1'); //the msg will be: you are not eligible user.
exit();
}
else
{
while($info2=oci_fetch_array($stmt2,OCI_ASSOC+OCI_RETURN_NULLS))
{
//gives error if the password is wrong
if ($pass != $info2['password'])
{
header('location: 1.php?error=2'); //password mismatch with id
exit();
}
else
{
// if login is ok then we add a cookie
$_SESSION['id'] = $_POST['id'];
$_SESSION['password'] = $_POST['password'];
$hour = time() + 86400;
setcookie(ID_site, $_SESSION['id'], $hour);
setcookie(Pass_site, $_SESSION['password'], $hour);
//then redirect them to the members area
if ($info2['role']=='admin')
{
header('Location: homeAdmin.php');
}
elseif ($info2['role']=='staff')
{
header('Location: homeStaff.php');
}
elseif ($info2['role']=='student')
{
header('Location: homeStudent.php');
}
else
{
header('Location: 1.php');
}
} //end else
} //end while
}//end else
}// end if submit
else
{
header('Location: 1.php');
}
?>
Please share your opinion or pls correct if i'm wrong. Thank you. :)
From PHP manual 'oci_num_rows' : http://php.net/manual/en/function.oci-num-rows.php
This function does not return number of rows selected! For SELECT
statements this function will return the number of rows, that were
fetched to the buffer with oci_fetch*() functions.