I am using following code in two different folder like Model and View. In View Folder contain two php file like Login.php and Login_success.php. Controller folder contain the mysql database table field fetch code. When I run below code It can't display the Login_success page. Only the else field Check Name and password displayed. These all file combined to out of folder index.php .
Here my code :
Login.php
<html>
<head>
<title>Login</title>
<link rel ='stylesheet' type = 'text/css' href = 'View/Design.css'>
<script>
function Validate(){
var x=document.forms["login"]["username"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
var x=document.forms["login"]["password"].value;
if (x==null || x=="")
{
alert("Password must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name = 'login' method = 'post' action = 'Controller/Controll.php' >
<fieldset>
<legend>Login</legend>
User Name :<input type = 'text' name = 'username'>
Password :<input type = 'password' name = 'password'><br><br>
<input type = 'submit' name = 'submit' value = 'submit' onsubmit = "return Validate()" >
</fieldset>
</form>
</body>
</html>
Controll.php
class Access{
function connection(){
require_once('View/Login.php');
$con = mysql_connect('localhost','root','root');
$db = mysql_select_db('Times_sheet');
$query = mysql_query('select * from Login');
$row = mysql_fetch_array($query);
if(isset($_POST['submit']))
{
if(($row['UserName']==$_POST['username']) && ($row['Password']==$_POST['password'])){
require_once("View/Login_Success.php");
}
}
else{
echo "Check User name and Password";
}
}
}
Index.php
require_once('Controller/Controll.php');
class login extends Access{
function getValu(){
require_once('View/Login.php');
}
}
$Obj = new login();
$Obj ->getValu();
$Obj ->connection();
When I enter the correct user name and password it shoes the empty page. I don't know what mistake I did.
you are just including Login_success.php in this line not redirecting to Login_success.php
if(($row['UserName']==$_POST['username']) && ($row['Password']==$_POST['password'])){
require_once("View/Login_Success.php");
}
so use header for this redirection
if(($row['UserName']==$_POST['username']) && ($row['Password']==$_POST['password'])){
header("Location: View/Login_Success.php");
exit();
}
using header php function for redirect purpose instead of require_once. Like this format header(url);
In your query you are fetching all(*) result from the table 'Login'.
Instead of this query table with a 'WHERE' :
eg. select * from Login WHERE user= $_POST['username'] AND password = $_POST['password']
If the result found then redirect the user to your required page :
header("Location : View/Login_Success.php");
First, you code is not save at all; Peace a cake for hacking
class Access{
function connection(){
require_once('View/Login.php');
$con = mysql_connect('localhost','root','root');
$db = mysql_select_db('Times_sheet');
$query = mysql_query('select * from Login');
$row = mysql_fetch_array($query);
if(isset($_POST['submit']))
{
Second, you are only including
View/Login_Success.php'
You have to do it this way:
if(($row['UserName']==$_POST['username']) && ($row['Password']==$_POST['password'])){
header('location: View/Login_Success.php');
}
}
else{
echo "Check User name and Password";
}
}
}
You must change you code ,
$query = mysql_query('select * from Login');
$row = mysql_fetch_array($query);
You SELECT all users from MySQL and after check on PHP it is not good way you can change it to : ( & MD5 your password because it is very important.)
$user = $_POST['username'];
$pass = MD5($_POST['password']);
$query = mysql_query("select * from Login WHERE `UserName` = '$user' AND `Password` = '$pass' ");
if (mysql_num_rows($query)==1)
{
// logined
}
and for save username and user in all page use session values :
session_start();
$_SESSION['user'] = $row['UserName'] ;
and for use it in Login_Success.php you can use it this code :
<?php
session_start();
echo "wellcome user : ".$_SESSION['user'] ;
?>
I have 2 offer for you:
1. use Anti SQL Injection in your code.
2. use header header('location: View/Login_Success.php'); for redirect to other page not include
Related
I know my question is easy to anyone. Just learning this PHP almost one month. I tried to perform my login system using OOP style. Where I need to login as a default user where the username and password is admin. When I tried to login it's saying object not found.
So here my code below.
Table:
CREATE TABLE loginmodule
(
loginId INT PRIMARY KEY AUTO_INCREMENT,
loginUsername VARCHAR(50),
loginPassword VARCHAR(50)
)
Here is my login script.
loginMe.php
<?php
require_once('../connection/connection.php');
require_once('../connection/loginCRUD.php');
require_once('../process/createProcess.php');
?>
<!doctype html>
<html>
<head>
<title>Login Frame</title>
</head>
<body>
<div id = "container">
<h1>Login</h1>
<form action = "post" action = "../process/createProcess.php">
<div class = "form-field">
<input type = "text" id = "username" name = "loginUsername" placeholder = "Enter Username">
</div>
<div class = "form-field">
<input type = "password" id = "password" name = "loginPassword" placeholder = "Enter Password">
</div>
<div class = "form-field">
<input type = "submit" id = "submit" name = "submit" value = "Login">
</div>
</form>
</div><!--- end container --->
</body>
</html>
So I set aside my CRUD in another file.
loginCRUD.php
<?php
error_reporting(0);
class CRUD
{
public function readLogin($dbusername,$dbpassword)
{
global $myDatabase;
$result = $myDatabase->query("SELECT * FROM loginmodule WHERE loginUsername = '$dbusername' AND loginPassword = '$dbpassword'");
if($result->num_rows > 0)
{
$row = $result->fetch_assoc();
return $row;
}
}
}
?>
Last where I set aside also my process where my validation happens.
createProcess.php
<?php
require_once('../connection/connection.php');
require_once('../connection/loginCRUD.php');
session_start();
$dbusername = $_POST['loginUsername']; //Get the value from textfield.
$dbpassword = $_POST['loginPassword'];
if(!empty($dbusername) && !empty($dbpassword))
{
if($loginUsername == $dbusername && $loginPassword == $dbpassword)
{
$create = loginCRUD::readLogin($dbusername,$dbusername);
echo "You are logged in!";
#$_SESSION['loginUsername'] = $loginUsername;
}
}
?>
Guide me if I missed something. If there's a shortcut style than this let me know :)
There are several errors in your code, such as:
There are two action attribute in your form tag.
<form action = "post" action = "../process/createProcess.php">
^ ^
It should be,
<form method="post" action="../process/createProcess.php">
On createProcess.php page, look at the following lines,
1) if($loginUsername == $dbusername && $loginPassword == $dbpassword)
^ ^
There are no variables named $loginUsername and $loginPassword
2) $create = loginCRUD::readLogin($dbusername,$dbusername);
^ ^
both the arguments are same
You're calling readLogin() method in a wrong way. You should first create an instance of class CRUD and then call it's instance method readLogin(), like this way:
(new CRUD)->readLogin($dbusername,$dbpassword);
3) $_SESSION['loginUsername'] = $loginUsername;
As I said, there is no variable named $loginUsername. It should be,
$_SESSION['loginUsername'] = $dbusername;
Always start session at your very top of your PHP script, right after the opening PHP tag, like this:
<?php
session_start();
// your code
Your query is susceptible to SQL injection. Use prepared statements for mysqli to prevent any kind SQL injection. And this is how you can prevent SQL injection in PHP.
Never store password as a plain readable text, always perform salted password hashing on raw password before inserting it into the table.
Suggestion: Don't use global in your code. Why Globals are evil?
So your code should be like this:
CRUD class:
class CRUD{
public function readLogin($dbusername,$dbpassword){
global $myDatabase;
$statement = $myDatabase->prepare("SELECT * FROM loginmodule WHERE loginUsername = ? AND loginPassword = ? LIMIT 1");
$statement->bind_param("ss", $dbusername, $dbpassword);
if($statement->execute()){
$result = $statement->get_result();
if($result->num_rows){
$row = $result->fetch_assoc();
return $row;
}else{
return false;
}
}else{
return false;
}
}
}
createProcess.php
if(isset($_POST['submit'])){
$dbusername = $_POST['loginUsername'];
$dbpassword = $_POST['loginPassword'];
if(!empty($dbusername) && !empty($dbpassword)){
if((new CRUD)->readLogin($dbusername,$dbpassword)){
echo "You are logged in!";
$_SESSION['loginUsername'] = $dbusername;
// redirect the user to the home page
}else{
echo "Incorrect username and/or password";
}
}
}
HTML
<div id = "container">
<h1>Login</h1>
<form method = "post" action = "../process/createProcess.php">
<div class = "form-field">
<input type = "text" id = "username" name = "loginUsername" placeholder = "Enter Username">
</div>
<div class = "form-field">
<input type = "password" id = "password" name = "loginPassword" placeholder = "Enter Password">
</div>
<div class = "form-field">
<input type = "submit" id = "submit" name = "submit" value = "Login">
</div>
</form>
</div>
I am trying to implement my own class, functions and views to implement multi-user authentication and pages with php, mysql and pdo class.
Please let me know if I am doing it in proper way or I am on wrong path?
Mysql table will look like:
userID-----------int 1
userName---------varchar abc
userPassword-----varchar pass
userAccessCode---int 100
This is the html, and php which will pass the data via post to function called(aut) in class authen
note: session will be start in header login. and close on logout
//include authen class
if(isset(POST){
$authen->name= Check_Params($_POST['name ']);
$authen->pass= Check_Params($_POST['pass']);
$authen->accs= Check_Params($_POST['accs']);
$authen->aut()
}
<form method="post">
<input name="name" type="text">
<input name="pass" type="password">
<input name="access" type="password">
<input type="submit" value="login">
</form>
Now authen class will check if the user is in database:
public function auth() {
$name = Check_Param($this->name);
$pass = Check_Param($this->pass);
$accs = Check_Param($this->accs);
$passhashed = hash_pass(Check_Params($this->password));
$stm = "SELECT COUNT(*) FROM userTBL WHERE `userName`=:name AND `userPassword`=:pass AND `userAccessCode`=:accs LIMIT 1";
$stm = $this->conn->prepare($stmt9);
$stm->bindParam(':nameo', $name);
$stm->bindParam(':passs', $passhashed);
$stm->bindParam(':accs', $accs);
$stm->execute();
$checkstm = $stm->fetchColumn();
if ($checkstm == 1) {
$_SESSION['accs'] = Check_Params($accs);
$_SESSION['name'] = Check_Params($name);
header("location:../home");
exit;
} else {
header("location:logout.php");
exit;
}
}
Now in each page this will check if it's login request, here is the ifitislogin function
public function ifitislogin() {
if ($_SESSION['name'] == '' | $_SESSION['accs'] == '') {
header("location:logout.php");
} else {
$accs = Check_Params(preg_replace('#[^0-9]#i', '', $_SESSION["accs"]));
$name = Check_Params(preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["name"]));
$stm = "SELECT COUNT(*) FROM userTBL WHERE `userName`=:name AND `userAccessCode`=:accs";
stm = $this->conn->prepare($stmt9);
$stm->bindParam(':nameo', $name);
$stm->bindParam(':accs', $accs);
$stm->execute();
$checkstm = $stm->fetchColumn();
if ($checkstm != 1) {
header("location:logout.php");
exit();
}
}
}
Now for example this is the index page for all:
//include class authentic
$authen->ifitislogin(); // this will check if user is valid:
echo "<h1>" welcome to the document management system</h1> <br/>";
//this will befor admin and operator
if($_SESSION['accs'] = Check_Params('100')){
echo "<h1>welcome to admin page data....</h1>";
} elseif($_SESSION['accs']) == 101) {
echo "<h1>welcome to reporter page data....</h1>"
} else {
echo "welcome msg";
}
//this will be for clients or users, the function will get the result from database based on the user name and accs/
$accs = Check_Params($_SESSION['accs']);
$name = Check_Params($_SESSION['name']);
//get the result from database based on these tow variable which means $accs, $name it will select from database base where access = $accs and name = $name
In this code section querying the data from database based on the data i get from session variables is it ok? if not how can i know which data should display to which user? or which page is for which user?
regards in advances.
I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */
I got user login system where user page has its own id in URL. for eg. xxx/profile.php?id=1
My question is: how to prevent logged user from writing other user id in URL and entering his site ?
here is the code of file profile.php:
session_start();
require 'config2.php';
require_once 'user.class.php';
if (!user::isLogged()) {
echo '<p class="error">Przykro nam, ale ta strona jest dostepna tylko dla zalogowanych u?ytkowników.</p>';
}
else {
$id = $_GET['id'];
$userExist = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM users WHERE id = '$id'"));
if ($userExist[0] == 0) {
die ('<p>Przykro nam, ale u?ytkownik o podanym identyfikatorze nie istnieje.</p>');
}
$profile = user::getDataById ($id);
echo '<h1>Profil u¿ytkownika '.$profile['login'].'</h1>';
echo '<b>ID:</b> '.$profile['id'].'<br />';
echo '<b>Nick:</b> '.$profile['login'].'<br />';
echo '<b>Email:</b> '.$profile['email'].'<br />';
echo '<b>Obiekt:</b> '.$profile['obiekt'].'<br />';
echo '<b>Typ obiektu:</b> '.$profile['typ'].'<br />';
echo '<b>Kod pocztowy:</b> '.$profile['kod'].'<br />';
echo '<b>Adres:</b> '.$profile['adres'].'<br />';
echo '<b>Poczta:</b> '.$profile['poczta'].'<br />';
echo '<b>Tel. stacjonarny:</b> '.$profile['tels'].'<br />';
echo '<b>Tel. komórkowy:</b> '.$profile['telk'].'<br />';
echo '<b>Adres strony internetowej:</b> '.$profile['www'].'<br />';
echo "<img src ='wyslane/$profile[photo]'";
}
and here's user_class.php:
<?php
class user {
public static $user = array();
public function getData ($login, $pass) {
if ($login == '') $login = $_SESSION['login'];
if ($pass == '') $pass = $_SESSION['pass'];
self::$user = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE login='$login' AND pass='$pass' LIMIT 1;"));
return self::$user;
}
public function getDataById ($id) {
$user = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE id='$id' LIMIT 1;"));
return $user;
}
public function isLogged () {
if (empty($_SESSION['login']) || empty($_SESSION['pass'])) {
return false;
}
else {
return true;
}
}
public function passSalter ($pass) {
$pass = '$###$##$'.$pass.'q2#$3$%###';
return md5($pass);
}
}
?>
I've got also my main page code here:
if (user::isLogged() == $_GET['id']) {
$user = user::getData('', '');
echo '<p>You are logged '.$user['login'].'!</p>';
echo '<p>You may see your profil or wylogować</p>';
}
else {
echo '<p>You are not logged.<br />Zaloguj się lub zarejestruj jeśli jeszcze nie masz konta.</p>';
}
I tried, what Ryan advised but it ( page) worked only when I double clicked the profile link, otherwise link sent me again to the login page.
Instead of passing the ID of the user through the URL ($_GET) try and set a $_SESSION variable with the ID of the user when he logs in.
Then you can just go to xxx/profile.php and read the $_SESSION var to find out the id of the user whose profile you want to to display.
Now I don't know how you retrieve the current logged-in user's id, but say for example you can get it from user::loggedInID() - you would just match this against the id of the profile being accessed.
For example:
if(user::loggedInID() == $_GET['id']) {
/* Allow profile to be edited */
} else {
/* Unable to edit profile */
}
As a side note, your database is extremely vulnerable with queries like so:
mysql_query("SELECT COUNT(*) FROM users WHERE id = '$id'")
Seeing as $id is retrieved from the query string, without being sanitized, the query is open to injection.
I advise not only sanitizing your query input to begin with, but also using mysqli_* functions instead of mysql_* functions (due to deprecation). Even better, use prepared statements.
While logging in just store the logged in user ID to a session variable like $_SESSION['Loggedusr'] and in each page at starting check this
session_start();
if($_SESSION['Loggedusr'] != $_GET['id'])
header("Location: loginpage.php");
I create a function to edit user password here the function code.
function updateUser ()
{
$current = md5($_POST['cpassword']);
$new = md5($_POST['npassword']);
$newc = md5($_POST['npasswordc']);
$name = $_POST['username'];
connectDB();
$check = mysql_query("SELECT password FROM user WHERE user_name = '$name'")
or die(mysql_error());
if ($check != $current) {
?> <div id="error">
<?php die('Current password is wrong. Press back to try again.'); ?>
</div> <?php
}
if ($new == $newc) :
$sql = "UPDATE user SET password = '$new' WHERE user_name = '$name'";
execute($sql);
?> <div id="error">
<?php die('Password Successfully Updated. Back to dashboard');
?> </div> <?php
else : ?> <div id="error">
<?php die('New Password did not match. Press back to try again');
?> </div> <?php
endif;
}
the value will be pass by the form on different page, everything seem to work fine. When I try to change password, it say successful, and when I check in the database, the md5 value is changing that mean the password was change.
But when I try to change password of same username, I still need to enter the old password for current password, even though in database it already changed?
What seem to be the problem?
Thank you
$check is a mysql resource, not a value. You might do
if($check && (mysql_num_rows($check) > 0))
{
$res = mysql_fetch_assoc($check);
if($res['password'] != $current) {
Be careful of SQL injections, you should do at least
$name = mysql_real_escape_string($_POST['username']);
before entering it into the query.
Also, md5 is a week hashing algorithm, I strongly suggest you use a SALT, and better hash algos like at the very least sha1() or better go for the sha2 family (sha256, sha512, for ex) or bcrypt
I have changed your code... maybe it works. also watch the comments it explains something maybe it helps:
function updateUser ()
{
$current = md5($_POST['cpassword']);
$new = md5($_POST['npassword']);
$newc = md5($_POST['npasswordc']);
// first check if the passwords matches if not why waist the connection
if ($new == $newc) {
$name = $_POST['username'];
connectDB();
// why not checking your pass in the query
// when a result is zero it means there is no match found
$check = mysql_query("SELECT password FROM user WHERE user_name = '{$name}' AND password = '{$current}'") or die(mysql_error());
$result = mysql_fetch_assoc($check);
// You where checking a resource with a string(MD5)?
if (mysql_num_rows($check) == 0) {
?><div id="error">
<?php die('Current password is wrong. Press back to try again.'); ?>
</div><?php
return false;
} else {
// update the query with the ID you got from the check..
// why? because a ID is always unique
$sql = "UPDATE user SET password = '{$new}' WHERE user_id = '{$result['user_id']}'";
execute($sql);
?><div id="error">
<?php echo 'Password Successfully Updated. Back to dashboard';
?></div><?php
return true;
}
} else {
?><div id="error">
<?php echo 'New Password did not match. Press back to try again';
?></div><?php
return false;
}
}