the code is running to match username with password and if both correct redirecting to another page but that and the else statements both run
Code:
if (isset($_POST['Login'])) {
$IncorrectDetails = 0;
$Username=$_REQUEST['Username'];
$Password=$_REQUEST['Password'];
echo "<p> $Username $Password</p>";
$myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
//reads raw file
$string = fread($myfile,filesize("bin\Account Details.txt"));
//turns the string to array
$a = explode(',', $string);
foreach ($a as $result) {
$b = explode('. ', $result);
$AccountDetails[trim($b[0])] = trim($b[1]);
}
//closes file
fclose($myfile);
print_r($AccountDetails);
foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
if ($StoredUsername == $Username){
if ($StoredPassword == $Password) {
header('Location: Main.php');
}
else {
$IncorrectDetails = 1;
}
}
else {
$IncorrectDetails = 1;
}
}
if ($IncorrectDetails == 1){
echo "<script type='text/javascript'>alert('Incorrect login details');</script>";
}
}
its expected to come up with a popup when incorrect and redirect when correct
if (isset($_POST['Login'])) {
$IncorrectDetails = 0;
$Username=$_REQUEST['Username'];
$Password=$_REQUEST['Password'];
echo "<p> $Username $Password</p>";
$myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
//reads raw file
$string = fread($myfile,filesize("bin\Account Details.txt"));
//turns the string to array
$a = explode(',', $string);
foreach ($a as $result) {
$b = explode('. ', $result);
$AccountDetails[trim($b[0])] = trim($b[1]);
}
//closes file
fclose($myfile);
foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
if ($StoredUsername == $Username && $StoredPassword == $Password){
$CorrectDetails = 1;
} else {
$IncorrectDetails = 1;
}
}
if(isset($CorrectDetails) && $CorrectDetails == 1){
header('Location: Main.php');
}else ($IncorrectDetails == 1){
echo "<script type='text/javascript'>alert('Incorrect login details');</script>";
}
}
You are redirect to another page it's not a proper way instead of that you can use a variable just like you have used in else and outside the loop you can redirect to another page.
That's beacuse the redirection is not instantaneus, php code still being processed.
So, just after header('Location: Main.php'); do exit; to stop at all your script in that point, and let the redirection works.
header('Location: Main.php');
exit;
Also, you musn't print anything before the header() instruction (remove print_r()).
Related
I am trying to make a website that echos out a number or a word based on some conditions. I connected it to my database, but it always echos out 2 (user not found), instead of yes100 (password and username correct).
The weird thing is, it works on my main domain, where it outputs yes100, but here it just can not do that for some reason.
I am sure my database details are correct, and I have uploaded the file where it should be.
This is my code (not secure at all, but it is for personal use only.)
$result = $link->query($sql);
if ($result->num_rows > 0) {
// Outputting the rows
while($row = $result->fetch_assoc())
{
$password = $row['password'];
$salt = $row['salt'];
$plain_pass = $_GET['password'];
$stored_pass = md5(md5($salt).md5($plain_pass));
function Redirect($url, $permanent = false)
{
if (headers_sent() === false)
{
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
if($stored_pass != $row['password'])
{
echo "BLAHAHAHAHAHAHAHAHA";
exit();
}
else
{
echo "yes"; // Correct pass
}
if (strlen($row['hwid']) > 1)
{
if ($hwid != $row['hwid'])
{
echo "0"; // Wrong
}
else
{
echo "100"; // Correct
}
}
else
{
$sql = "UPDATE ". $tables ." SET hwid='$hwid' WHERE username='$user'";
if(mysqli_query($link, $sql))
{
echo "rdy"; // HWID Set
exit();
}
else
{
echo "4"; // Else errors
exit();
}
}
}
}
else
{
echo "2"; // User doesn't exist
exit();
}
?>
I forgot to give the user the permissions. It works now. Thanks everyone.
My login of admin panel and member panel both works fine on local server, But on Live server member panel doesn't work. As admin and member panel both use same connection file so it means connection file works fine. More over when we fill wrong user or password it says
Invalid User or Password
But when we login with correct user or password it returns back with no indication of error.
My login file upper php part is:
<?php
include_once("../init.php");
$msg='';
?>
<?php
if(isset($_POST['click']))
{
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
if(($user =='' )|| ($pass=='')){
$msg ='Please enter username & password';
}else{
$npass = ($pass);
$qry = mysql_query("select * from user where user ='$user'");
if(mysql_num_rows($qry)==0) {
$msg ='Invalid UserName';
} else {
$res = mysql_fetch_array($qry);
if($res['pass']==$npass) {
$_SESSION['USE_USER'] = $res['user'];
$_SESSION['SID'] = $res['id'];
$_SESSION['USE_NAME'] = $res['fname'];
$_SESSION['USE_SPONSOR'] = $res['sponsor'];
$_SESSION['PACKAGE_AMT'] = $res['package_amt'];
$_SESSION['ADDRESS'] = $res['address'];
$_SESSION['PHONE'] = $res['phone'];
$_SESSION['JOIN_DATE'] = $res['join_date'];
header('location: main.php');
} else {
$msg ='Invalid Password';
}
}
}
}
?>
My header file main.php is
<?php
include_once("../init.php");
validation_check($_SESSION['SID'],MEM_HOME_ADMIN);
$msg='';
$dir ='../'.USER_PIC;
$sId = $_SESSION['SID'];
?>
Session is started from another file called function.php
<?php
function logout($destinationPath)
{
if(count($_SESSION))
{
foreach($_SESSION AS $key=>$value)
{
session_unset($_SESSION[$key]);
}
session_destroy();
}
echo "<script language='javaScript' type='text/javascript'>
window.location.href='".$destinationPath."';
</script>";
}
function validation_check($checkingVariable, $destinationPath)
{
if($checkingVariable == '')
{
echo "<script language='javaScript' type='text/javascript'>
window.location.href='".$destinationPath."';
</script>";
}
}
function realStrip($input)
{
return mysql_real_escape_string(stripslashes(trim($input)));
}
function no_of_record($table, $cond)
{
$sql = "SELECT COUNT(*) AS CNT FROM ".$table." WHERE ".$cond;
$qry = mysql_query($sql);
$rec = mysql_fetch_assoc($qry);
$count = $rec['CNT'];
return $count;
}
//drop down
function drop_down($required=null, $text_field, $table_name, $id, $name, $cond, $selected_id=null)
{
$qry = mysql_query("SELECT $id, $name FROM $table_name WHERE $cond ORDER BY $name ASC");
$var = '';
if(mysql_num_rows($qry)>0)
{
$var = '<select id="'.$text_field.'" name="'.$text_field.'" '.$required.'>';
$var .='<option value="">--Choose--</option>';
while($r = mysql_fetch_assoc($qry))
{
$selected = '';
if($selected_id==$r[$id]){
$selected = 'selected="selected"';
}
$var .='<option value="'.$r[$id].'" '.$selected.'>'.$r[$name].'</option>';
}
$var .='</select>';
}
echo $var;
}
function uploadResume($title,$uploaddoc,$txtpropimg)
{
$upload= $uploaddoc;
$filename=$_FILES[$txtpropimg]['name'];
$fileextension=strchr($filename,".");
$photoid=rand();
$newfilename=$title.$photoid.$fileextension;
move_uploaded_file($_FILES[$txtpropimg]['tmp_name'],$upload.$newfilename);
return $newfilename;
}
function fRecord($field, $table, $cond)
{
$fr = mysql_fetch_assoc(mysql_query("SELECT $field FROM $table WHERE $cond"));
return $fr[$field];
}
function get_values_for_keys($mapping, $keys) {
$output_arr = '';
$karr = explode(',',$keys);
foreach($karr as $key) {
$output_arr .= $mapping[$key].', ';
}
$output_arr = rtrim($output_arr, ', ');
return $output_arr;
}
function getBaseURL() {
$isHttps = ((array_key_exists('HTTPS', $_SERVER)
&& $_SERVER['HTTPS']) ||
(array_key_exists('HTTP_X_FORWARDED_PROTO', $_SERVER)
&& $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
);
return 'http' . ($isHttps ? 's' : '') .'://' . $_SERVER['SERVER_NAME'];
}
function request_uri()
{
if ($_SERVER['REQUEST_URI'])
return $_SERVER['REQUEST_URI'];
// IIS with ISAPI_REWRITE
if ($_SERVER['HTTP_X_REWRITE_URL'])
return $_SERVER['HTTP_X_REWRITE_URL'];
$p = $_SERVER['SCRIPT_NAME'];
if ($_SERVER['QUERY_STRING'])
$p .= '?'.$_SERVER['QUERY_STRING'];
return $p;
}
preg_match ('`/'.FOLDER_NAME.'(.*)(.*)$`', request_uri(), $matches);
$tableType = (!empty ($matches[1]) ? ($matches[1]) : '');
$url_array=explode('/',$tableType);
?>
Moreover I have created user id by words and time like LH1450429882 and column is verture type. I think this has no effect on login.
I think main errors come from function.php Sorry for a long code, but I tried to cover all parts of coding.
I am struggling with this code from a week. Thanks in advance for help.
This is probably a bug that error_reporting will show off. Always use it in development mode, to catch some carelessness errors and ensure the code's clarity.
ini_set('display_errors',1);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
By implementing code ini_set('display_errors',1); error_reporting(E_ERROR | E_WARNING | E_PARSE); I got the error of header ploblem on line 6 in login php I have removed ?> and
Now my working code in login.php is
<?php
include_once("../init.php");
$msg='';
if(isset($_POST['click']))
{
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
if(($user =='' )|| ($pass=='')){
$msg ='Please enter username & password';
}else{
$npass = ($pass);
$qry = mysql_query("select * from user where user ='$user'");
if(mysql_num_rows($qry)==0) {
$msg ='Invalid UserName';
} else {
$res = mysql_fetch_array($qry);
if($res['pass']==$npass) {
$_SESSION['USE_USER'] = $res['user'];
$_SESSION['SID'] = $res['id'];
$_SESSION['USE_NAME'] = $res['fname'];
$_SESSION['USE_SPONSOR'] = $res['sponsor'];
$_SESSION['PACKAGE_AMT'] = $res['package_amt'];
$_SESSION['ADDRESS'] = $res['address'];
$_SESSION['PHONE'] = $res['phone'];
$_SESSION['JOIN_DATE'] = $res['join_date'];
header('location: main.php');
} else {
$msg ='Invalid Password';
}
}
}
}
?>
I am retrieving information from a text document and trying to test if the users input matches any of the information in the text document.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<?php
$userpassfile = fopen("usernamepass.txt", "r") or die("Unable to open file!");
$username = $_POST["usernamepassword"];
$_SESSION['$usernamepassword'] = $_POST["usernamepassword"];
while(!feof($userpassfile)){
$line = fgets($userpassfile);
$users = explode("#", $line);
for($x=0; $x<sizeof($users); $x++){
if($users[$x]==$username){
header('Location: booking.php');
} else {
header('Location: login.php');
}
}
}
if($username=="ADMINadmin"){
header('LOCATION: admin.php');
}
fclose($usernamefile);
When it checks the information in the txt, it seems to only check the first and last element. I don't know why. I thought it was because in the for loop there was a < not <=, however when set to <= it wont check the file at all. Any ideas, cheers!
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<?php
$userpassfile = fopen("usernamepass.txt", "r") or die("Unable to open file!");
$username = $_POST["usernamepassword"];
$_SESSION['$usernamepassword'] = $_POST["usernamepassword"];
if($username=="ADMINadmin"){
header('LOCATION: admin.php');
fclose($usernamefile);
exit; // If user is admin, there is no need for further checking.
} else {
header('Location: login.php'); // Set redirect to login.php by default
}
while(!feof($userpassfile)){
$line = fgets($userpassfile);
$users = explode("#", $line);
if(in_array($username, users) {
// If user was found, override redirect to login.php
// and set it to booking.php
header('Location: booking.php');
// And there is no need to iterate further, so stop the loop
break;
}
}
fclose($usernamefile);
Maybe your code must look like this
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<?php
$username = $_POST["usernamepassword"];
$_SESSION['$usernamepassword'] = $_POST["usernamepassword"];
if($username=="ADMINadmin"){
header('LOCATION: admin.php');
} else {
$userpassfile = fopen("usernamepass.txt", "r") or die("Unable to open file!");
$in_file = false;
while(!feof($userpassfile)){
if($in_file) {
break;
}
$users = explode("#", fgets($userpassfile));
$in_file = in_array($username, $users);
}
if($in_file) {
header('Location: booking.php');
} else {
header('Location: login.php');
}
fclose($userpassfile);
}
<?php
session_start();
// note here that i has removed your DOCTYPE INPUT ...
$location = NULL;
$defaultPage = "login.php";
$username = $_POST["usernamepassword"];
$_SESSION['$usernamepassword'] = $username;
// this test must be the first ... for performance
if($username=="ADMINadmin"){
$location = "admin.php";
}
else {
$userpassfile = fopen("usernamepass.txt", "r") or die("Unable to open file!");
while(!feof($userpassfile)){
$line = fgets($userpassfile);
$users = explode("#", $line);
for($x=0; $x<sizeof($users); $x++){
// i have added trim : maybe there is spaces or other invisible chars in your file
// note: if your login system is case insensitive so use this condition :
// if(strtolower(trim($users[$x])) == strtolower($username)){ ... }
if (trim($users[$x]) == $username){
$location = "booking.php";
break;
}
// here it is the mistake : if the first token of the first line is not the connected user
// so php will redirect to login page
/*
else {
header('Location: login.php');
}
*/
}
}
fclose($usernamefile);
}
// it is a good practice to be explicit... for maintenance simplicity
if (is_null($location)) {
$location = $defaultPage;
}
header("Location: " . $location);
?>
I am trying to create a login page and I am having some troubles. I cannot get this code not to return false even though I know I have the right password in my .txt document (It's just hashed though).
Here's my PHP file that I can not stop getting not to return False:
<?php
$file1 = 'userlist.txt';
$file2 = 'passlist.txt';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user = trim($_POST["usermail"]);
$pass = trim($_POST["password"]);
}
$hashedPass = "";
$arr1 = file($file1);
$arr2 = file($file2);
$userKey = array_search($user, $arr1);
if ($userKey != false) {
reset($arr2);
for ($x = 0; $x <= $userKey; $x++) {
next($arr2);
if ($x == $userKey) {
$hashedPass = current($arr2);
}
}
echo $hashedPass;
}
if (password_verify($pass, $hashedPass)) {
header("Location: worked.html"); //change this to direct user to market
}
else {
/*header("Location: index.html"); //change this to direct user back to login page with error prompt*/
print $pass;
print $hashedPass;
echo '<br>Invalid pass.';
return false;
}
?>
Also, if you can think of anything I should have in my code, please let me know. Thanks so much.
Edit: Updated what I have for my code right now. Still returning False.
Since unHash is a function, it is not getting executed (it is not called from what I can see), so $hashedPass is not getting set. In the future, try adding some debug statements (e.g. just print out $pass and $hashedPass before the return false;).
A shot in the dark: You have turned off error messages and only get a blank page instead of a redirect when entring a right login combination?
If that is the case, you might use the following code:
<?php
$file1 = 'userlist.txt';
$file2 = 'passlist.txt';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user = trim($_POST["usermail"]);
$pass = trim($_POST["password"]);
}
$hashedPass = "";
$arr1 = file($file1);
$arr2 = file($file2);
$userKey = array_search($user, $arr1);
if ($userKey != false) {
reset($arr2);
for ($x = 0; $x <= $userKey; $x++) {
next($arr2);
if ($x == $userKey) {
$hashedPass = current($arr2);
}
}
// echo $hashedPass;
}
if (password_verify($pass, $hashedPass)) {
header("Location: worked.html"); //change this to direct user to market
}
else {
/*header("Location: index.html"); //change this to direct user back to login page with error prompt*/
print $pass;
print $hashedPass;
echo '<br>Invalid pass.';
return false;
}
?>
The reason your code fails is the echo statement, which is executed before the header-redirect. It´s not allowed to have any output before an header-redirect. (more about this behaviour: How to fix "Headers already sent" error in PHP)
Here is my code:
if(is_file($userName.".txt")) {
$userDetails = explode(',', file_get_contents($userName.".txt"));
print($userDetails[0]);
if ($password == $userDetails[0]) {
print('Correct login');
} else {
print('Incorrect login');
}
}
And I have the following file: Simon.txt with the following contents: simonpassword,4,1
If the $userName is 'Simon', when the code is run, how come 4 is printed out instead of simonpassword at the line: print($userDetails[0])?
<?
$userName = "Simon";
$password = "simonpassword";
if(is_file($userName.".txt")) {
$userDetails = explode(',', file_get_contents($userName.".txt"));
print($userDetails[0]);
if ($password == $userDetails[0]) {
print('Correct login');
} else {
print('Incorrect login');
}
}
?>
Here is Simon.txt
simonpassword,4,1
And it works.