Am using this code for authenticating my URL.
Its working fine in my localhost but when I load onto the server(goDaddy), its repeatedly asking for the username and password.
I wanna take control of those username and password fields and connect them to my database.
For that am using code like this:
$conid = mysql_connect("localhost", "root", "");
if(!$conid) {
die("sorry unable to establish a connection".mysql_error());
}
echo "connected succesfully<br>";
mysql_select_db("passurl", $conid);
$rr = mysql_query("select password from validate where username='$user' ");
while($row = mysql_fetch_array($rr)) {
$x = $row['password'];
}
if($x == $password) {
//take into the website
}
so when the username & password are entered by user, on successful authentication it takes into that page.
Am using PHP-MYSQL, as I've preliminary knowledge in it, am newbie to programming.
kindly help me in fixing the above two issues with the suitable tested code.
Edit:
Issue one is working locally and am using the same code as provided in the link. Issue two is am trying to retrieve those username and password fields from my local database so as login can be granted, on my localhost(if it works on later stage I'll take the database to online).
Edit-2:
ty.php contains code like
<?php
$auth_realm = 'Access restricted';
require_once 'auth.php';
echo "You've logged in as {$_SESSION['username']}<br>";
echo '<p>LogOut</p>'
?>
<center><h1>now you see the protected content</h1></center>
and auth.php contains
<?php
$_user_ = 'test';
$_password_ = 'test';
session_start();
$url_action = (empty($_REQUEST['action'])) ? 'logIn' : $_REQUEST['action'];
$auth_realm = (isset($auth_realm)) ? $auth_realm : '';
if (isset($url_action)) {
if (is_callable($url_action)) {
call_user_func($url_action);
} else {
echo 'Function does not exist, request terminated';
};
};
function logIn() {
global $auth_realm;
if (!isset($_SESSION['username'])) {
if (!isset($_SESSION['login'])) {
$_SESSION['login'] = TRUE;
header('WWW-Authenticate: Basic realm="'.$auth_realm.'"');
header('HTTP/1.0 401 Unauthorized');
echo 'You must enter a valid login and password';
echo '<p>Try again</p>';
exit;
} else {
$user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
$password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
$result = authenticate($user, $password);
if ($result == 0) {
$_SESSION['username'] = $user;
} else {
session_unset($_SESSION['login']);
errMes($result);
echo '<p>Try again</p>';
exit;
};
};
};
}
function authenticate($user, $password) {
global $_user_;
global $_password_;
if (($user == $_user_)&&($password == $_password_)) { return 0; }
else { return 1; };
}
function errMes($errno) {
switch ($errno) {
case 0:
break;
case 1:
echo 'The username or password you entered is incorrect';
break;
default:
echo 'Unknown error';
};
}
function logOut() {
session_destroy();
if (isset($_SESSION['username'])) {
session_unset($_SESSION['username']);
echo "You've successfully logged out<br>";
echo '<p>LogIn</p>';
} else {
header("Location: ?action=logIn", TRUE, 301);
};
if (isset($_SESSION['login'])) { session_unset($_SESSION['login']); };
exit;
}
?>
so once we hit ty.php it asks for username and password and on successful validation it shows the protected down. All this is working fine in localhost but its not working on the server.
Can someone pls help me out of this
Thanks in advance :)
You need to create a database username and password on your goDaddy hosting service, root and empty password can't get you through. The root is the default username for your local server and you didn't set any password for it, hence "" works for you as password. You must set up a username and a password on your remote server for it to work.
mysql_connect("your-host-server", "a-username", "a-secret-password"); // Password can't be empty and username can't be root, hope you understand
You are looping over the paswords, but only checking a single value after your loop.
Your code is:
while($row = mysql_fetch_array($rr)) {
$x = $row['password'];
}
if($x == $password) {
//take into the website
}
It should be:
while($row = mysql_fetch_array($rr)) {
if ($password == $row['password']) {
// take into the website
}
}
Related
First I thought this is just an IE problem. But now I enable error codes and there this is displaying this:
Notice: A session had already been started - ignoring session_start() in /var/www/html/login.php on line 7
Line 7 is the session start command.
I have three files. index.php, auth.php and login.php which contains all the login process:
index.php
<?php
echo "Log in";
?>
auth.php
$_user_ = 'admin';
$_password_ = 'password';
session_start();
$url_action = (empty($_REQUEST['action'])) ? 'logIn' : $_REQUEST['action'];
$auth_realm = (isset($auth_realm)) ? $auth_realm : '';
if (isset($url_action)) {
if (is_callable($url_action)) {
call_user_func($url_action);
} else {
echo 'Function does not exist, request terminated';
};
};
function logIn() {
global $auth_realm;
if (!isset($_SESSION['username'])) {
if (!isset($_SESSION['login'])) {
$_SESSION['login'] = TRUE;
header('WWW-Authenticate: Basic realm="'.$auth_realm.'"');
header('HTTP/1.0 401 Unauthorized');
echo '<h1>Not authorized!</h1>';
echo '<p>You must enter a valid login and password.</p>';
echo 'Log in | ';
echo 'Back to the Website</p>';
exit;
} else {
$user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
$password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
$result = authenticate($user, $password);
if ($result == 0) {
$_SESSION['username'] = $user;
} else {
session_unset($_SESSION['login']);
errMes($result);
exit;
};
};
};
}
function authenticate($user, $password) {
global $_user_;
global $_password_;
if (($user == $_user_)&&($password == $_password_)) { return 0; }
else { return 1; };
}
function errMes($errno) {
switch ($errno) {
case 0:
break;
case 1:
echo '<h1>Not authorized!</h1>';
echo 'Username and password are incorrect.';
echo '<p>Log in | ';
echo 'Back to the Website</p>';
break;
default:
echo 'Unknown error';
};
}
function logOut() {
session_destroy();
session_unset();
if (isset($_SESSION['username'])) {
session_destroy($_SESSION['username']);
foreach(array_keys($_SESSION) as $k) unset($_SESSION[$k]);
echo "<h1>You've successfully logged out</h1>";
echo 'Log In | ';
echo 'Back to the Website';
} else {
header("Location: ?action=logIn", TRUE, 301);
};
if (isset($_SESSION['login'])) { session_unset($_SESSION['login']); };
exit;
}
login.php
<?php
$auth_realm = 'My Website';
require_once 'auth.php';
session_start();
if(!isset($_SESSION['username'])) {
die('Please login first log in.');
}
echo "<p>You've logged in as {$_SESSION['username']} ";
echo 'Log out</p>'
?>
Start with index.php and click on login and enter "admin" and "password"
Click on Log out
Click on "Back to the Website"
Now Click on "Log in" again
Press cancel
Click on "Back to the Website"
Click on login.
==> Now you are logged in, without passing the username and password. This is a security lack and only works with IE 11. I tried to use several different options to delete the session, but nothing helps. Who can help me?
I also tested this with Chrome, here it works correctly and I am forced to pass the login data after point 7.
Try logging out this way:
unset($_SESSION['username']);
session_destroy();
setcookie('PHPSESSID','',time()-3600,'/','',0,0); //unless you changed the PHP session cookie name
I have a login system for a member/admin site. The login is working perfectly, but I want to verify the user and give error messages if it's not the correct user or password. So far, with what I have, it will not give any error messages although I'm not getting any errors either.
function error_message(){ $error = '';
$loginName = isset($_REQUEST['loginName']) ? $_REQUEST['loginName'] : "";
$password = isset($_REQUEST['password']) ? $_REQUEST['password'] : "";
{$results = connect($loginName);
$loginName === $results['email'];
$passwords = password_verify($password,$results['password']);
if(!$results) {$error = 'Username not found'; echo $error; header ('Location: home.php');} //if no records returned, set error to no username
else //if found {if ((isset($password)) !== (isset($passwords))) //check password, if matched log him in
{ $error = 'Password is wrong'; echo $error; header('Location: home.php');} //if not matched then set error message
}
}
if(isset($error)) {echo $error; }//if there is an error print it, this can be anywhere in the page
}
This is my connection and how it is logging in:
function connect($loginName) {
global $db;
$query = "SELECT email, level, password FROM members WHERE email ='$loginName'";
$result = $db->query($query);
$results = $result->fetch(PDO::FETCH_ASSOC);
return $results;
}
Login:
function login($loginName, $password) {
$results = connect($loginName);
if(!$results) {
header('Location: /tire/admin/home.php?err=1');
}
if ($loginName === $results['email'] && password_verify($password,$results['password'])) {
$_SESSION['loginName'] = $loginName;
if ($results['level'] === 'a') { // 1 == Administrator
$_SESSION['level'] = 'Administrator';
header('Location: /tire/admin/home.php');
} elseif ($results['level'] === 'm') { // 1 == Member
$_SESSION['level'] = 'Member';
header('Location: /tire/member/home.php');
exit;
}
}
header('Location: /tire/admin/home.php');
}
Wow, that's some nasty code we have here. Let's get started:
Let's first take a look in the connect function:
Gets the row where the email matches the loginName provided.
Return the array with the desired row.
That's correct.
Now let's take a look to the login function:
Retrieves the row where the email matches loginName.
If there is no row (email does not match any user), redirects to home.php of ¿ADMIN? with the variable $err = 1.
Recheck the email (what for?) and verify the password.
If password is correct, it checks permissions and redirects to the correspondent home.php.
Notice that if there is no matches for a permission, it redirects you to admin home.php.
Notice that if the password is incorrect, you do nothing.
I will improve this code:
function login($loginName, $password) {
$results = connect($loginName);
if(!$results) {
header('Location: /tire/error.php?code=1');
}
if (password_verify($password,$results['password'])) {
$_SESSION['loginName'] = $loginName;
if ($results['level'] === 'a') { // 1 == Administrator
$_SESSION['level'] = 'Administrator';
header('Location: /tire/admin/home.php');
} elseif ($results['level'] === 'm') { // 1 == Member
$_SESSION['level'] = 'Member';
header('Location: /tire/member/home.php');
exit;
}
} else {
header('Location: /tire/error.php?code=2');
}
}
And then in error.php (or whatever place you would like to show the errors, it's just an example):
switch($_GET['code']){
case 1:
$error = "Email invalid";
break;
case 2:
$error = "Password invalid";
break;
}
print $error
That being said, I will strongly recommend you to read about exceptions and implement the logic based on that. It's far more clean than the code above, but I didn't want to change your code so drastically.
See: http://php.net/manual/en/language.exceptions.php
Please help me I want my program to choose a site if it has not yet username then it will proceed it to ch_uname.php. Then if the login credentials have already username then it will be preceded to index_profile.php. Thank you in advance.
if(mysql_num_rows($runcreds)> 0 ) //checking log in forms
{
if(mysql_num_rows($run_uname)>=1 ) //if username has already avalaible(proceed)
{
$_SESSION['Email_add']=$email;
echo "<script>window.open('modules/index_profile.php','_self')</script>";
}
if(mysql_num_rows($run_uname)<1)//choouse username if has not yet username
{
$_SESSION['Email_add']=$email;
echo "<script>window.open('forms/ch_uname.php','_self')</script>";
//modules/index_profile.php
}
}
else
{
echo "<script>alert('Admin details are incorrect!')</script>";
}
}
Here is a basic demonstration (using a PDO connection) of what I think you are looking for? I am assuming some stuff here because you don't give enough info before your code snippet:
session_start();
// I will use PDO because I cannot bring myself to use mysql_ in this demonstration
// Initiate connection (assigning credentials assumed)
$con = new PDO("mysql:host=$mysqlDB;dbname=$mysqlTable", $mysqlUser, $mysqlPass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT));
if(isset($_POST['login'])) {
$username = trim($_POST['username']);
// Stop if empty
if(empty($username)) {
// You can echo or assign to a variable to echo down the page
echo 'Username cannot be empty';
return;
}
// Set up prepared statement
$query = $con->prepare("select Email_add,password from `users` where username = :username");
$query->execute(array(":username"=>$username));
// Loop through returned
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
// If the loop comes up blank, assign false (0)
$result = (isset($result) && !empty($result))? $result:0;
// If username exists
if($result != 0) {
// I am assuming you have some form of super secure hash method for passwords...
$password = bcrypt($_POST['password']);
// If passwords match, create session
if($result[0]['password'] == $password) {
$_SESSION['Email_add'] = $result[0]['Email_add'];
// You probably don't need javascript to redirect
header('Location: modules/index_profile.php');
exit;
}
else {
// Password doesn't match
// You can echo or assign to a variable to echo down the page
echo 'Invalid Username/Password';
}
}
// This would mean the username doesn't exist
else {
header('Location: forms/ch_uname.php');
exit;
}
}
login/index.php
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
<?php
if($_SESSION['valid'] == 1){ #user has logged in by creating a session var
echo "<a href='logout.php'>Logout</a>";
}
else{
return false;
}
?>
Once login/index.php is filled out, it validates a valid login with check_buyer.php:
<?php
session_start(); #recall session from index.php where user logged
require_once('../inc/db/dbc.php');
$connect = mysql_connect($h, $u, $p) or die ("Can't Connect to Database.");
mysql_select_db($db);
$LoginUserName = $_POST['userName'];
$LoginPassword = mysql_real_escape_string($_POST['userPass']);
//connect to the database here
$LoginUserName = mysql_real_escape_string($LoginUserName);
$query = "SELECT uID, uUPass, dynamSalt, uUserType FROM User WHERE uUName = '$LoginUserName';";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such USER exists
{
echo "Invalid Username and/or Password";
}
$ifUserExists = mysql_fetch_array($result, MYSQL_ASSOC);
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
header( 'Location: buyer/' ); # return true if sessions are made and login creds are valid
echo "Invalid Username and/or Password";
return true;
}
function validateUser() {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = (isset($ifUserExists['uID'])) ? $ifUserExists['uID'] : null;
$_SESSION['uUserType'] = 1; // 1 for buyer - 2 for merchant
}
$dynamSalt = $ifUserExists['dynamSalt']; #get value of dynamSalt in query above
$SaltyPass = hash('sha512',$dynamSalt.$LoginPassword); #recreate originally created dynamic, unique pass
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
else {
validateUser();
}
// If User *has not* logged in yet, keep on /login
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
If a valid user is provided, it redirects to buyer/index.php which includes the buyer_profile.php page (farther below):
<?php
session_start();
if($_SESSION['uUserType'] != 1) // error
{
die("
<div class='container_infinity'>
<div class='container_full' style='position:static;'>
<img src='img/error/noAccess.png' style='float:left;' /> <br />
<h2>403 Error: You may not view this page. Access denied.</h2>
</div>
</div>
");
}
function isLoggedIn()
{
return ($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1);
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: ../index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1){
#echo "<a href='../logout.php'>Logout</a>";
echo 'buyerid: '.$_SESSION['uID'];
require_once('buyer_profile.php');
}
else{
echo "<a href='../index.php'>Login</a>";
}
?>
buyer_profile.php
Which is basic HTML with the session_start(); at the first line
The problem lies in login/buyer/index.php, where echo 'buyerid: '.$_SESSION['uID']; does not display anything. It should be outputting the uID of the user logged in from the SELECT query in the login/check_buyer.php why isn't it storing this value upon logging in??
Anyone??
Perhaps the SELECT query is returning false so $ifUserExists is not having any value set to it (other than false).
You can test this by using print_r($ifUserExists);, which will print out the array if it is a set and valid array; otherwise, it will not print anything.
You can also try this code, that I think might solve the problem.
list($ifUserExists) = ($result) ? #array_values(mysqli_fetch_assoc($result)) : NULL;
$_SESSION["uID"] = ($ifUserExists && $ifUserExists["uId"]) ? $ifUserExists["uId"] : NULL;
# insert your couple other lines of code here, I will not write them to save space
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
elseif ($_SESSION["uID"]) {
validateUser();
}
else {die("error!");}
I am creating a login system for my website. I want to grab the user's userID (aka a primary key out of the database) to use when they log in.
I have 3 files I'm using:
/index.php - that is basically the login form with a username and password fields. It contains this php code:
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
Once form is submitted, it goes to check_buyer.php (/check_buyer.php)
<?php
session_start(); #recall session from index.php where user logged
require_once('../inc/db/dbc.php');
$connect = mysql_connect($h, $u, $p) or die ("Can't Connect to Database.");
mysql_select_db($db);
$LoginUserName = $_POST['userName'];
$LoginPassword = mysql_real_escape_string($_POST['userPass']);
//connect to the database here
$LoginUserName = mysql_real_escape_string($LoginUserName);
$query = "SELECT uID, uUPass, dynamSalt, uUserType FROM User WHERE uUName = '$LoginUserName';";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such USER exists
{
echo "Invalid Username and/or Password";
}
$ifUserExists = mysql_fetch_array($result, MYSQL_ASSOC);
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
#header( 'Location: buyer/' ); # return true if sessions are made and login creds are valid
echo "Invalid Username and/or Password";
return true;
}
function validateUser() {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = (isset($ifUserExists['uID'])) ? $ifUserExists['uID'] : null;
echo 'sessuID: '.$_SESSION['uID'];
$_SESSION['uUserType'] = 1; // 1 for buyer - 2 for merchant
}
$dynamSalt = $ifUserExists['dynamSalt']; #get value of dynamSalt in query above
$SaltyPass = hash('sha512',$dynamSalt.$LoginPassword); #recreate originally created dynamic, unique pass
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
else {
validateUser();
}
// If User *has not* logged in yet, keep on /login
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
If the credentials are valid, the user is sent to login_new/buyer/index.php
<?php
session_start();
if($_SESSION['uUserType'] != 1) // error
{
die("
<div class='container_infinity'>
<div class='container_full' style='position:static;'>
<img src='img/error/noAccess.png' style='float:left;' /> <br />
<h2>403 Error: You may not view this page. Access denied.</h2>
</div>
</div>
");
}
function isLoggedIn()
{
return ($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1);
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: ../index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1){
#echo "<a href='../logout.php'>Logout</a>";
echo 'buyerid: '.$_SESSION['uID'];
require_once('buyer_profile.php');
}
else{
echo "<a href='../index.php'>Login</a>";
}
?>
The problem is, when I login with valid credentials it sends me to login_new/buyer/index.php with the account, but is not outputting the buyer ID using the code echo 'buyerid: '.$_SESSION['uID']; what am I doing wrong here?
Try commenting the header() redirect and echo the $_SESSION['uID'] right after you set it in function validateUser() to see if the session data is actually set right there